<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Martin Kjellstrand on Medium]]></title>
        <description><![CDATA[Stories by Martin Kjellstrand on Medium]]></description>
        <link>https://medium.com/@madworx?source=rss-8b93919e8075------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*CjWBHaJUGTKOVXRBV6chRA.jpeg</url>
            <title>Stories by Martin Kjellstrand on Medium</title>
            <link>https://medium.com/@madworx?source=rss-8b93919e8075------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 09:08:52 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@madworx/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[SSH might surprise you — in all the wrong ways]]></title>
            <link>https://blog.devops.dev/ssh-might-surprise-you-in-all-the-wrong-ways-a5926d11ff11?source=rss-8b93919e8075------2</link>
            <guid isPermaLink="false">https://medium.com/p/a5926d11ff11</guid>
            <category><![CDATA[openssh]]></category>
            <category><![CDATA[ssh]]></category>
            <category><![CDATA[unix]]></category>
            <category><![CDATA[linux]]></category>
            <category><![CDATA[devops]]></category>
            <dc:creator><![CDATA[Martin Kjellstrand]]></dc:creator>
            <pubDate>Wed, 05 Jul 2023 13:44:29 GMT</pubDate>
            <atom:updated>2023-07-06T17:28:09.016Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>SSH might surprise you — in all the wrong ways</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*feL81a-rHG_jrsZ4MHIvtw.png" /></figure><p>OpenSSH has some very peculiar handling around command line arguments.</p><p>It was only after nearly 23 years of using OpenSSH on an almost daily basis that I encountered this issue.</p><p><strong>TL;DR</strong></p><p>If you just want the short summary, I suggest you skip to “<a href="#249d">A few simple examples where this really bites you</a>” section.</p><p><strong>Background</strong></p><p>A while back I was assisting a mentee with a script to automate some tasks and we were using ssh to execute commands on the remote server.</p><p>I was just feeding him commands off the top of my head without testing them myself, and he got back to me and said that they didn’t work.</p><p>Surely he was mistaken? Turns out, he wasn’t.</p><p>Intrigued? I certainly was; Keep reading.</p><p>Before we dig into the gory details, let’s examine how processes are actually executed and how command line arguments are passed to the respective program.</p><p><strong>Let’s talk about how a program gets executed</strong></p><p>When you type a command in the shell, the following description provides a simplified explanation of the underlying process:</p><ol><li>The shell breaks what you wrote into distinct arguments, observing well-defined rules around what is a unique argument and what isn’t.</li><li>The shell searches the directories specified in the $PATH environment variable to locate the requested program.</li><li>The shell employs the exec family of POSIX system calls (such as execl(), execv(), and others) to execute the desired program. In essence, a system call is a mechanism by which an application solicits the kernel to perform an action on its behalf, and the exec family of system calls are used to execute another program.</li></ol><p>Example:</p><pre>$ figlet foobar ‘bar baz’</pre><p>You shell will search the $PATH environment variable for a program named figlet, and then calls fork() followed by execve() with the arguments /usr/bin/figlet, figlet, foobar and bar baz as show on the below strace output (strace is a Linux-specific application that shows which system calls an application performs, but similar tools exist for other unices):</p><pre>execve(“/usr/bin/figlet”, [“figlet”, “foobar”, “bar baz”], …</pre><p>This output from strace shows us that our shell did a system call to the execve routine in the kernel (In the rest of this article, I will interleave output from invocations of execve() calls with the command line illustrations. If you want to try this out yourself you can use the strace -f -e trace=execve command to observe which calls to execve are actually made, and which arguments are passed to them)</p><p>As you can see, the quotes around “bar baz” are not passed to execve() because they are part of the shell’s parsing process.</p><p>We could have expressed this in a number of functionally equivalent ways using various quoting and expansion primitives, e.g:</p><pre>$ figlet foobar bar\ baz<br>execve(&quot;/usr/bin/figlet&quot;, [&quot;figlet&quot;, &quot;foobar&quot;, &quot;bar baz&quot;], …<br>$ figlet foobar &quot;bar baz&quot;<br>execve(&quot;/usr/bin/figlet&quot;, [&quot;figlet&quot;, &quot;foobar&quot;, &quot;bar baz&quot;], …<br>$ BAZ=&#39;bar baz&#39; figlet foobar &quot;${BAZ}&quot;<br>execve(&quot;/usr/bin/figlet&quot;, [&quot;figlet&quot;, &quot;foobar&quot;, &quot;bar baz&quot;], …</pre><p>As long as we maintain proper quoting, we can nest invocations of sub-shells etc as much as we want, and still get the same result. For example:</p><pre>$ sh -c &#39;sh -c &quot;figlet foobar bar\ baz&quot;&#39;<br>execve(&quot;/usr/bin/sh&quot;, [&quot;sh&quot;, &quot;-c&quot;, &quot;sh -c \&quot;figlet foobar bar\\ baz\&quot;&quot;], …<br>execve(&quot;/usr/bin/sh&quot;, [&quot;sh&quot;, &quot;-c&quot;, &quot;figlet foobar bar\\ baz&quot;], …<br>execve(&quot;/usr/bin/figlet&quot;, [&quot;figlet&quot;, &quot;foobar&quot;, &quot;bar baz&quot;], …</pre><p>In each step the quoting/separating into individual arguments works exactly as expected.</p><blockquote>After some time, the nesting of quotes and escape characters becomes second nature to us, and we seldom devote much thought to it.</blockquote><p>Which is why the next part was so confusing.</p><p><strong>Enter OpenSSH</strong></p><p>The ssh man page says the following in the SYNOPSIS: (I’ve removed some of the options for brevity)</p><blockquote>NAME</blockquote><blockquote>ssh — OpenSSH remote login client</blockquote><blockquote>SYNOPSIS</blockquote><blockquote>ssh [-…] destination [command [argument …]]</blockquote><p>This looks awfully similar to the man page of for example the dash shell:</p><blockquote>NAME</blockquote><blockquote>dash — command interpreter (shell)</blockquote><blockquote>SYNOPSIS</blockquote><blockquote>dash [-aCefnuvxIimqVEbp] [+aCefnuvxIimqVEbp] [-o option_name]<br>[+o option_name] [command_file [argument …]]</blockquote><p>At this point, I’d argue that most people expect ssh to behave in a transparent fashion (i.e. like a regular sub-shell or any other command), and that the command line arguments are passed to the remote shell according to regular shell expansion rules. Much like rsh does; After all — the concept behind the SSH client command line utility was to create a secure drop-in replacement for utilities like rsh, offering enhanced security features. rsh in turn, was an extension to run sh commands on a remote host.</p><p>In other words, we would expect the following commands to be functionally equivalent:</p><pre>$ figlet foobar bar\ baz<br>execve(&quot;/usr/bin/figlet&quot;, [&quot;figlet&quot;, &quot;foobar&quot;, &quot;bar baz&quot;], …<br>$ ssh localhost figlet foobar bar\ baz<br>execve(&quot;/usr/bin/ssh&quot;, [&quot;ssh&quot;, &quot;localhost&quot;, &quot;figlet&quot;, &quot;foobar&quot;, &quot;bar baz&quot;], …<br>execve(&quot;/usr/bin/figlet&quot;, [&quot;figlet&quot;, &quot;foobar&quot;, &quot;bar&quot;, &quot;baz&quot;], …</pre><p>WAT? Apparently our single argument “bar baz” which was passed to ssh as a single argument, was broken up by ssh into two distinct arguments, namely “bar” and “baz”.</p><p>Let’s nest it one level deeper, using standard shell expansion rules:</p><pre>$ sh -c &#39;figlet foobar bar\ baz&#39;<br>execve(&quot;/usr/bin/sh&quot;, [&quot;sh&quot;, &quot;-c&quot;, &quot;figlet foobar bar\\ baz&quot;], …<br>execve(&quot;/usr/bin/figlet&quot;, [&quot;figlet&quot;, &quot;foobar&quot;, &quot;bar baz&quot;], …<br>$ ssh localhost sh -c &#39;figlet foobar bar\ baz&#39;<br>execve(&quot;/usr/bin/ssh&quot;, [&quot;ssh&quot;, &quot;localhost&quot;, &quot;sh&quot;, &quot;-c&quot;, &quot;figlet foobar bar\\ baz&quot;], …<br>execve(&quot;/usr/bin/sh&quot;, [&quot;sh&quot;, &quot;-c&quot;, &quot;figlet&quot;, &quot;foobar&quot;, &quot;bar baz&quot;], …<br>execve(&quot;/usr/bin/figlet&quot;, [&quot;figlet&quot;], …</pre><p>Now surely, we’ve even embedded the “bar baz” argument inside single quotes — no way is ssh messing with that, right?</p><p>Wrong.</p><p>You’ll notice that /usr/bin/sh in the ssh case suddenly was invoked with [“sh”, “-c”, “figlet”, “foobar”, “bar baz”] and not [“sh”, “-c”, “figlet foobar bar\\ baz”] as we would expect.</p><p>Since we can see on the following line, ssh is invoked with properly quoted arguments:</p><pre>execve(&quot;/usr/bin/ssh&quot;, [&quot;ssh&quot;, &quot;localhost&quot;, &quot;sh&quot;, &quot;-c&quot;, &quot;figlet foobar bar\\ baz&quot;], …</pre><p>but we still end up with the wrong arguments executed on the remote server. (In this case, figlet gets called without any arguments, making it seemingly “hang” since it’s expecting input on stdin).</p><p>The ssh manpage vaguely alludes to this behaviour with the following sentence:</p><blockquote>If a command is specified, it will be executed on the remote host instead<br>of a login shell. A complete command line may be specified as command,<br>or it may have additional arguments. If supplied, the arguments will be<br>appended to the command, separated by spaces, before it is sent to the<br>server to be executed.</blockquote><p>The sentence I’m referring to is <em>If supplied, the arguments will be appended to the command, separated by spaces</em>, but to my mind it is very unclear and fails to convey the fact that ssh does its own expansion of command line arguments containing spaces themselves.</p><p><strong>A few simple examples where this really bites you</strong></p><pre>$ ssh localhost &#39;cd /tmp &amp;&amp; pwd&#39;<br>/tmp<br>$ ssh localhost sh -c &#39;cd /tmp &amp;&amp; pwd&#39;<br>/home/mad<br><br>$ ls documentation\ directory<br>readme.txt<br>$ ssh localhost ls documentation\ directory<br>ls: cannot access &#39;documentation&#39;: No such file or directory<br>ls: cannot access &#39;directory&#39;: No such file or directory</pre><p>In conclusion:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*1zki3vyraE8i8yVStGu4dw.jpeg" /><figcaption>WAT</figcaption></figure><p>How anyone could think this was a good idea is beyond me, but at this point I’m going to assume that it was a either unintentional or intentional design decision taken long ago and at this point openssh can’t fix/change it with the risk of breaking existing code and installations.</p><p>Do you have any insights into this? Know the history behind this behavior? Feel like spending a few hours digging through historical openssh releases to uncover the back story behind this?</p><p>I’d love to hear about it!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a5926d11ff11" width="1" height="1" alt=""><hr><p><a href="https://blog.devops.dev/ssh-might-surprise-you-in-all-the-wrong-ways-a5926d11ff11">SSH might surprise you — in all the wrong ways</a> was originally published in <a href="https://blog.devops.dev/">DevOps.dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ChatGPT Ate My Homework]]></title>
            <link>https://medium.com/@madworx/chatgpt-ate-my-homework-d092ada866d4?source=rss-8b93919e8075------2</link>
            <guid isPermaLink="false">https://medium.com/p/d092ada866d4</guid>
            <category><![CDATA[cockroach]]></category>
            <category><![CDATA[go]]></category>
            <category><![CDATA[chatgpt]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[postgresql]]></category>
            <dc:creator><![CDATA[Martin Kjellstrand]]></dc:creator>
            <pubDate>Sat, 03 Jun 2023 17:59:36 GMT</pubDate>
            <atom:updated>2023-06-03T18:00:33.551Z</atom:updated>
            <content:encoded><![CDATA[<p>In the ever-evolving realm of artificial intelligence (AI), surprises and breakthroughs are commonplace.</p><p>Yet, a recent interaction with ChatGPT, left me astonished; Over the past six months, I’ve grown accustomed to leveraging ChatGPT for generating boiler-plate code, answering questions and generating text, but its capabilities surpassed all my expectations when it composed around 90% of a software project I ended up releasing on <a href="https://github.com/madworx/rowdy-crdb-exporter">GitHub</a>.</p><p>More impressively, it managed to orchestrate all the crucial elements for a full-fledged open source project, from setting up CI/CD pipelines to establishing a Code of Conduct, Contributing guide, and Security Policy.</p><p>But let’s not get ahead of ourselves, and let me walk you through my journey.</p><h3>Background</h3><p>This expedition was sparked by my quest to uncover comprehensive insights about our database, particularly <a href="https://www.cockroachlabs.com/">CockroachDB</a>.</p><p>I aimed to discern which tables were occupying the most disk space and which ones were row-heavy.</p><p>This task wasn’t suited for a single, one-off query, as it necessitated a deeper, more refined exploration of temporal trends and patterns for making informed decisions.</p><p>During my investigation into CRDB’s architecture, I discovered several internal tables that could provide the statistics I sought.</p><p>Although Cockroach Labs advised caution against excessive querying, the possibility of gathering meaningful data was enticing.</p><p>What initially seemed like a simple Python coding task quickly escalated into a full-blown experiment as I delegated it to ChatGPT.</p><p>Entrusting ChatGPT with my SQL query, I requested it to formulate a Prometheus exporter.</p><p>The result was quite astonishing: a polished, idiomatic Python script that acted as a Prometheus exporter, that perfectly catered to my needs.</p><p>Tempted by this outcome, I asked for additional features and customizable options.</p><p>In response, ChatGPT rolled out a plethora of functionalities, morphing my basic script into a robust Prometheus exporter. Recognizing the potential utility of such a tool for others, I decided to transition it into an open-source project.</p><h3>Open-Sourcing The Project</h3><p>Open-sourcing a project is not as simple as dumping the code onto a repository. There are certain unwritten standards and guidelines that ensure the quality and accessibility of However, open-sourcing a project is no simple feat. It requires adherence to unwritten standards and guidelines that ascertain the project’s quality and accessibility. Pondering over these complexities, I wondered, “Could I rely on ChatGPT to navigate these intricacies?”</p><p>To my delight, ChatGPT proved its worth once again; It restructured the Python implementation in Go, crafted configuration files for VSCode DevContainers, Docker, and a Makefile to manage the build process.</p><p>ChatGPT managed to implement Makefile targets for diverse platforms, such as x86, ARM, and Windows, while also integrating GitHub Actions for automated testing and release pipelines.</p><p>As it turns out, ChatGPT isn’t just usable for generating boiler plate coding. It grasped the essence of open-source, drafting comprehensive documentation, templates for deploying the service, and even a Security Policy, Code of Conduct, and a Contributing guide, all vital components for fostering a healthy open-source community.</p><p>Approximately eight hours later, I had a complete, open-source-ready project. Without lifting a finger for manual coding, I had a well-structured, adaptable, and well-documented project that would’ve taken me twice as long to create independently.</p><h3>Technical improvements</h3><p>My final test for ChatGPT was to implement support for PostgreSQL, since CockroachDB has the same wire-protocol as PostgreSQL it made sense.</p><p>With no actual input from me, it managed to adapt the CRDB-specific SQL queries and made them compatible with PostgreSQL.</p><p>This entire experience has been a testament to how AI and tools like ChatGPT can amplify human productivity and creativity.</p><p>It not only expedited the development process but also made the journey enjoyable, enabling me to focus on design and strategy instead of being bogged down with syntax.</p><h3>Conclusion</h3><p>This experiment with ChatGPT redefined my understanding of its capabilities; While I’ve so far mostly used it for writing code or crafting business e-mails, this project showed how much more it can do. The role of AI in augmenting human effort is undeniable and tools like ChatGPT are continuously redefining these boundaries.</p><p>All-in-all I had to write some of the code coverage tests myself due to ChatGPT not grasping what I attempted to do, but in summary 90% of what you see in <a href="https://github.com/madworx/rowdy-crdb-exporter">the repository</a> is ChatGPT generated.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TKJmfEI9RlSTcnYaHAC-IA.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d092ada866d4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Measuring Code Coverage in End-to-End Test Scenarios with Golang]]></title>
            <link>https://medium.com/@madworx/measuring-code-coverage-in-end-to-end-test-scenarios-with-golang-3c6c9d8a93ba?source=rss-8b93919e8075------2</link>
            <guid isPermaLink="false">https://medium.com/p/3c6c9d8a93ba</guid>
            <category><![CDATA[go]]></category>
            <category><![CDATA[test-automation]]></category>
            <category><![CDATA[e2e-testing]]></category>
            <dc:creator><![CDATA[Martin Kjellstrand]]></dc:creator>
            <pubDate>Mon, 15 May 2023 18:04:01 GMT</pubDate>
            <atom:updated>2023-05-16T07:20:59.953Z</atom:updated>
            <content:encoded><![CDATA[<p>In the world of software development, it’s a common quest to measure the effects of code coverage when running end-to-end (e2e) tests on a back-end application. Code coverage, a critical metric showing how much of your code is executed during testing, is invaluable for understanding the effectiveness of your tests both in the short term (i.e., how a specific commit affects code coverage) and in the long term (i.e., how the code coverage evolves over time).</p><p>However, the role of code coverage in e2e tests is often misunderstood. Some may argue that code coverage is not as relevant in e2e tests as it is in unit tests. Their rationale usually stems from the belief that e2e tests aim to verify the functionality of the application as a whole, rather than individual pieces of code, as unit tests do.</p><p>Yet, this perspective overlooks an important aspect of e2e tests. By their very nature, they tend to cover more code paths and integrate various components of the application. Therefore, the code coverage obtained from e2e tests provides a more holistic view of the overall system’s robustness and resilience to potential bugs.</p><h3>Technical Approach</h3><p>To achieve our goal of measuring the code coverage of our back-end application during end-to-end (e2e) testing, we’ll follow these steps:</p><ol><li>Start the back-end application.</li><li>Execute a number of e2e tests that interact with the back-end application.</li><li>Measure the code coverage of the back-end application by capturing the paths exercised by the tests.</li></ol><p>However, we run into a hurdle when we consider the typical approach of using the go test command. Our application, like many, relies on settings from a .env file located in the current directory. go test, though, runs tests in a temporary directory, rendering it unable to locate the .env file or any other configuration files that reside in the application&#39;s root directory.</p><h3>A Two-step solution</h3><p>To tackle this challenge, we’ve devised a two-step process:</p><pre>rm -f dist/app<br>go test -c -o dist/app -covermode=count -coverpkg=./... ./cmd/app</pre><p>In the first step, we ensure any existing compiled test binary is removed with rm -f dist/app. This is a preventative measure to ensure that if go test -c encounters a failure (which can surprisingly exit with a status code 0 due to what I believe to be a bug in go test), the outdated binary won’t persist.</p><p>Next, we harness the power of the go test -c command to compile the test binary without executing it. The binary is then output to dist/app, with the coverage mode set to “count,” to enable analysis of all packages in the current directory and subdirectories for coverage.</p><pre>MODE=run-e2e-tests ./dist/app -test.coverprofile=coverage-e2e.out</pre><p>In the second step, we execute the compiled test binary with the MODE environment variable set to run-e2e-tests. The -test.coverprofile=coverage-e2e.out option instructs Go to compile a coverage profile and write it to the coverage-e2e.out file.</p><h3>Initiating the coverage run</h3><p>We create a file, main_test.go, to initiate the coverage run:</p><pre>package main<br>import (<br>	&quot;os&quot;<br>	&quot;testing&quot;<br>)<br><br>func TestE2E(t *testing.T) {<br> if os.Getenv(&quot;MODE&quot;) != &quot;run-e2e-tests&quot; {<br>  t.Skip(&quot;Skipping e2e test&quot;)<br> }<br> main()<br>}</pre><p>This approach gives us flexibility in controlling the test execution based on the environment settings. It ensures that the full application only starts when we explicitly want to measure code coverage during an end-to-end test run, avoiding unnecessary overhead during regular unit tests.</p><h3>Implementing Graceful Shutdown</h3><p>To ensure the backend application shuts down gracefully (i.e., main() returns), we&#39;ll implement a dedicated /shutdown endpoint. The following code snippet illustrates this:</p><pre>if serverKonfig.IsLocal &amp;&amp; os.Getenv(&quot;MODE&quot;) == &quot;run-e2e-tests&quot; {<br>    router.Get(&quot;/shutdown&quot;, func(rw http.ResponseWriter, req *http.Request) {<br>        go func() {<br>            server.Shutdown(context.Background())<br>        }()<br>    })<br>}</pre><p>In the code above, we’re verifying whether we are operating within a local development or a Continuous Integration (CI) environment, and also if we’re currently running in end-to-end test mode.</p><p>While this approach utilizes an HTTP endpoint for the shutdown trigger, alternative implementations could involve IPC, Unix signal(7)s, a drop-in file in a directory, or even predefined timeouts. The method you choose largely depends on your application&#39;s specific requirements and the environment in which it operates.</p><h3>Workflow Execution</h3><ol><li>Start the application with the appropriate parameters and put it into the background: MODE=run-e2e-tests ./dist/app -test.coverprofile=coverage-e2e.out &amp;.</li><li>Proceed to execute the end-to-end tests using external means.</li><li>Trigger the /shutdown endpoint.</li><li>Following this, the application will perform a graceful shutdown, subsequently generating a coverage-e2e.out file.</li></ol><p>After the execution, you can take advantage of common tools like go tool cover or SonarQube to examine the coverage data. These tools help you understand the areas of your code that the tests touched, providing valuable insights into the effectiveness of your tests.</p><h3>Conclusion</h3><p>Measuring code coverage in end-to-end tests can be challenging, especially when your application depends on specific environment settings. But with a methodical process like the one we’ve described — running the application in test mode, executing the tests, then shutting down the application to generate coverage data — you can overcome these challenges.</p><p>Though this requires some initial setup, the insights gained into your code coverage can be extremely useful. It helps identify how well your tests interact with your code, contributing to overall code-base quality. Remember, the end goal is not just about reaching a high coverage percentage, but about building effective tests that improve the reliability and robustness of your application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S7lTLZqdxMzNtWP3_XTbRg.png" /><figcaption>Anthropomorphic gophers writing tests, Image fades out towards the right, into stars in black sky</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3c6c9d8a93ba" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Optimize EC2 Costs for Self-Hosted GitHub Action Runners: A Smart Solution for Small Development…]]></title>
            <link>https://medium.com/cloud-native-daily/optimize-ec2-costs-for-self-hosted-github-action-runners-a-smart-solution-for-development-teams-fb3f31e98bb2?source=rss-8b93919e8075------2</link>
            <guid isPermaLink="false">https://medium.com/p/fb3f31e98bb2</guid>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[ec2-instance]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[github-actions]]></category>
            <dc:creator><![CDATA[Martin Kjellstrand]]></dc:creator>
            <pubDate>Tue, 09 May 2023 10:30:37 GMT</pubDate>
            <atom:updated>2023-05-11T12:28:38.401Z</atom:updated>
            <content:encoded><![CDATA[<h3>Optimize EC2 Costs for Self-Hosted GitHub Action Runners: A Smart Solution for Small Development Teams</h3><h4>A cost-effective solution that leverages AWS EC2 to optimize your self-hosted GitHub Action runners.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Cjg0HovLRqGwuWY7ZgiK-A.png" /></figure><p>Using GitHub’s own runners for building the front- and back-end, running unit tests, and executing end-to-end tests can take considerable time.</p><p>This is especially true for small development teams working in mono-repos, where build times can reach around 20 minutes.</p><p>To address this issue, you can use self-hosted runners with more cores and RAM.</p><p>However, the challenge lies in avoiding high monthly costs for a machine that idles most of the time.</p><p>In this post, we’ll discuss a cost-effective solution that leverages AWS EC2 to optimize your self-hosted GitHub Action runners.</p><h3>Overview</h3><p>The solution involves creating an IAM role for starting and stopping EC2 instances, using a GitHub-hosted runner to start the dedicated build host only when necessary, and automating the shutdown of idle runners with a cron job.</p><p>This approach ensures that you only pay for the resources you actually use, saving you money without sacrificing performance.</p><p>This strategy can be particularly beneficial for small development teams, with a single dedicated build host being sufficient for most use cases.</p><h3>Simplified savings calculation</h3><p>At the time of writing, the hourly cost for a c6i.2xlarge instance is $0.3880, which amounts to approximately $300 per month.</p><p>However, with the solution outlined in this article and taking into account the following assumptions:</p><ul><li>10 commits per day on average (*)</li><li>A 20-day work month</li><li>Each commit initiating a full start/stop cycle</li><li>The build server shutting down after 30 minutes of starting</li></ul><p>The estimated monthly cost is reduced to under $40.</p><p>This equates to a significant savings of around 87% compared to the expense of running the instance continuously.</p><p>In addition to this, the “commits per day on average” may be skewed too high, and not every commit will lead to a full start/stop cycle, so the actual savings will likely be even greater.</p><p>(*) To calculate the average number of commits per day in your repository, use the following one-liner: git log --format=&quot;%ad&quot; --date=short | sort | uniq -c | awk &#39;{s += $1; n++;} END {print s/n}&#39; (Note: This does not take into account days for where there are no commits at all.)</p><h3>Setting Up a GitHub Action Runner Instance on EC2</h3><p>Before proceeding with the IAM setup, you’ll need to set up a GitHub Action runner instance on EC2. While a detailed explanation of this process is outside the scope of this article, you can follow the official GitHub documentation for installing a self-hosted runner on your EC2 instance:</p><p><a href="https://docs.github.com/en/actions/hosting-your-own-runners/adding-self-hosted-runners">GitHub: Adding self-hosted runners</a></p><p>Once you’ve completed the installation and the runner is registered as “idle” in your GitHub Actions settings, you can continue with the remaining steps in this article.</p><h3>Set Up an IAM Role</h3><p>First, create a dedicated IAM role for this operation, which we’ll call builder-bob. Attach the following JSON permission policy to grant the necessary permissions for starting and stopping EC2 instances, replacing 123456789abcdef01 with your build host instance-id, and 098765432109 with your AWS account-id.</p><pre>{<br>    &quot;Version&quot;: &quot;2012-10-17&quot;,<br>    &quot;Statement&quot;: [<br>        {<br>            &quot;Effect&quot;: &quot;Allow&quot;,<br>            &quot;Action&quot;: [<br>                &quot;ec2:StartInstances&quot;,<br>                &quot;ec2:StopInstances&quot;<br>            ],<br>            &quot;Resource&quot;: &quot;arn:aws:ec2:eu-central-1:098765432109:instance/i-123456789abcdef01&quot;<br>        }<br>    ]<br>}</pre><h3>Configure Your GitHub Actions Workflow</h3><p>Next, set up your GitHub Actions workflow file to use a GitHub-hosted runner for starting the dedicated build host only when needed. This prevents the build host from running continuously and accumulating unnecessary costs.</p><pre>name: example<br>on: push<br><br>jobs:<br>    # This will use a Github hosted runner to start our dedicated build host<br>    start_builder:<br>        runs-on: ubuntu-20.04<br>        steps:<br>            - name: Set up AWS CLI<br>              uses: aws-actions/configure-aws-credentials@v2<br>              with:<br>                  aws-access-key-id: ${{ secrets.AWS_ACCESS_KEY_ID }}<br>                  aws-secret-access-key: ${{ secrets.AWS_SECRET_ACCESS_KEY }}<br>                  aws-region: ${{ secrets.AWS_REGION }}<br>            - name: Start self-hosted builder<br>              run: aws ec2 start-instances --instance-ids i-123456789abcdef01 || true<br>    integration_tests:<br>        runs-on: self-hosted<br>        needs: startbuilder<br>        steps:<br>          - name: Your build / test commands here<br>            run: make -j</pre><p>Lastly, implement a cron job to automate the shutdown of idle runners. This will check the server’s uptime and the age of the most recent job folder. If the server has been up for more than 20 minutes and no recent jobs are found, it will shut down automatically.</p><p>Here’s the cron job script:</p><pre>* * * * * root find /proc -maxdepth 1 -name uptime -mmin +20 -exec sh -c &#39;find /opt/github-runner/_work -maxdepth 0 -type d ! -mmin -20 -execdir /sbin/poweroff \;&#39; \;</pre><p>The find command checks if /proc/uptime was modified more than 20 minutes ago (its mtime is set to when the server booted). If true, another find invocation checks for new runner jobs in the last 20 minutes. If no recent jobs are found, it issues a /sbin/poweroff to shut down the server.</p><h3>Conclusion</h3><p>By implementing these strategies, you can improve your build times and save on EC2 costs, making your development process more efficient and cost-effective.</p><h4>Learn More:</h4><ul><li><a href="https://gethelios.dev/blog/5-microservices-challenges-and-blindspots-for-developers/?utm_source=medium&amp;utm_medium=content&amp;utm_campaign=cloudnativedaily">5 Microservices Challenges and Blindspots for Developers</a></li><li><a href="https://gethelios.dev/blog/testing-microservices-with-helios/?utm_source=medium&amp;utm_medium=content&amp;utm_campaign=cloudnativedaily">Testing Microservices - Trace Based Integration Testing Example</a></li><li><a href="https://gethelios.dev/blog/opentelemetry-tracing/?utm_source=medium&amp;utm_medium=content&amp;utm_campaign=cloudnativedaily">OpenTelemetry Tracing: Everything you need to know</a></li><li><a href="https://gethelios.dev/blog/evaluating-distributed-tracing-tools-a-guide/?utm_source=medium&amp;utm_medium=content&amp;utm_campaign=cloudnativedaily">Evaluating distributed tracing tools: A guide</a></li><li><a href="https://javascript.plainenglish.io/9-best-distributed-tracing-tools-for-developers-185e415b7101">9 Best Distributed Tracing Tools for Developers</a></li><li><a href="https://python.plainenglish.io/opentelemetry-in-python-a-full-guide-98fef9b500a1">OpenTelemetry in Python — A Full Guide</a></li><li><a href="https://gethelios.dev/blog/evaluating-distributed-tracing-tools-a-guide/?utm_source=medium&amp;utm_medium=content&amp;utm_campaign=cloudnativedaily">Evaluating distributed tracing tools: A guide</a></li><li><a href="https://gethelios.dev/blog/using-distributed-tracing-to-identify-bottlenecks-in-your-app-flows/?utm_source=medium&amp;utm_medium=content&amp;utm_campaign=cloudnativedaily">Using distributed tracing to identify bottlenecks in your app flows</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fb3f31e98bb2" width="1" height="1" alt=""><hr><p><a href="https://medium.com/cloud-native-daily/optimize-ec2-costs-for-self-hosted-github-action-runners-a-smart-solution-for-development-teams-fb3f31e98bb2">Optimize EC2 Costs for Self-Hosted GitHub Action Runners: A Smart Solution for Small Development…</a> was originally published in <a href="https://medium.com/cloud-native-daily">Cloud Native Daily</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>