<?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[TeamSnap Engineering - Medium]]></title>
        <description><![CDATA[Sharing our learnings and challenges as we work on taking the work out of play! If you’re interested in what we’re working on, come join us https://jobs.lever.co/teamsnap! - Medium]]></description>
        <link>https://medium.com/teamsnap-engineering?source=rss----c8de247e26d7---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>TeamSnap Engineering - Medium</title>
            <link>https://medium.com/teamsnap-engineering?source=rss----c8de247e26d7---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 25 Nov 2026 00:30:28 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/teamsnap-engineering" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Automating API Test Coverage with Optic]]></title>
            <link>https://medium.com/teamsnap-engineering/automating-api-test-coverage-with-optic-f771b644dc63?source=rss----c8de247e26d7---4</link>
            <guid isPermaLink="false">https://medium.com/p/f771b644dc63</guid>
            <category><![CDATA[test-automation]]></category>
            <category><![CDATA[test-coverage]]></category>
            <category><![CDATA[api-testing]]></category>
            <dc:creator><![CDATA[Natalie Kramer]]></dc:creator>
            <pubDate>Tue, 23 Jul 2024 17:42:34 GMT</pubDate>
            <atom:updated>2024-07-23T17:42:34.697Z</atom:updated>
            <content:encoded><![CDATA[<p>API tests are widely adopted in development teams, ensuring the functionality and reliability of backend services, providing rapid feedback, and detecting regressions early to enhance software quality. I’ve been a part of many debates that ask: why do you need API tests if you have good unit test coverage or good end-to-end test coverage? The answer lies in the different levels of testing each approach provides. Unit tests focus on individual components, while E2E tests evaluate the entire application flow. API tests, however, validate the interactions between different components or services, ensuring that integration points work as expected. They offer a faster feedback loop, better isolation of issues, and coverage of a wide range of input and output conditions, including edge cases and error handling.</p><p>But how do you know how many of your APIs are covered by a test? While unit tests have established methods to measure coverage (like line, branch, and statement coverage) with various integration tools, measuring API test coverage lacks a standardized approach. At TeamSnap, we started with a spreadsheet. Yes, I know what you’re thinking — a spreadsheet… We exported all of our APIs into a document and started marking the ones covered with tests as “x”. This method worked well until our teams started adding or updating new endpoints, which, for a SaaS company, you can imagine how often this happened. So, we faked a smile and tried our best to keep this spreadsheet up to date, knowing it would cover at least 75% of the cases.</p><p>In this article, I’ll walk you through how we transitioned from this manual process to implementing Optic API Test Coverage, providing a modern, automated solution for tracking and managing our API test coverage.</p><h3>Why does test coverage matter?</h3><p>Aside from nudging your development teams to add more tests, test coverage is crucial for several reasons:</p><ol><li><strong>Improves Confidence in Releases</strong>: Boosts confidence in the reliability and stability of new releases, knowing that they are backed by comprehensive test coverage.</li><li><strong>Visibility into Coverage Gaps</strong>: Identifies which parts of the API are not covered by tests, allowing you to address these gaps and ensure comprehensive coverage.</li><li><strong>Informed Decision Making</strong>: Helps stakeholders make data-driven decisions about where to focus development and testing efforts.</li><li><strong>Benchmarking and Goals</strong>: Supports benchmarking against industry standards and setting achievable goals for improving API test coverage.</li></ol><p>Given the significance of test coverage, we opted for <a href="https://www.useoptic.com/docs">Optic</a> as our tool to integrate with our test suites. Optic is an API development tool that allows you to keep your OpenAPI docs up to date, catch breaking changes, review API changes and improve API designs. At TeamSnap, we leverage Optic’s test runner to generate test coverage reports against our OpenAPI specs, verifying that the API’s runtime behavior aligns with its documented specification. We run our Optic test coverage report as a pull request check in our build pipeline in order to continuously measure our test coverage.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*XzhCIWU3SXnw_Anz" /></figure><h3>Tooling</h3><p><a href="https://jestjs.io/"><strong>Jest</strong></a> is a JavaScript test framework that we use to write our API tests.</p><ul><li>You don’t need Jest specifically to use Optic; other API test frameworks should also be compatible with it.</li><li>Several of our backend services are node services, and having the same testing stack simplifies the development process. If you’re a fan of Node/Typescript, come join!</li></ul><p><a href="https://www.useoptic.com/docs"><strong>Optic</strong></a> is an API development tool we use to generate test coverage reports.</p><p><a href="https://swagger.io/specification/"><strong>OpenAPI</strong></a> is a standard format for defining the structure and syntax of REST APIs. This is required in order to use Optic.</p><ul><li>At TeamSnap, all of our OpenAPI docs are posted internally.</li></ul><p><a href="https://github.com/marketplace/actions/add-pr-comment"><strong>Add PR Comment</strong></a> is a GitHub action that posts a customizable comment to a pull request.</p><h3>Details</h3><p>When running API tests normally, you make a request to the server and verify the response. With some slight configuration changes to your test suite, Optic captures the network traffic by using a reverse proxy to intercept the requests.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*M7uDCxgYr00ExPsy" /><figcaption>Image Credit: <a href="https://www.useoptic.com/docs/verify-openapi">Optic Labs Corporation</a></figcaption></figure><h3>Step 1</h3><p>In order to run our tests against this proxy layer, we added a new file called optic.yml.</p><pre>capture:<br> openapi.yml:<br>   Server:<br>     # The url where your server can be reached once running.<br>     url: https://api.example.com/<br>   requests:<br>     run:<br>       # The command that will generate traffic to the Optic proxy.<br>       command: yarn test:api<br>       # The name of the environment variable injected into the env of the command that contains the address of the Optic proxy.<br>       proxy_variable: OPTIC_PROXY</pre><p><strong>Glossary:</strong></p><ol><li><strong>openapi.yml:</strong> file path to the OpenAPI spec for your service.</li><li><strong>url:</strong> this is the url for your API.</li><li><strong>command:</strong> this is the command that you use to run your API tests.</li><li><strong>proxy_variable:</strong> you will replace the url in your test suite with OPTIC_PROXY.</li></ol><h3>Step 2</h3><p>Next, we replaced the base url for our API tests with process.env.OPTIC_PROXY. Here’s how that would look in a test:</p><p><strong>Original:</strong></p><pre>const request = require(&#39;supertest&#39;);<br><br>describe(&#39;GET /api/hello&#39;, () =&gt; {<br>   it(&#39;should return a JSON object with message &quot;Hello, World!&quot;&#39;, async () =&gt; {<br>       const url = &#39;https://api.example.com&#39;;<br>       const response = await request(url).get(&#39;/api/hello&#39;);;<br>       expect(response.status).toBe(200);<br>       expect(response.body).toEqual({ message: &#39;Hello, World!&#39; });<br>   });<br>});</pre><p><strong>New:</strong></p><pre>const request = require(&#39;supertest&#39;);<br><br>describe(&#39;GET /api/hello&#39;, () =&gt; {<br>   it(&#39;should return a JSON object with message &quot;Hello, World!&quot;&#39;, async () =&gt; {<br>       const url = process.env.OPTIC_PROXY;<br>       const response = await request(url).get(&#39;/api/hello&#39;);<br>       expect(response.status).toBe(200);<br>       expect(response.body).toEqual({ message: &#39;Hello, World!&#39; });<br>   });<br>});</pre><p>You’ll notice the only difference here is the URL. By setting process.env.OPTIC_PROXY as the URL for the test, you target the Optic proxy layer to intercept the HTTP request.</p><h3>Step 3</h3><p>Time to run your tests! From the command line:</p><pre>yarn dlx @useoptic/optic capture openapi.yml</pre><p><strong>Note:</strong> openapi.yml refers to the file path for the OpenAPI spec. Yours may look different.</p><p>Here’s what the output will look like:</p><pre>✓ Finished running requests<br>- GET /api<br>  ✓ GET /api<br>    ✓ 200 response<br><br>- GET /api/hello<br>  ✓ GET /api/hello<br>    ✓ 200 response<br>  ...and 1 endpoint that did not receive traffic<br> <br>66.7% coverage of your documented operations. All requests matched a documented path (2 total requests)</pre><h3>Reporting</h3><p>When introducing tools like these, it’s crucial to make them highly visible and user-friendly. We had two primary goals for reporting this type of test coverage:</p><ol><li><strong>PR Comments</strong>: Notify the development team of the current test coverage status by providing a detailed PR comment with each change.</li><li><strong>Historical Reports</strong>: Generate reports that track test coverage over time, allowing us to monitor whether our coverage is improving or declining.</li></ol><h3>PR Comments</h3><p>We added 3 new steps to our GitHub actions file: run the test coverage report, format the test coverage details, and finally, post the PR comment with the test coverage results.</p><pre>- name: Run Test Coverage Report<br>  id: test_coverage<br>  run: |<br>    yarn test:api:coverage &gt; ./optic-test-output.txt 2&gt;&amp;1 || true<br>    echo &quot;Created the test coverage report&quot;<br><br>    # Extract the test coverage information into a new file<br>    awk &#39;/✔ Finished running requests/{flag=1; next} flag&#39; ./optic-test-output.txt &gt;&gt; ./extracted-output.txt<br>    echo &quot;Parsed the test coverage report into ./extracted-output.txt&quot;<br>    sed -i &#39;/New endpoints are only added in interactive mode. Run .* to add new endpoints/d&#39; ./extracted-output.txt<br>    echo &quot;Removed the interactive mode message&quot;<br><br>- name: Format Test Coverage Details<br>  run: |<br>    # Read the extracted output<br>    extracted_output=$(&lt;./extracted-output.txt)<br><br>    # Separate the coverage summary from the details<br>    summary=$(echo &quot;$extracted_output&quot; | awk &#39;/^[0-9]+(\.[0-9]+)?% coverage of your documented operations/{print}&#39;)<br>    details=$(echo &quot;$extracted_output&quot; | awk &#39;!/^[0-9]+(\.[0-9]+)?% coverage of your documented operations/{print}&#39;)<br><br>    # Format the details<br>    formatted_details=&quot;&quot;<br>    while IFS= read -r line; do<br>      if [[ $line =~ ^- ]]; then<br>        formatted_details+=&quot;\n$line\n&quot;<br>      else<br>        formatted_details+=&quot;  $line\n&quot;<br>      fi<br>    done &lt;&lt;&lt; &quot;$details&quot;<br><br>    # Reconstruct the formatted output<br>    formatted_output=&quot;# API Test Coverage Report\n\n&lt;details&gt;&lt;summary&gt;Test Coverage Details&lt;/summary&gt;\n\n\`\`\`\n$formatted_details\`\`\`\n&lt;/details&gt;\n\n$summary\n&quot;<br>    echo -e &quot;$formatted_output&quot; &gt; ./formatted-output.txt<br><br>- name: Post PR Comment for Test Coverage<br>  uses: mshick/add-pr-comment@v2<br>  with:<br>    repo-token: ${{ secrets.GITHUB_TOKEN }}<br>    allow-repeats: true<br>    message-path: |<br>      ./formatted-output.txt   </pre><p>Here’s how that looks as a PR comment:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/826/0*enesNqCEZroLogJw" /></figure><h3>Historical Reports</h3><p>In order to create a historical report of our test coverage, we store the test coverage data in a central database and use a data analytics dashboard tool to create historical reports. This has helped us track trends, identify areas for improvement, and make data-driven decisions to enhance the overall quality and reliability of our software. Here’s what this looks like as a time series line chart:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/974/0*H6dmLDlrPJOHiAf0" /><figcaption>Each line represents a different service</figcaption></figure><h4>Important Considerations:</h4><ol><li>Optic measures test coverage against every documented path in your OpenAPI spec. So make sure you add tests for those non-happy paths! (401, 403, 404, etc.)</li><li>When analyzing historical reports, it is important to compare test coverage data with the total number of test cases over time. An increase in test coverage resulting from the removal of endpoints or paths paints a different picture than an increase due to the addition of new tests.</li><li>Make sure your OpenAPI specs are up-to-date!</li></ol><h3>Conclusion</h3><p>Implementing Optic API Test Coverage at TeamSnap has allowed us to move out of the dark ages of spreadsheets and into a modern, automated approach to tracking and managing our API test coverage. By integrating Optic into our testing framework, we validate API behaviors against documented specifications, gaining crucial insights into our test coverage effectiveness. This approach supports informed decision-making, helps prioritize development efforts, and fosters continuous improvement in software quality. The PR comments and historical reports enable us to continuously monitor our test coverage and quality, ensuring that we consistently deliver reliable, high-quality software for our customers.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f771b644dc63" width="1" height="1" alt=""><hr><p><a href="https://medium.com/teamsnap-engineering/automating-api-test-coverage-with-optic-f771b644dc63">Automating API Test Coverage with Optic</a> was originally published in <a href="https://medium.com/teamsnap-engineering">TeamSnap Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Properly Running Kubernetes Jobs with Sidecars in 2024 (K8s 1.28+)]]></title>
            <link>https://medium.com/teamsnap-engineering/properly-running-kubernetes-jobs-with-sidecars-in-2024-k8s-1-28-ad9b51d17d50?source=rss----c8de247e26d7---4</link>
            <guid isPermaLink="false">https://medium.com/p/ad9b51d17d50</guid>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[cronjob]]></category>
            <category><![CDATA[sidecar]]></category>
            <dc:creator><![CDATA[Steven Aldinger]]></dc:creator>
            <pubDate>Thu, 14 Mar 2024 01:07:10 GMT</pubDate>
            <atom:updated>2024-03-14T01:07:10.310Z</atom:updated>
            <content:encoded><![CDATA[<p>Kubernetes has been a great orchestrator of Jobs and CronJobs for over <a href="https://kubernetes.io/blog/2017/09/kubernetes-18-security-workloads-and/#spotlight-on-workload-support">half a decade now</a>, but if you had a need for running proxy containers or other secondary containers alongside the job, <a href="https://medium.com/teamsnap-engineering/properly-running-kubernetes-jobs-with-sidecars-ddc04685d0dc">running things properly</a> took a bit of work and decision-making to handle gracefully.</p><p>This article introduces the easiest way to run Jobs with sidecars using the latest Kubernetes features, and has a <a href="https://github.com/stevenaldinger/k8s-cronjobs-with-sidecars/tree/main">complementary repository</a> with complete example manifests you can try in your own cluster. The repository contains all the examples for earlier versions of K8s as well, so make sure to focus on <a href="https://github.com/stevenaldinger/k8s-cronjobs-with-sidecars/blob/main/manifests/cronjob.sidecar.success.yaml">the cronjob.sidecar.*.yaml examples</a>.</p><h3>Table of Contents</h3><ol><li><a href="#c6e9">What are Sidecars and Why is This a Challenge?</a></li><li><a href="#be1c">Past Solutions and Caveats</a></li><li><a href="#e5a7">Native Sidecar Containers in Kubernetes v1.28+</a></li><li><a href="#0ce8">Using Native Sidecar Containers</a></li><li><a href="#ca1a">Do they Work?</a></li><li><a href="#b27d">Conclusion</a></li></ol><h3>What are Sidecars and Why is This a Challenge?</h3><p>Sidecars are containers running in the same pod as an application container or some other primary container that generally play a supporting role like proxying or helping with observability.</p><p>Even though sidecars have been a common and accepted concept used by the Kubernetes community for quite some time now, Kubernetes itself has never been aware of which containers you consider sidecars, or which container you consider to be your primary container. That lack of awareness has meant that you need to manage part of the sidecar life cycle yourself.</p><p>The consequences of not handling sidecar shutdown properly can include situations like Jobs stalling indefinitely after completing without ever being marked as successful (generally leading to a timeout and the appearance of failed runs), or CronJobs creating an ever-growing number of pods that cost a fortune or eat up all your cluster’s resources.</p><h3>Past Solutions and Caveats</h3><p>Two common solutions are to <a href="https://medium.com/teamsnap-engineering/properly-running-kubernetes-jobs-with-sidecars-ddc04685d0dc#e8c4">use pkill to kill the sidecar container’s process</a>, or to <a href="https://medium.com/teamsnap-engineering/properly-running-kubernetes-jobs-with-sidecars-ddc04685d0dc#0055">mount a shared volume in each of the containers</a> and have a script wrap the sidecar process that can watch for “success” or “failure” to be written to a file and use that as a signal to shut the container down with a matching exit code.</p><p>The pkill strategy can work with any sidecar, but it can require running the primary container as root or overriding the user that the sidecar runs as, and it requires pkill to be installed as a dependency in the primary container.</p><p>The shared volume mount strategy can work with any container that has a shell available, but it requires overriding the sidecar’s entry point and adding relatively complex logic to both containers’ entry points to handle shutting things down properly.</p><p>Regardless of the strategy, managing the containers like this adds complexity and room for error, and it still lacks the ability to control the startup order of the containers for common cases like ensuring the database proxy container has started up before running the application container.</p><h3>Native Sidecar Containers in Kubernetes v1.28+</h3><p>Kubernetes describes the previous types of solutions in <a href="https://kubernetes.io/blog/2023/08/25/native-sidecar-containers/#how-did-users-get-sidecar-behavior-before-1-28">their release article</a> and lumps the ones I’m talking about here into a common category…</p><blockquote><strong>Lifetime of sidecar equal to Pod lifetime</strong>: Use a main container that runs alongside your workload containers in the Pod. This method doesn’t give you control over startup order, and lets the sidecar container potentially block Pod termination after the workload containers exit.</blockquote><p>…and then goes on to brag about the new feature.</p><blockquote>The built-in sidecar feature solves for the use case of having a lifetime equal to the Pod lifetime and has the following additional benefits:</blockquote><blockquote>Provides control over startup order</blockquote><blockquote>Doesn’t block Pod termination</blockquote><p>Here’s a diagram of how things have worked up until now, where we want sidecar behavior, and we talked about one of the containers as a sidecar, but there was no way to indicate to Kubernetes that a container in the pod was a sidecar or a primary container, they’re both just regular containers in the pod.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/281/1*s7lBoVR1KnC2Pc53-6_OhA.jpeg" /><figcaption>Kubernetes CronJob Overview (before 1.28)</figcaption></figure><p>In Kubernetes v1.28, with the new <a href="https://kubernetes.io/docs/concepts/workloads/pods/sidecar-containers/">Sidecar Containers</a> alpha feature, you can declare init containers in a special way where they’re treated as actual sidecars. Kubernetes v1.29, which is available in GKE’s regular channel but not the <a href="https://cloud.google.com/kubernetes-engine/docs/release-notes#stable-channel_1">stable channel</a> quite yet, has the sidecar feature in beta, and it is available by default at that point in any GKE clusters. Based on Google’s <a href="https://cloud.google.com/kubernetes-engine/docs/concepts/release-channels">docs for the release channels</a>, we should expect this feature to be available in stable clusters any day now.</p><p>This new sidecar feature lets us control the startup order of the containers, as well as avoid all of the caveats we had to choose between historically.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/281/1*igipYEAUgkI01gVHsOqZSg.png" /><figcaption>Kubernetes CronJob Overview (1.28+)</figcaption></figure><p>It’s not particularly intuitive to configure or obvious if you’re not told the behavior, but just by moving our supporting containers from the containers stanza to the initContainers stanza, and then ensuring restartPolicy: Always is set for those containers (that’s the real secret), we unlock native sidecars. This is a one-size fits all solution and results in simpler and more secure Kubernetes manifests and Dockerfiles (depending on the strategy you chose previously) since you no longer have to handle the concern yourself.</p><h3>Using Native Sidecar Containers</h3><p>Here’s an example from <a href="https://medium.com/teamsnap-engineering/properly-running-kubernetes-jobs-with-sidecars-ddc04685d0dc">my original article</a>, updated to use the new pattern. haproxy is configured in the initContainers section and given a restartPolicy of Always. That’s all you have to do for things to work properly with the new feature.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/54260f4c15c94bac013b8203173e65d5/href">https://medium.com/media/54260f4c15c94bac013b8203173e65d5/href</a></iframe><p>To appreciate the simplicity of this more, we can compare <a href="https://github.com/stevenaldinger/k8s-cronjobs-with-sidecars/blob/main/manifests/cronjob.pkill.success.yaml">an example of an older solution</a> with <a href="https://github.com/stevenaldinger/k8s-cronjobs-with-sidecars/blob/main/manifests/cronjob.sidecar.success.yaml">the native sidecar solution</a>. Here’s a handful of steps you’d need to take to migrate from the old strategy to native containers:</p><ol><li>remove securityContext runAs config</li><li>remove shareProcessNamespace config</li><li>remove crazy shell script logic that overrides and wraps the original command</li><li>remove procps (pkill) install from the Dockerfile</li></ol><h3>Do they Work?</h3><p>Here’s the response from a kubectl describe on a <a href="https://github.com/stevenaldinger/k8s-cronjobs-with-sidecars/blob/main/manifests/cronjob.sidecar.success.yaml">job pod that’s using the sidecar feature</a>. Note that the sidecar, haproxy, started at 19:55:00, and then the primary container started at 19:55:01 and finished within the same second (still at 19:55:01), before the haproxy container finally finishes at 19:55:02, demonstrating ordered startup, and that the sidecar was available throughout the primary containers lifetime.</p><pre>Name:             successful-cron-sidecar-28471855-29gr9<br>Start Time:       Sun, 18 Feb 2024 19:55:00 -0700<br>Status:           Succeeded<br>Init Containers:<br>  haproxy:<br>    State:          Terminated<br>      Reason:       Completed<br>      Exit Code:    0<br>      Started:      Sun, 18 Feb 2024 19:55:00 -0700<br>      Finished:     Sun, 18 Feb 2024 19:55:02 -0700<br>    Ready:          False<br>    Restart Count:  0<br>Containers:<br>  primary:<br>    Command:<br>      /bin/bash<br>      -c<br>    Args:<br>      echo &quot;Pretend this is real logic&quot;<br>    State:          Terminated<br>      Reason:       Completed<br>      Exit Code:    0<br>      Started:      Sun, 18 Feb 2024 19:55:01 -0700<br>      Finished:     Sun, 18 Feb 2024 19:55:01 -0700<br>    Ready:          False<br>    Restart Count:  0</pre><p>Looking at an <a href="https://github.com/stevenaldinger/k8s-cronjobs-with-sidecars/blob/main/manifests/cronjob.sidecar.failure.yaml">intentionally failing job</a> is also interesting. This job was configured with a backoff limit of 2, and you can see the Restart Count of the primary container reaching 2 in the following snippet as it sits in Terminated state. The pod Status is Terminating already, even though the haproxy container is still Running. The Events at the very bottom of the snippet show that haproxy is about to be stopped now that the primary container has reached its backoff limit and the job is considered a failure.</p><p>Native sidecars work!</p><pre>Name:                      failing-cron-sidecar-28471854-tgl9m<br>Start Time:                Sun, 18 Feb 2024 19:54:00 -0700<br>Status:                    Terminating (lasts &lt;invalid&gt;)<br>Init Containers:<br>  haproxy:<br>    State:          Running<br>      Started:      Sun, 18 Feb 2024 19:54:01 -0700<br>    Ready:          True<br>    Restart Count:  0<br>Containers:<br>  primary:<br>    Command:<br>      /bin/bash<br>      -c<br>    Args:<br>      cat /not/a/real/file/so/this/will/error<br>    State:          Terminated<br>      Reason:       Error<br>      Exit Code:    1<br>      Started:      Sun, 18 Feb 2024 19:54:22 -0700<br>      Finished:     Sun, 18 Feb 2024 19:54:22 -0700<br>    Ready:          False<br>    Restart Count:  2<br>Events:<br>  Type     Reason     Age               From               Message<br>  ----     ------     ----              ----               -------<br>  Normal   Pulled     24s               kubelet            Container image &quot;haproxy:2.6&quot; already present on machine<br>  Normal   Created    24s               kubelet            Created container haproxy<br>  Normal   Started    23s               kubelet            Started container haproxy<br>  Normal   Pulled     2s (x3 over 23s)  kubelet            Container image &quot;ubuntu:22.04&quot; already present on machine<br>  Normal   Created    2s (x3 over 23s)  kubelet            Created container primary<br>  Normal   Started    2s (x3 over 23s)  kubelet            Started container primary<br>  Warning  BackOff    1s (x4 over 21s)  kubelet            Back-off restarting failed container primary in pod failing-cron-sidecar-28471854-tgl9m_default(3242ba44-2153-4818-863b-b8117941b0bf)<br>  Normal   Killing    0s                kubelet            Stopping container haproxy</pre><h3>Conclusion</h3><p>The new sidecar feature in Kubernetes makes it painless to run Jobs and CronJobs with sidecars. The caveats and complexities we used to have to choose between can all be deleted and replaced with this feature, although it’s not recommended that you use it in it’s alpha state, so make sure you’re on Kube 1.29+ before you switch over (and even then, be aware its still a beta feature).</p><p>You can use the examples in the complementary repo to test <a href="https://github.com/stevenaldinger/k8s-cronjobs-with-sidecars/blob/main/manifests/cronjob.sidecar.failure.yaml">failure</a> and <a href="https://github.com/stevenaldinger/k8s-cronjobs-with-sidecars/blob/main/manifests/cronjob.sidecar.success.yaml">success</a> conditions using this new native sidecar strategy.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ad9b51d17d50" width="1" height="1" alt=""><hr><p><a href="https://medium.com/teamsnap-engineering/properly-running-kubernetes-jobs-with-sidecars-in-2024-k8s-1-28-ad9b51d17d50">Properly Running Kubernetes Jobs with Sidecars in 2024 (K8s 1.28+)</a> was originally published in <a href="https://medium.com/teamsnap-engineering">TeamSnap Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Enhancing API Integration Testing: Leveraging GitHub’s Repository Dispatch Action]]></title>
            <link>https://medium.com/teamsnap-engineering/enhancing-api-integration-testing-leveraging-githubs-repository-dispatch-action-2c70d788c955?source=rss----c8de247e26d7---4</link>
            <guid isPermaLink="false">https://medium.com/p/2c70d788c955</guid>
            <category><![CDATA[backends-for-frontends]]></category>
            <category><![CDATA[automated-testing]]></category>
            <category><![CDATA[api-testing]]></category>
            <category><![CDATA[github-actions]]></category>
            <dc:creator><![CDATA[Natalie Kramer]]></dc:creator>
            <pubDate>Fri, 23 Feb 2024 19:19:11 GMT</pubDate>
            <atom:updated>2024-02-23T19:19:11.575Z</atom:updated>
            <content:encoded><![CDATA[<p>Whenever I pack for a trip, I carefully select the items I’ll need, chosen for the specific destination I will be visiting. However, if the weather forecast changes, I may need to adjust my plans and pack different items to make sure I’m prepared for the conditions. This adaptability is key in ensuring a smooth and enjoyable trip. The same principle applies to layered architecture. At TeamSnap, we are strong advocates for the backend for frontend (BFF) architecture pattern, which allows us to adapt and tailor our backend services to meet the specific needs of our frontend applications. We have a wide range of products we support; a mobile application (iOS and Android), a tournaments management offering, a team management tool and a club and league platform (to name a few). This approach is particularly useful because it allows us to optimize performance and user experience across all our offerings, ensuring that each product is finely tuned to its intended audience.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3zb758sZHXhsuEYaLbfYwg.png" /><figcaption>Navigating downstream dependencies of backend services in the backend for frontend (BFF) pattern</figcaption></figure><p>There are many benefits to using the BFF pattern, like simplified development and better scalability, but one drawback is the complexity it adds to testing. For example, if I make changes to my backend service, I want to know that those changes did not cause any regressions in our BFF layer. This becomes especially important when you have multiple BFF layers that point to shared backend services. Testing the BFF layer ensures that the frontend applications continue to function correctly and that any changes to the backend do not negatively impact the user experience. After all, it’s all about the customer, the customer, the customer!</p><p>In this article, I’m going to explain how we mitigated that risk in order to deploy our backend changes with more confidence.</p><h3>Testing Strategy</h3><p>First, I’ll explain what types of automated tests we have in our backend and BFF repositories and how those tests get run.</p><p>Each BFF and backend service have a test suite of API integration tests that live alongside the code. Each time we deploy code changes to our testing (staging) environment, we use GitHub Actions to run the automated API tests against that staging environment. Our development team receives instant feedback on their code changes through a comment on their pull request and a Slack message, indicating whether their tests passed or failed. If any of the tests fail, developers debug and fix their code before deploying again to the staging environment. This process repeats itself until all tests pass and developers get the green light to deploy their code to production. This is a condensed version of our testing process, but for the sake of this article, we’re keeping it brief.</p><p>Running API tests after making backend changes gives us the confidence that we did not introduce any regressions to our service. However, in this model, we don’t know whether or not our BFF layer is still working as expected. And depending on the size of the platform, we may not always remember which BFF layers are pointing to our backend. Using <a href="https://docs.github.com/en/actions/using-workflows/events-that-trigger-workflows#repository_dispatch">GitHub’s Repository Dispatch</a> event, we can trigger our BFF layer API integration tests to run after a staging deployment in our backend services. This ensures that our BFF layers remain in sync with the backend, providing a comprehensive testing approach for our entire system.</p><p>Here are the tools we used to accomplish this.</p><h3>Tooling Overview</h3><p><a href="https://jestjs.io/">Jest</a> is a JavaScript test framework that we use to write our API tests.</p><p><a href="https://jqlang.github.io/jq/">jq</a> is a command-line JSON processor that we use to parse our API test results.</p><p><a href="https://github.com/marketplace/actions/repository-dispatch">Repository Dispatch</a> is a GitHub action to create a dispatch event from one repository to another.</p><p><a href="https://github.com/marketplace/actions/slack-notify">Slack Notify</a> is a GitHub action that allows you to send a customizable Slack message. This is optional, but gives development teams visibility into automated test results.</p><p><a href="https://github.com/marketplace/actions/add-pr-comment">Add PR Comment</a> is a GitHub action that posts a customizable comment to a pull request. This is also optional, but provides direct testing feedback onto pull requests.</p><h3>Backend Service</h3><p>I’m going to outline the before and after steps for adding this Repository Dispatch event to demonstrate how quickly this can be set up. For this example, our backend service will be called <strong>backend-service</strong>, and our BFF layer will be called <strong>bff-api</strong>.</p><h4>Before Repository Dispatch:</h4><pre>name: Integration Tests<br>on:<br> push:<br>   branches:<br>     - staging<br><br>jobs:<br> integration_tests:<br>   name: Integration Tests<br>   steps:<br>     - name: Checkout code<br>       uses: actions/checkout@v4<br><br>     - name: Use Node.js 18.x<br>       uses: actions/setup-node@v4<br>       with:<br>         node-version: 18.x<br><br>     - name: Install yarn packages<br>       run: yarn install<br><br>     - name: Run Integration tests<br>       id: integration_tests<br>       run: |<br>         yarn run test <br>         <br>         # Extract test suite information<br>         total_test_suites=$(jq &quot;.numTotalTestSuites&quot; ./integration-test-output.txt)<br>         failed_test_suites=$(jq &quot;.numFailedTestSuites&quot; ./integration-test-output.txt)<br>         passed_test_suites=$(jq &quot;.numPassedTestSuites&quot; ./integration-test-output.txt)<br><br>         # Extract test information<br>         total_tests=$(jq &quot;.numTotalTests&quot; ./integration-test-output.txt)<br>         failed_tests=$(jq &quot;.numFailedTests&quot; ./integration-test-output.txt)<br>         passed_tests=$(jq &quot;.numPassedTests&quot; ./integration-test-output.txt)<br><br>         echo &quot;failed_tests=$failed_tests&quot; &gt;&gt; $GITHUB_OUTPUT<br>         echo &quot;suite_line=Passed suites: $passed_test_suites, Failed suites: $failed_test_suites, Total suites: $total_test_suites&quot; &gt;&gt; $GITHUB_OUTPUT<br>         echo &quot;tests_line=Passed tests: $passed_tests, Failed tests: $failed_tests, Total tests: $total_tests&quot; &gt;&gt; $GITHUB_OUTPUT<br><br>     - name: Post PR Comment<br>       if: always()<br>       uses: mshick/add-pr-comment@v2<br>       with:<br>         repo-token: ${{ secrets.GITHUB_TOKEN  }}<br>         refresh-message-position: true<br>         message: |<br>           # Staging API Test Results<br>           Integration Test Results: ${{ steps.integration_tests.outputs.tests_line }}<br>           Integration Suite Results: ${{ steps.integration_tests.outputs.suite_line }}<br>           See test results here: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}<br><br>     - name: Send Slack Notification<br>       uses: rtCamp/action-slack-notify@v2<br>       env:<br>         SLACK_COLOR: ${{ job.status }}<br>         SLACK_WEBHOOK: ${{ secrets.SLACK_WEBHOOK }}<br>         SLACK_TITLE: &#39;Backend-service Staging API Tests ${{ job.status }}&#39;<br>         SLACK_MESSAGE: |<br>           Integration Test Results: ${{ steps.integration_tests.outputs.tests_line }}<br>           Integration Suite Results: ${{ steps.integration_tests.outputs.suite_line }}<br>           See test results here: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}<br>         MSG_MINIMAL: true</pre><h4>After Repository Dispatch:</h4><pre>name: Integration Tests<br>on:<br> push:<br>   branches:<br>     - staging<br><br>jobs:<br>  integration_tests:<br>   name: Integration Tests<br>   runs-on: ubuntu-latest<br><br>   steps:<br>     - name: Checkout code<br>       uses: actions/checkout@v4<br><br>     - name: Use Node.js 18.x<br>       uses: actions/setup-node@v4<br>       with:<br>         node-version: 18.x<br><br>     - name: Install yarn packages<br>       run: yarn install<br><br>     - name: Run Integration tests<br>       id: integration_tests<br>       run: |<br>         yarn run test --json | tee ./integration-test-output.txt<br><br>         # Extract test suite information<br>         total_test_suites=$(jq &quot;.numTotalTestSuites&quot; ./integration-test-output.txt)<br>         failed_test_suites=$(jq &quot;.numFailedTestSuites&quot; ./integration-test-output.txt)<br>         passed_test_suites=$(jq &quot;.numPassedTestSuites&quot; ./integration-test-output.txt)<br><br>         # Extract test information<br>         total_tests=$(jq &quot;.numTotalTests&quot; ./integration-test-output.txt)<br>         failed_tests=$(jq &quot;.numFailedTests&quot; ./integration-test-output.txt)<br>         passed_tests=$(jq &quot;.numPassedTests&quot; ./integration-test-output.txt)<br><br>         echo &quot;failed_tests=$failed_tests&quot; &gt;&gt; $GITHUB_OUTPUT<br>         echo &quot;suite_line=Passed suites: $passed_test_suites, Failed suites: $failed_test_suites, Total suites: $total_test_suites&quot; &gt;&gt; $GITHUB_OUTPUT<br>         echo &quot;tests_line=Passed tests: $passed_tests, Failed tests: $failed_tests, Total tests: $total_tests&quot; &gt;&gt; $GITHUB_OUTPUT<br><br>     - name: Post PR Comment<br>       if: always()<br>       uses: mshick/add-pr-comment@v2<br>       with:<br>         repo-token: ${{ secrets.GITHUB_TOKEN}}<br>         refresh-message-position: true<br>         message: |<br>           # Staging API Test Results<br>           Integration Test Results: ${{ steps.integration_tests.outputs.tests_line }}<br>           Integration Suite Results: ${{ steps.integration_tests.outputs.suite_line }}<br>           See test results here: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}<br><br>     - name: Send Slack Notification<br>       uses: rtCamp/action-slack-notify@v2<br>       if: always()<br>       env:<br>         SLACK_COLOR: ${{ job.status }}<br>         SLACK_WEBHOOK: ${{ secrets.SLACK_WEBHOOK }}<br>         SLACK_TITLE: &#39;Backend-service Staging API Tests ${{ job.status }}&#39;<br>         SLACK_MESSAGE: |<br>           Integration Test Results: ${{ steps.integration_tests.outputs.tests_line }}<br>           Integration Suite Results: ${{ steps.integration_tests.outputs.suite_line }}<br>           See test results here: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}<br>         MSG_MINIMAL: true<br><br> setup_repository_list:<br>   name: Setup Repository List<br>   runs-on: ubuntu-latest<br>   outputs:<br>     BFFmatrix: ${{ steps.retrieve-repo-list.outputs.repo_list }}<br>   steps:<br>     - name: Checkout code<br>       uses: actions/checkout@v4<br><br>     - id: retrieve-repo-list<br>       run: |<br>         # returns something like this:<br>         # { repo: [&quot;teamsnap/bff-api&quot;, &quot;teamsnap/bff-2&quot;, &quot;teamsnap/bff-3&quot;] }<br>         TARGETS=$(./bffRepositories.sh)<br>         echo &quot;repo_list=$(echo &quot;$TARGETS&quot; | jq -c)&quot; &gt;&gt; $GITHUB_OUTPUT<br><br> bff_integration_tests:<br>   name: BFF Integration Tests<br>   runs-on: ubuntu-latest<br>   needs: setup_repository_list<br>   strategy:<br>     matrix: ${{ fromJson(needs.setup_repository_list.outputs.BFFmatrix) }}<br>   steps:<br>     - name: Trigger BFF API tests<br>       uses: peter-evans/repository-dispatch@v3<br>       with:<br>         token: ${{ secrets.GITHUB_TOKEN }}<br>         repository: ${{ matrix.repo }}<br>         event-type: bff_dispatch_backend_service<br>         client-payload: &#39;{ &quot;original_repository&quot;: &quot;Backend-service Staging Deploy&quot; }&#39;</pre><p>The difference between these two is the <em>setup_repository_list</em> and <em>bff_integration_tests</em> jobs at the bottom of the GitHub actions file.</p><p>In order to dynamically retrieve the list of BFF services that point to this backend service, we added a script called <em>bffRepositories.sh</em>. If we add new BFF layers, we can add them to this script rather than hard-coding them into our GitHub actions file. Our next iteration will be automatically generating this list each time a repository gets added or removed so we can remove the manual step altogether.</p><pre>#!/usr/bin/env bash<br><br>echo &#39;{ &quot;repo&quot;: [&quot;teamsnap/bff-api&quot;, &quot;teamsnap/bff-2&quot;, &quot;teamsnap/bff-3&quot;] }&#39;</pre><p>These are all of the changes needed for our backend service. Now onto our BFF layer.</p><h3>BFF Layer</h3><p>In the previous section, we covered how to send a trigger to the BFF repository and tell it to run their API tests. Now we need to add a GitHub action to our BFF repository to receive that call from our backend and trigger the API tests.</p><pre>name: Backend Service Dispatch<br># run staging integration tests after backend-service is deployed to staging<br>on:<br> repository_dispatch:<br>   types: [bff_dispatch_backend_service] # this is the event-type from our backend service GitHub action file<br><br>jobs:<br> integration_tests:<br>   name: Integration Tests<br>   runs-on: ubuntu-latest<br><br>   steps:<br>     - name: Checkout code<br>       uses: actions/checkout@v4<br><br>     - name: Use Node.js 18.x<br>       uses: actions/setup-node@v4<br>       with:<br>         node-version: 18.x<br><br>     - name: Install yarn packages<br>       run: yarn install<br><br>     - name: Run Integration tests<br>       id: integration_tests<br>       run: |<br>         yarn run test --json | tee ./integration-test-output.txt<br><br>         # Extract test suite information<br>         total_test_suites=$(jq &quot;.numTotalTestSuites&quot; ./integration-test-output.txt)<br>         failed_test_suites=$(jq &quot;.numFailedTestSuites&quot; ./integration-test-output.txt)<br>         passed_test_suites=$(jq &quot;.numPassedTestSuites&quot; ./integration-test-output.txt)<br><br>         # Extract test information<br>         total_tests=$(jq &quot;.numTotalTests&quot; ./integration-test-output.txt)<br>         failed_tests=$(jq &quot;.numFailedTests&quot; ./integration-test-output.txt)<br>         passed_tests=$(jq &quot;.numPassedTests&quot; ./integration-test-output.txt)<br><br>         echo &quot;failed_tests=$failed_tests&quot; &gt;&gt; $GITHUB_OUTPUT<br>         echo &quot;suite_line=Passed suites: $passed_test_suites, Failed suites: $failed_test_suites, Total suites: $total_test_suites&quot; &gt;&gt; $GITHUB_OUTPUT<br>         echo &quot;tests_line=Passed tests: $passed_tests, Failed tests: $failed_tests, Total tests: $total_tests&quot; &gt;&gt; $GITHUB_OUTPUT<br><br>     - name: Send Slack Notification<br>       uses: rtCamp/action-slack-notify@v2<br>       if: always()<br>       env:<br>         SLACK_COLOR: ${{ job.status }}<br>         SLACK_WEBHOOK: ${{ secrets.SLACK_WEBHOOK }}<br>         SLACK_TITLE: ${{ github.event.client_payload.original_repository }}<br>         SLACK_MESSAGE: |<br>           :arrow_right: *bff-api* Staging Tests ${{ job.status }}<br>           Integration Test Results: ${{ steps.integration_tests.outputs.tests_line }}<br>           Integration Suite Results: ${{ steps.integration_tests.outputs.suite_line }}<br>           See test results here: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}<br>         MSG_MINIMAL: true</pre><p>This is what the slack notification will look like from our BFF layer:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*GHaWAybvdWZQjOfM" /></figure><h3>Conclusion</h3><p>Running API integration tests in our BFF layer after deploying backend changes is a simple yet effective way to ensure our backend changes are not causing any unintended changes downstream. By using a Repository Dispatch GitHub action, we can map each BFF layer to its backend services, and vice-versa. This not only helps with regression testing, but helps us document these relationships as well. At TeamSnap, our backend services are shared across teams. This documentation notifies each developer, regardless of their team, about how their code changes could affect others. This approach enhances our development process by promoting better understanding and collaboration across teams, ultimately leading to more reliable and stable software.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2c70d788c955" width="1" height="1" alt=""><hr><p><a href="https://medium.com/teamsnap-engineering/enhancing-api-integration-testing-leveraging-githubs-repository-dispatch-action-2c70d788c955">Enhancing API Integration Testing: Leveraging GitHub’s Repository Dispatch Action</a> was originally published in <a href="https://medium.com/teamsnap-engineering">TeamSnap Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Accessing AWS Resources from Google Kubernetes Engine]]></title>
            <link>https://medium.com/teamsnap-engineering/accessing-aws-resources-from-google-kubernetes-engine-3df21a8ca297?source=rss----c8de247e26d7---4</link>
            <guid isPermaLink="false">https://medium.com/p/3df21a8ca297</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[google-cloud-platform]]></category>
            <category><![CDATA[authentication]]></category>
            <category><![CDATA[google-kubernetes-engine]]></category>
            <dc:creator><![CDATA[Steven Aldinger]]></dc:creator>
            <pubDate>Thu, 15 Feb 2024 16:17:29 GMT</pubDate>
            <atom:updated>2024-02-15T16:17:29.267Z</atom:updated>
            <content:encoded><![CDATA[<p>My team had a requirement to integrate with a project in AWS, but the primary infrastructure we were working with was all in Google Cloud already. It only takes a few steps to set up a service account user in AWS and generate an API key to use for authenticating from GCP, but using a long-lived key isn’t best practice and felt like too much of a security risk to use in a production solution.</p><p>With AWS support for <a href="https://openid.net/developers/how-connect-works/">Open ID Connect</a> Federation, and <a href="https://cloud.google.com/kubernetes-engine/docs/concepts/workload-identity#:~:text=Workload%20identity%20federation%20for%20GKE%20allows%20a%20Kubernetes%20service%20account,when%20accessing%20Google%20Cloud%20APIs.">Google workload identity federation in GKE</a>, setting up a secure solution with short-lived credentials is pretty easy. It’s much more tedious than just putting an API key in an environment variable and calling it done, but still reasonable to set up in short order if you already know the path to take.</p><p>There’s some <a href="https://aws.amazon.com/blogs/security/access-aws-using-a-google-cloud-platform-native-workload-identity/">decent documentation</a> around this from both AWS <a href="https://developers.google.com/identity/openid-connect/openid-connect#obtainuserinfo">and GCP</a>, but it’s easy to stray down complicated tangents in the documentation, and it felt a bit more involved than it needed to be to figure out how to implement properly, so the purpose of this article is to show a direct path with no extraneous detail to sidetrack. The example here will be showing how to provide secure AWS admin access with short-lived credentials to an <a href="https://www.runatlantis.io/">Atlantis</a> server, but this is a general solution that will work for any applications running in <a href="https://cloud.google.com/kubernetes-engine?hl=en">GKE</a>.</p><h3>Strategy Overview</h3><p>There’s a handful of distinct pieces involved here. The combination of things might seem overwhelming at first, but no individual step is very complicated, and each step has it’s own section further down to elaborate anywhere it seemed like it’d be helpful.</p><ol><li><strong>[GCP]</strong> Create a service account to use for identity.</li><li><strong>[GKE]</strong> Create a K8s service account in the namespace of the application that needs AWS access.</li><li><strong>[GCP]</strong> Create an iam.workloadIdentityUser role binding that allows the K8s service account to act as the Google service account.</li><li><strong>[AWS]</strong> Configure an IAM role that allows authentication from the Google service account.</li><li><strong>[AWS]</strong> Configure an IAM policy binding that allows the service account’s role to access whichever resources the application needs.</li><li><strong>[Application]</strong> Configure an AWS profile with a credentials script in the application’s container that can fetch fresh short-lived credentials as necessary.</li><li><strong>[Application]</strong> Refer to the AWS profile in the application.</li></ol><h3>Create the GCP Service Account</h3><p>The first step is to <a href="https://cloud.google.com/iam/docs/service-accounts-create">create a service account</a> in Google Cloud <a href="https://cloud.google.com/iam/docs/overview">IAM</a>. This service account doesn’t need any roles granted, since it’s being used purely for identity.</p><pre>module &quot;atlantis_svc_account&quot; {<br>  source  = &quot;terraform-google-modules/service-accounts/google&quot;<br>  version = &quot;4.2.2&quot;<br><br>  project_id   = &quot;gcp-project-id&quot;<br>  names        = [&quot;atlantis&quot;]<br>  display_name = &quot;atlantis&quot;<br>  description  = &quot;Atlantis Service Account&quot;<br><br>  project_roles = []<br>}</pre><p>There’s nothing special about the service account creation, so if you want to use an existing service account or create it in the Google Cloud UI, or with Google’s Terraform provider resources directly, that’ll work fine. I use terraform-google-modules/service-accounts/google for other things so I’m using it here too. The simplest version might look like the following snippet instead.</p><pre>resource &quot;google_service_account&quot; &quot;atlantis&quot; {<br>  account_id   = &quot;atlantis&quot;<br>  display_name = &quot;Atlantis Service Account&quot;<br>}</pre><h3>Create a Kubernetes Service Account</h3><p>Create a K8s service account with the special annotation iam.gke.io/gcp-service-account, which needs it’s value to match the email address of the Google Cloud service account. You can follow along with Google’s documentation <a href="https://cloud.google.com/kubernetes-engine/docs/how-to/workload-identity#authenticating_to">here</a>, but just looking at the declarative version of what’s being accomplished is always clearer to me personally, so here’s what that looks like.</p><pre>---<br>apiVersion: v1<br>kind: ServiceAccount<br>metadata:<br>  name: atlantis<br>  namespace: atlantis<br>  annotations:<br>    iam.gke.io/gcp-service-account: atlantis@gcp-project-id.iam.gserviceaccount.com</pre><h3>Create a workloadIdentityUser Role Binding</h3><p>This step gives the K8s service account permission to assume the identity of the Google Cloud service account. Prior to workload identity federation in GKE, this may have been accomplished in a less-secure way by mounting a JSON file with GCP service account credentials inside the application container. One advantage of using workload identity for this is that there isn’t a long-lived credentials file exposed anywhere in the process, so if there’s a security breach, any credentials stolen will be useless soon after they’re taken.</p><p>The service account reference for workload identity federation in GKE looks a little interesting compared to the email address format that’s more typical in Google Cloud. The format is serviceAccount:GCP_PROJECT_ID.svc.id.goog[KUBE_NAMESPACE/KUBE_SVC_ACCOUNT_NAME], where KUBE_NAMESPACE and KUBE_SVC_ACCOUNT_NAME depend on the K8s service account creation in the previous step. In this example the K8s namespace and K8s service account are both named atlantis, so the service account reference looks like serviceAccount:gcp-project-id.svc.id.goog[atlantis/atlantis].</p><pre>resource &quot;google_service_account_iam_binding&quot; &quot;atlantis_k8s_workload_identity&quot; {<br>  service_account_id = module.atlantis_svc_account.service_account.name<br>  role               = &quot;roles/iam.workloadIdentityUser&quot;<br><br>  # &quot;serviceAccount:GCP_PROJECT_ID.svc.id.goog[KUBE_NAMESPACE/KUBE_SVC_ACCOUNT_NAME]&quot;<br>  members = [&quot;serviceAccount:gcp-project-id.svc.id.goog[atlantis/atlantis]&quot;]<br>}</pre><h3>Halfway There!</h3><p>At this point, all the setup on the GCP side of things is finished, and the project is ready to use the GCP service account with OIDC federation in AWS, but we still need to configure the AWS project to recognize the service account and allow the specific access we want to give it.</p><h3>Configure an AWS Role</h3><p>The role demonstrated here is based on <a href="https://aws.amazon.com/blogs/security/access-aws-using-a-google-cloud-platform-native-workload-identity/#define_IAM_role">this AWS documentation</a>, where 123456789012345678900 is the unique ID of the Google Cloud service account. This ID can be found in the GCP console UI under the Unique ID section of the service account’s details page.</p><p>The accounts.google.com:oaud field in the role definition is arbitrary, but whatever value you decide to use needs to match the credentials script in an upcoming step. In this example, I’m using AtlantisAccess as the oaud so it’s obvious what its purpose is supposed to be at a glance.</p><p>The principal value {&quot;Federated&quot;: &quot;accounts.google.com&quot;} is boilerplate, but is also the real magic here, immediately integrating with Google’s IAM solution without explicitly configuring identity pools or anything complicated between the two cloud providers.</p><pre>locals {<br>  # hardcode if you want<br>  svc_acct_id = &quot;123456789012345678900&quot;<br><br>  # use the module output instead if that makes sense with your setup<br>  #<br>  # svc_acct_id = module.atlantis_svc_account.service_account.unique_id<br><br>  # use the resource output if you created the service account that way<br>  #<br>  # svc_acct_id = google_service_account.atlantis.unique_id<br>}<br><br>resource &quot;aws_iam_role&quot; &quot;atlantis_google_workload_identity_role&quot; {<br>  name               = &quot;atlantis_google_workload_identity_role&quot;<br>  assume_role_policy = &lt;&lt;EOF<br>{<br>    &quot;Version&quot;: &quot;2012-10-17&quot;,<br>    &quot;Statement&quot;: [<br>        {<br>            &quot;Effect&quot;: &quot;Allow&quot;,<br>            &quot;Principal&quot;: {&quot;Federated&quot;: &quot;accounts.google.com&quot;},<br>            &quot;Action&quot;: &quot;sts:AssumeRoleWithWebIdentity&quot;,<br>            &quot;Condition&quot;: {<br>                &quot;StringEquals&quot;: {<br>                    &quot;accounts.google.com:aud&quot;: local.svc_acct_id,<br>                    &quot;accounts.google.com:oaud&quot;: &quot;AtlantisAccess&quot;,<br>                    &quot;accounts.google.com:sub&quot;: local.svc_acct_id<br>                }<br>            }<br>        }<br>    ]<br>}<br>EOF<br>}<br><br><br>output &quot;atlantis_role_arn&quot; {<br>  value = aws_iam_role.atlantis_google_workload_identity_role.arn<br>}</pre><h3>Configure an AWS policy binding</h3><p>For the Atlantis use case, you might want to give blanket admin permissions using the special arn:aws:iam::aws:policy/AdministratorAccess ARN that <a href="https://docs.aws.amazon.com/aws-managed-policy/latest/reference/AdministratorAccess.html#AdministratorAccess-details">AWS provides</a> by default.</p><pre>resource &quot;aws_iam_role_policy_attachment&quot; &quot;atlantis_admin&quot; {<br>  role = aws_iam_role.atlantis_google_workload_identity_role.name<br>  policy_arn = &quot;arn:aws:iam::aws:policy/AdministratorAccess&quot;<br>}</pre><p>If you’re looking to lock things down more explicitly, you can attach a custom policy instead. The following snippet shows an example of how you might allow listing secrets throughout the project, and only allow reading secrets hosted in a specified aws_region.</p><pre>data &quot;aws_iam_policy_document&quot; &quot;get_secrets&quot; {<br>  statement {<br>    actions = [<br>      &quot;secretsmanager:GetResourcePolicy&quot;,<br>      &quot;secretsmanager:GetSecretValue&quot;,<br>      &quot;secretsmanager:DescribeSecret&quot;,<br>      &quot;secretsmanager:ListSecretVersionIds&quot;,<br>    ]<br>    resources = [&quot;arn:aws:secretsmanager:${var.aws_region}:${var.aws_account_id}:secret:*&quot;]<br>    effect    = &quot;Allow&quot;<br>  }<br><br>  statement {<br>    actions   = [&quot;secretsmanager:ListSecrets&quot;]<br>    resources = [&quot;*&quot;]<br>    effect    = &quot;Allow&quot;<br>  }<br>}<br><br>resource &quot;aws_iam_policy&quot; &quot;secrets_manager_policy&quot; {<br>  name        = &quot;example-secrets-manager-policy&quot;<br>  description = &quot;Read-only access to secrets manager&quot;<br>  path        = &quot;/example/&quot;<br><br>  policy = data.aws_iam_policy_document.get_secrets.json<br>}<br><br>resource &quot;aws_iam_role_policy_attachment&quot; &quot;secret_manager_read_only&quot; {<br>  role       = aws_iam_role.atlantis_google_workload_identity_role.name<br>  policy_arn = aws_iam_policy.secrets_manager_policy.arn<br>}</pre><h3>Configure AWS Credentials Script and Profile</h3><p>This script is nearly copy-paste from <a href="https://aws.amazon.com/blogs/security/access-aws-using-a-google-cloud-platform-native-workload-identity/#define_IAM_role">AWS documentation</a>, but it’s worth highlighting a few things going on here.</p><p>The AUDIENCE variable needs to match the accounts.google.com:oaud field in the AWS role definition from the role configuration step, and the ROLE_ARN variable needs to match the atlantis_role_arn output .</p><p>One tricky thing to be aware of, is that this script prints the credentials to be captured in stdout. That means if you’re looking to add debug statements to the script, you need to make sure nothing else ends up in stdout or the debug statements themselves will become a bug.</p><p>Another potential “gotcha” is that the script assumes curl and jq are both installed in the container. Be sure to apk add --no-cache curl jq or apt install -y curl jq in your Dockerfile before trying to use this with an application.</p><pre>#!/bin/bash<br><br>AUDIENCE=&quot;AtlantisAccess&quot;<br>ROLE_ARN=&quot;arn:aws:iam::${AWS_ACCOUNT_ID}:role/atlantis_admin_google_workload_identity_role&quot;<br><br>jwt_token=$(curl -sH &quot;Metadata-Flavor: Google&quot; &quot;http://metadata/computeMetadata/v1/instance/service-accounts/default/identity?audience=${AUDIENCE}&amp;format=full&amp;licenses=FALSE&quot;)<br>jwt_decoded=$(jq -R &#39;split(&quot;.&quot;) | .[1] | @base64d | fromjson&#39; &lt;&lt;&lt; &quot;$jwt_token&quot;)<br><br>jwt_sub=$(echo -n &quot;$jwt_decoded&quot; | jq -r &#39;.sub&#39;)<br><br>credentials=$(aws sts assume-role-with-web-identity --role-arn $ROLE_ARN --role-session-name $jwt_sub --web-identity-token $jwt_token | jq &#39;.Credentials&#39; | jq &#39;.Version=1&#39;)<br><br>echo $credentials</pre><p>The file containing the script can be placed anywhere on the same machine it’s being used, but to actually reference the script, we need to refer to it in an <a href="https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-files.html#cli-configure-files-where">AWS profile config</a>.</p><p>The documentation explains that the default AWS config directory is in the user’s home directory, so the appropriate place for this config file might be /root/.aws/config or something like /home/atlantis/.aws/config depending on the container image being used. In this example profile, the credentials script was placed at /opt/bin/credentials.sh along with a chmod +x to make sure the script is executable.</p><pre>[profile AtlantisAccess]<br>credential_process = /opt/bin/credentials.sh</pre><h3>Using the AWS credentials profile</h3><p>This is the fun part. AWS clients seem to all have a way to refer to a credentials profile by name to use for authentication. For the AWS Terraform provider, you can easily set up auth by matching the profile field to whatever you put for the [profile AtlantisAccess] piece of the ~/.aws/config file.</p><pre>provider &quot;aws&quot; {<br>  region  = &quot;us-east-1&quot;<br>  profile = &quot;AtlantisAccess&quot;<br>}</pre><p>Referring to the profile in application code is nearly as easy. This snippet demonstrates what that looks like in a C# application.</p><pre>using Amazon;<br><br>...<br><br>var chain = new Amazon.Runtime.CredentialManagement.CredentialProfileStoreChain();<br>chain.TryGetAWSCredentials(&quot;AtlantisAccess&quot;, out var credentials);<br><br>... use `credentials` variable in some other AWS code</pre><h3>Conclusion</h3><p>Authenticating to AWS from GKE in a secure way takes a few steps to set up, but Terraform can help make the process painless. The general OIDC federation strategy used here to enable Google service accounts to authenticate with AWS can be applied across GCP products with nearly the exact same steps, just by replacing the workloadIdentityUser role binding step with something other than the Kubernetes service account reference, or removing that step entirely if it makes sense to use the Google service account credentials directly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VXIIaGVcX3U0k1HTjqR2eg.jpeg" /><figcaption>Adorable Kubernetes service account bot accessing cloud resources</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3df21a8ca297" width="1" height="1" alt=""><hr><p><a href="https://medium.com/teamsnap-engineering/accessing-aws-resources-from-google-kubernetes-engine-3df21a8ca297">Accessing AWS Resources from Google Kubernetes Engine</a> was originally published in <a href="https://medium.com/teamsnap-engineering">TeamSnap Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Vertex AI and BigQuery for Natural Language Exploration of GCP Billing Data]]></title>
            <link>https://medium.com/teamsnap-engineering/vertex-ai-and-bigquery-for-natural-language-exploration-of-gcp-billing-data-7f96b13c7a7e?source=rss----c8de247e26d7---4</link>
            <guid isPermaLink="false">https://medium.com/p/7f96b13c7a7e</guid>
            <category><![CDATA[google-cloud-platform]]></category>
            <category><![CDATA[generative-ai-tools]]></category>
            <category><![CDATA[vertex-ai]]></category>
            <category><![CDATA[bigquery]]></category>
            <category><![CDATA[streamlit]]></category>
            <dc:creator><![CDATA[Steven Aldinger]]></dc:creator>
            <pubDate>Wed, 24 Jan 2024 16:01:53 GMT</pubDate>
            <atom:updated>2024-01-24T16:01:53.314Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>One of the best parts of the generative AI boom is that historically-technical things to interact with can be reduced to a natural, intuitive interface. Tasks that require in-depth knowledge and skills to carry out can now be wrapped with <a href="https://www.cloudflare.com/learning/ai/what-is-large-language-model/">Large Language Models</a> (LLM) to respond to questions asked in natural language, and thanks to frameworks like <a href="https://streamlit.io/">Streamlit</a> and <a href="https://www.gradio.app/">Gradio</a>, you can seamlessly integrate a graphical interface in mere minutes.</p><p>This article is your guide to unleashing Google’s new <a href="https://blog.google/technology/ai/google-gemini-ai/">Gemini Pro</a> model on your Google Cloud billing data that has been <a href="https://cloud.google.com/billing/docs/how-to/export-data-bigquery">exported</a> to <a href="https://cloud.google.com/bigquery">BigQuery</a>. Combining these tools can help break down technical barriers, and make exploring datasets as approachable as having a conversation.</p><p>Everything shown in the article can be run on your computer or as a <a href="https://cloud.google.com/run">Cloud Run</a> application by following the instructions in the <a href="https://github.com/stevenaldinger/vertex-ai-google-cloud-billing/blob/main/README.md">stevenaldinger/vertex-ai-google-cloud-billing</a> repository.</p><h3>Why spend the time to do this?</h3><p>Unlocking the immense power of BigQuery becomes a thrilling journey when paired with the magic of generative AI’s natural language capabilities. Imagine being able to ask intricate questions about your data using everyday language, eliminating the need for complex query languages like <a href="https://cloud.google.com/bigquery/docs/introduction-sql">GoogleSQL</a>, as well as the skills to interact with BigQuery. This is a convenient time saver for people already familiar with the tools, but it’s also ushering in a new era of data exploration and discovery for everyone else.</p><p>In this new era, data access isn’t reserved for the tech-savvy engineers. Generative AI can help democratize data, empowering a more diverse audience with natural language driven analysis. As businesses start to embrace this, the result will be more than just operational efficiency. Efficiency will come paired with a true competitive advantage, fueled by fresh perspectives and a profound understanding of their own data.</p><h3>Leveraging Generative AI with BigQuery</h3><p>This section gives an overview of the strategy I used to integrate Gemini Pro with BigQuery, and most of the links point to relevant lines of code in the open source repo. I’m working with Google Cloud products, but <strong>you can swap in other models like OpenAI’s GPT just by changing the few lines in </strong><a href="https://github.com/stevenaldinger/vertex-ai-google-cloud-billing/blob/main/app/streamlit_helpers/llm.py#L5-L15"><strong>this single file</strong></a>.</p><p>The following image is a preview of what the application looks like. If you get bored of the walkthrough and want to jump straight into running the app or spelunking in the code base, you can choose your own adventure at <a href="https://github.com/stevenaldinger/vertex-ai-google-cloud-billing">stevenaldinger/vertex-ai-google-cloud-billing</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/845/1*xfDJdxF-AuiyG60EbyIHAQ.png" /></figure><p>In this strategy, the first thing to do is <a href="https://github.com/stevenaldinger/vertex-ai-google-cloud-billing/blob/main/modules/helpers/utils/bigquery.py#L27-L43">load</a> the BigQuery dataset’s table schemas and make them <a href="https://github.com/stevenaldinger/vertex-ai-google-cloud-billing/blob/main/app/app.py#L27-L42">available</a> for use in an <a href="https://github.com/stevenaldinger/vertex-ai-google-cloud-billing/blob/main/modules/helpers/llm/bigquery.py#L13-L29">LLM chain</a>.</p><p>I used LangChain’s <a href="https://python.langchain.com/docs/integrations/document_loaders/google_bigquery">BigQuery Loader</a>, but the main purpose for that was just to more easily integrate with other LangChain tools. The real secret sauce is this simple <a href="https://github.com/stevenaldinger/vertex-ai-google-cloud-billing/blob/main/modules/helpers/utils/bigquery.py#L6-L24">BigQuery query</a> for the table names and their DDLs so that we can add the table definitions to an LLM prompt later on.</p><pre>SELECT table_name, ddl<br>FROM `{bigquery_dataset}.INFORMATION_SCHEMA.TABLES`<br>WHERE table_type = &#39;BASE TABLE&#39;<br>ORDER BY table_name;</pre><p>The result of executing that snippet in BigQuery is a list of all the table names in a dataset, as well as their definitions. The output for the billing export table we’re targeting looks like this:</p><pre>CREATE TABLE `steven-aldinger.gdax.gcp_billing_export_v1_0161FF_E1335F_xxxxx`<br>(<br>  billing_account_id STRING OPTIONS(description=&quot;&quot;),<br>  service STRUCT&lt;id STRING OPTIONS(description=&quot;&quot;), description STRING OPTIONS(description=&quot;&quot;)&gt; OPTIONS(description=&quot;&quot;),<br>  sku STRUCT&lt;id STRING OPTIONS(description=&quot;&quot;), description STRING OPTIONS(description=&quot;&quot;)&gt; OPTIONS(description=&quot;&quot;),<br>  usage_start_time TIMESTAMP OPTIONS(description=&quot;&quot;),<br>  usage_end_time TIMESTAMP OPTIONS(description=&quot;&quot;),<br>  project STRUCT&lt;id STRING OPTIONS(description=&quot;&quot;), number STRING OPTIONS(description=&quot;&quot;), name STRING OPTIONS(description=&quot;&quot;), labels ARRAY&lt;STRUCT&lt;key STRING OPTIONS(description=&quot;&quot;), value STRING OPTIONS(description=&quot;&quot;)&gt;&gt; OPTIONS(description=&quot;&quot;), ancestry_numbers STRING OPTIONS(description=&quot;&quot;), ancestors ARRAY&lt;STRUCT&lt;resource_name STRING OPTIONS(description=&quot;&quot;), display_name STRING OPTIONS(description=&quot;&quot;)&gt;&gt; OPTIONS(description=&quot;&quot;)&gt; OPTIONS(description=&quot;&quot;),<br>  labels ARRAY&lt;STRUCT&lt;key STRING OPTIONS(description=&quot;&quot;), value STRING OPTIONS(description=&quot;&quot;)&gt;&gt; OPTIONS(description=&quot;&quot;),<br>  system_labels ARRAY&lt;STRUCT&lt;key STRING OPTIONS(description=&quot;&quot;), value STRING OPTIONS(description=&quot;&quot;)&gt;&gt; OPTIONS(description=&quot;&quot;),<br>  location STRUCT&lt;location STRING OPTIONS(description=&quot;&quot;), country STRING OPTIONS(description=&quot;&quot;), region STRING OPTIONS(description=&quot;&quot;), zone STRING OPTIONS(description=&quot;&quot;)&gt; OPTIONS(description=&quot;&quot;),<br>  export_time TIMESTAMP OPTIONS(description=&quot;&quot;),<br>  cost FLOAT64 OPTIONS(description=&quot;&quot;),<br>  currency STRING OPTIONS(description=&quot;&quot;),<br>  currency_conversion_rate FLOAT64 OPTIONS(description=&quot;&quot;),<br>  usage STRUCT&lt;amount FLOAT64 OPTIONS(description=&quot;&quot;), unit STRING OPTIONS(description=&quot;&quot;), amount_in_pricing_units FLOAT64 OPTIONS(description=&quot;&quot;), pricing_unit STRING OPTIONS(description=&quot;&quot;)&gt; OPTIONS(description=&quot;&quot;),<br>  credits ARRAY&lt;STRUCT&lt;name STRING OPTIONS(description=&quot;&quot;), amount FLOAT64 OPTIONS(description=&quot;&quot;), full_name STRING OPTIONS(description=&quot;&quot;), id STRING OPTIONS(description=&quot;&quot;), type STRING OPTIONS(description=&quot;&quot;)&gt;&gt; OPTIONS(description=&quot;&quot;),<br>  invoice STRUCT&lt;month STRING OPTIONS(description=&quot;&quot;)&gt; OPTIONS(description=&quot;&quot;),<br>  cost_type STRING OPTIONS(description=&quot;&quot;),<br>  adjustment_info STRUCT&lt;id STRING OPTIONS(description=&quot;&quot;), description STRING OPTIONS(description=&quot;&quot;), mode STRING OPTIONS(description=&quot;&quot;), type STRING OPTIONS(description=&quot;&quot;)&gt; OPTIONS(description=&quot;&quot;),<br>  tags ARRAY&lt;STRUCT&lt;key STRING OPTIONS(description=&quot;&quot;), value STRING OPTIONS(description=&quot;&quot;), inherited BOOL OPTIONS(description=&quot;&quot;), namespace STRING OPTIONS(description=&quot;&quot;)&gt;&gt; OPTIONS(description=&quot;&quot;),<br>  cost_at_list FLOAT64,<br>  transaction_type STRING,<br>  seller_name STRING<br>)<br>PARTITION BY DATE(_PARTITIONTIME);</pre><p>This next step is where the fun starts. The table definitions can be passed into a prompt alongside a natural language question about billing, but instead of asking for a direct answer to the question, we can ask it to generate <a href="https://cloud.google.com/bigquery/docs/introduction-sql">GoogleSQL</a> code instead. Note that it’s also important to supplement the prompt with the current date, so when we say “last 3 months” in a query, it doesn’t go by the (very incorrect) date of the data it was trained on.</p><pre>Write a BigQuery Google Standard SQL query that answers the following question.<br>Today&#39;s date is {todays_date}.<br><br>Question: {human_language_question}<br><br>{table_ddl}</pre><p>Given the question, <strong><em>“What are my top 5 most used services by cost?”</em></strong>, this is the code it outputted; which can be passed directly into the standard BigQuery <a href="https://cloud.google.com/python/docs/reference/bigquery/latest#example-usage">python client</a>. The cherry on top is that the client has a <a href="https://github.com/stevenaldinger/vertex-ai-google-cloud-billing/blob/main/modules/helpers/utils/bigquery.py#L45-L59">built-in way</a> to get the results as a <a href="https://pandas.pydata.org/docs/user_guide/dsintro.html#dataframe">Pandas DataFrame</a>, which makes it really easy to integrate with other code.</p><pre>WITH ServiceCost AS (<br>  SELECT<br>    service.description AS service_name,<br>    SUM(cost) AS total_cost<br>  FROM<br>    `steven-aldinger.gdax.gcp_billing_export_v1_0161FF_E1335F_xxxxx`<br>  WHERE<br>    _PARTITIONTIME BETWEEN TIMESTAMP(&quot;2023-01-21 00:00:00&quot;) AND TIMESTAMP(&quot;2024-01-21 00:00:00&quot;)<br>  GROUP BY<br>    service.description<br>)<br>SELECT<br>  service_name,<br>  total_cost<br>FROM<br>  ServiceCost<br>ORDER BY<br>  total_cost DESC<br>LIMIT 5;</pre><p>What if the generated code fails to execute and BigQuery responds with an error message instead? An engineer would read the error message, review their failed query, and double check the DDL to see where they made a mistake. Why not try to reproduce that process automatically with <a href="https://github.com/stevenaldinger/vertex-ai-google-cloud-billing/blob/main/modules/helpers/prompts/bigquery.py#L7-L34">another generative AI prompt</a>?</p><p>The LLM can be called into play in a <a href="https://github.com/stevenaldinger/vertex-ai-google-cloud-billing/blob/main/app/streamlit_helpers/interface.py#L58-L78">normal error handling</a> pattern, and this time it’s goal will be to try to resolve the bug. By writing a new prompt that contains the same context an engineer would use to fix the issue, the LLM has a chance of recovering the fumble and still successfully answering the question.</p><pre><br>Fix the following BigQuery Google Standard SQL code to resolve the error.<br>Only respond with code, no explanation.<br><br>BigQuery Google Standard SQL code:<br>```sql<br>{failed_query}<br>```<br><br>Error message:<br>```<br>{error_message}<br>```<br><br>Schema context:<br>{content}</pre><p>If the query executes successfully, the rows returned from the BigQuery client will be in an easy to work with DataFrame that’ll look something like this.</p><pre>#    service_name  total_cost<br>0  Compute Engine  325.275<br>1       Vertex AI  128.687<br>2   Cloud Storage   32.423<br>3        Maps API    4.739<br>4        BigQuery    1.59191</pre><p>That’s pretty neat on it’s own, but I think most people would agree that visualizing data in charts can make it much more meaningful than viewing rows in a table. Generative AI can be leveraged <em>even further</em> by prompting it to write visualization code for the DataFrame.</p><p>A visualization prompt might look something like the following snippet. Giving the user’s question as context in the prompt alongside the DataFrame helps it better understand how to display the data clearly. The <a href="https://github.com/stevenaldinger/vertex-ai-google-cloud-billing/blob/main/modules/helpers/prompts/visualization.py#L4-L66">prompt that’s actually used in the code</a> is a one-shot prompt that uses a single example of what we consider to be a good output. This reduces the chances of generating incomplete or broken code and gives us confidence it will follow nuanced instructions like assigning the <a href="https://matplotlib.org/">Matplotlib</a> figure to a variable named fig.</p><pre>Write python code to visualize the following pandas dataframe using matplotlib. Only respond with code, no explanation.<br>Be sure to define the dataframe as `df` before plotting.<br>Assign the figure to a variable named `fig`.<br>The question asked was &quot;{query}&quot;<br>The corresponding dataframe is:<br>{dataframe}<br>Visualization code:</pre><p>Here’s an example of generated visualization code from Gemini Pro.</p><pre>import pandas as pd<br>import matplotlib.pyplot as plt<br><br># Define the dataframe<br>df = pd.DataFrame({<br>    &#39;ServiceDescription&#39;: [&#39;Compute Engine&#39;, &#39;Vertex AI&#39;, &#39;Cloud Storage&#39;, &#39;Maps API&#39;, &#39;BigQuery&#39;],<br>    &#39;TotalCost&#39;: [325.275, 128.687, 32.423, 4.739, 1.59191]<br>})<br><br># Plot the bar chart<br>df.sort_values(by=&#39;TotalCost&#39;, ascending=False).head(5).plot.barh(x=&#39;ServiceDescription&#39;, y=&#39;TotalCost&#39;)<br><br># Customize the plot<br>plt.title(&#39;Top 5 Most Used Services By Cost&#39;)<br>plt.xlabel(&#39;Total Cost&#39;)<br>plt.ylabel(&#39;Service Description&#39;)<br>plt.grid(True)<br>plt.show()<br><br>fig = plt.gcf()</pre><p>Take whatever precautions you deem necessary for your environment before following this approach, but if you’re confident enough in your security and reliability, the visualization code returned from the LLM can be passed into <a href="https://docs.python.org/3/library/functions.html#exec">exec()</a>, and integrated with your business logic. This is demonstrated in a way that won’t break your code base <a href="https://github.com/stevenaldinger/vertex-ai-google-cloud-billing/blob/main/modules/helpers/utils/visualization.py#L9-L31">here</a>, but with a complete disregard for security concerns, given this is effectively an intentional <a href="https://www.checkpoint.com/cyber-hub/cyber-security/what-is-remote-code-execution-rce/">remote code execution</a> vulnerability.</p><p>Since the LLM was told to assign the figure to a variable named fig, we can take control of it after the exec() and <a href="https://github.com/stevenaldinger/vertex-ai-google-cloud-billing/blob/main/modules/helpers/utils/visualization.py#L56-L77">convert it into a NumPy array</a> using <a href="https://python-pillow.org/">Pillow</a>, or whatever else you might need to do. By saving the image data as <a href="https://www.digitalocean.com/community/tutorials/python-io-bytesio-stringio#python-bytesio">BytesIO</a> or converting to a NumPy array, we can easily display the chart for the user in the UI as a <a href="https://github.com/stevenaldinger/vertex-ai-google-cloud-billing/blob/main/app/streamlit_helpers/interface.py#L102-L110">Streamlit image</a>.</p><pre># execute the code generated by the LLM<br># this runs `fig = plt.gcf()` after configuring the plot<br>exec(visualization_code)<br><br># save the figure to a BytesIO object<br>buf = io.BytesIO()<br>fig.savefig(buf, format=&#39;png&#39;)<br>buf.seek(0)<br><br># load the image data from the BytesIO object into a numpy array<br>image = Image.open(buf)<br>image_array = np.array(image)</pre><h3>Conclusion</h3><p>The ease of integration between generative AI and BigQuery represents a paradigm shift in how organizations harness the power of data, marking a significant step forward in the evolution of data analytics within organizations. The fusion of human-like language understanding with the analytical capabilities of BigQuery transforms the way users can interact with their data, making it more accessible and insightful.</p><p>Furthermore, the synergy between generative AI and BigQuery facilitates the discovery of patterns and trends that might have remained hidden in traditional analysis approaches. By allowing users to pose nuanced questions in natural language, they can uncover correlations, anomalies, and potential cost optimization opportunities that might have eluded them using conventional methods. Even for technical people, asking back-to-back questions in natural language comes with a lot less fatigue than writing coded queries. This easy interaction with data could also enhance the agility of decision-making processes and enable organizations to adapt more swiftly to changing circumstances.</p><p>Regardless of how great the potential seems to be in theory, how much of an impact it really makes will depend on the creativity of the people adopting it. I’m optimistic about where things are headed, but only time will tell.</p><p>Thanks for reading, and be sure to check out the <a href="https://github.com/stevenaldinger/vertex-ai-google-cloud-billing">open source companion repo</a> to deploy the example app to Cloud Run for a starting point if you’d like to try working with your own data.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7f96b13c7a7e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/teamsnap-engineering/vertex-ai-and-bigquery-for-natural-language-exploration-of-gcp-billing-data-7f96b13c7a7e">Vertex AI and BigQuery for Natural Language Exploration of GCP Billing Data</a> was originally published in <a href="https://medium.com/teamsnap-engineering">TeamSnap Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Practical Applications of Generative AI]]></title>
            <link>https://medium.com/teamsnap-engineering/practical-applications-of-generative-ai-f23c5d0a4088?source=rss----c8de247e26d7---4</link>
            <guid isPermaLink="false">https://medium.com/p/f23c5d0a4088</guid>
            <category><![CDATA[generative-ai-use-cases]]></category>
            <category><![CDATA[generative-ai-solution]]></category>
            <category><![CDATA[vertex-ai]]></category>
            <category><![CDATA[google-cloud-platform]]></category>
            <category><![CDATA[generative-ai-development]]></category>
            <dc:creator><![CDATA[Steven Aldinger]]></dc:creator>
            <pubDate>Wed, 20 Dec 2023 21:00:02 GMT</pubDate>
            <atom:updated>2023-12-20T22:32:03.731Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>If you want to jump straight into code, check out <a href="https://github.com/stevenaldinger/generative-ai">stevenaldinger/generative-ai</a> on GitHub for a small but practical collection of ready-to-run Jupyter notebooks.</blockquote><p>It’s fascinating to see the sudden widespread interest around generative AI on platforms like LinkedIn. As an engineer, I can appreciate the discussions surrounding the topic, but I want to see more hands-on experimentation too.</p><p>Exploring its capabilities firsthand provided valuable insights for me, and this blog article and its <a href="https://github.com/stevenaldinger/generative-ai">companion repository</a> are intended to give a starting point, for anyone interested, to get that same experience themselves. I’m a Staff SRE over at <a href="https://medium.com/teamsnap-engineering">TeamSnap</a> and not an expert on generative AI, so the focus of this post is less about generative AI concepts, and more about <em>how low the barrier of entry currently is to start writing practical applications.</em> The repository contains an automated development environment and a handful of personal solutions that I hope will lower that barrier even further.</p><p>After reading this article and getting oriented with the companion repository, you should have a better idea of what opportunities exist at the very least. Best case, you’ll feel empowered to start applying generative AI to real world problems.</p><p>Here’s a teaser image from the <a href="#3330">World Pool-Billiard Association Rule Book Chat Bot</a> example to pique your interest. A similar looking chat bot is deployed in <a href="https://cloud.google.com/run">Google Cloud Run</a> as part of the Y<a href="#d2e3">ouTube Presentation Question-Answering</a> example.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/635/1*uPRI_XQRtU12f0d3LjpYpQ.png" /></figure><h3>Table of Contents</h3><ol><li><a href="#6a4d">Stack Overview</a></li><li><a href="#54ea">Applying Generative AI</a><br>1. <a href="#4538">Blog Content Generation</a> (with <a href="https://cloud.google.com/vertex-ai/docs/generative-ai/models/tune-text-models-supervised">supervised tuning</a> to create a custom model)<br>2. <a href="#cb38">Wikipedia-Connected ReAct Agent</a><br>3. <a href="#72aa">Valorant (Riot Games) FAQ and News Question-Answering</a><br>4. <a href="#3330">World Pool-Billiard Association Rule Book Chat Bot</a> (PDF source)<br>5. Y<a href="#d2e3">ouTube Presentation Question-Answering</a> (with bonus chat bot and deployable application on <a href="https://cloud.google.com/run?hl=en">Cloud Run</a>)<br>6. <a href="http://d14d/">Competitive Analysis Question-Answering</a> (with <a href="https://www.selenium.dev/">Selenium</a> to automatically drive a web browser for content gathering)<br>7. <a href="#6f6b">Engineering Incident Response Question-Answering</a> (Slack workspace history)<br>8. <a href="#1774">Repository-Aware Code Generation</a> (Copilot code generation but with the entire code base to work with instead of your open file)</li><li><a href="#8587">Next Steps for Non-Developers</a></li><li><a href="#4ba5">Next Steps for Developers</a></li></ol><h3>Stack Overview</h3><p>Let’s briefly run through the technologies that power the <a href="https://github.com/stevenaldinger/generative-ai">companion repository</a>. This stack allows me to automate away the technical burden for getting started, so anyone interested can focus on the generative AI concepts. The only thing you need to install is Docker. I kept this brief here, but there’s a more in-depth summary in the repository’s <a href="https://github.com/stevenaldinger/generative-ai/blob/main/README.md">README.md</a>.</p><ol><li><a href="https://www.docker.com/products/docker-desktop/">Docker</a> (❤️) for packaging up an operating system and all of the dependencies our code needs to function for development or production.</li><li><a href="https://www.terraform.io/">Terraform</a> for automatically setting up a Google Cloud project.</li><li><a href="https://jupyter-notebook-beginner-guide.readthedocs.io/en/latest/what_is_jupyter.html">Jupyter Notebook</a> for showcasing examples.</li><li><a href="https://cloud.google.com/vertex-ai">Vertex AI</a> for creating embeddings and leveraging Google’s models.</li><li><a href="https://www.langchain.com/">LangChain</a> for <a href="https://python.langchain.com/docs/use_cases/question_answering/">higher level tools</a> for working with generative AI.</li><li><a href="https://www.trychroma.com/">ChromaDB</a> for a persistent vector database.</li><li><a href="https://www.gnu.org/software/make/">Make</a> for hiding the complexity of the commands that operate the repository.</li></ol><h3>Applying Generative AI</h3><p>The remaining sections will cover all of the notebooks included in the code base and some examples of how it can be applied to real world cases.</p><p>A few terms are used here that are worth a review, but are not necessarily important to understand before playing with some code.</p><ol><li><a href="https://www.cloudflare.com/learning/ai/what-is-large-language-model/">Large Language Model</a> (LLM)</li><li><a href="https://research.ibm.com/blog/retrieval-augmented-generation-RAG">Retrieval Augmented Generation</a> (RAG)</li><li><a href="https://www.promptingguide.ai/techniques/zeroshot">Zero-Shot Prompting</a></li><li><a href="https://www.promptingguide.ai/techniques/fewshot">Few-Shot Prompting</a></li><li><a href="https://react-lm.github.io/">ReAct Prompting</a></li><li><a href="https://cloud.google.com/vertex-ai/docs/generative-ai/models/tune-models#supervised-tuning">Supervised Tuning</a></li><li><a href="https://www.pinecone.io/learn/vector-database/">Vector Database</a> (Embeddings Database)</li></ol><h3>Blog Content Generation</h3><p>Creating blog content is one of the most obvious applications of generative AI, and was probably the first use case to dominate the internet. LLMs are very capable of that sort of task out-of-the-box, so the level of effort to get something functioning with reasonable enough quality is extremely low.</p><p>Asking ChatGPT to write an article can have decent results, but if you want to generate an article every day or 100 at a time, you’ll immediately be subjected to the burden of manually copying and pasting things around. Additionally, it might take multiple attempts to get the voice or formatting to match what you’re really looking for.</p><p>The strategy used in the example code is to:</p><ol><li>Use few-shot prompting to generate 10 blog article titles per topic given a list of topics we want content for.</li><li>Use few-shot prompting to generate blog content for each article title in the specific voice and formatting we want, and save the generated content to files.</li><li>Manually review the output and adjust the prompt/regenerate content until it meets our quality expectations.</li><li>Use the generated content to fine-tune Google’s LLM to create our own custom model, eliminating the need for lengthy context passed into the prompt while improving overall results. The end result is an LLM with the ability to recognize a 1-line prompt, Article subject: Our Topic, and still output our desired voice and formatting.</li></ol><p>If you find yourself using the same lengthy few-shot prompt frequently, that may be a good candidate for tuning. Even if we can achieve what we need to without fine-tuning the model, the longer the prompt is, the more money it costs to run. Too long of a prompt can also lead to reduced quality of results if you push the limits, because the LLM has a finite amount it can keep track of.</p><p>If you’re able to leverage a preexisting data set, or take the time to manually (or otherwise) edit generated content, this same technique can be used to teach the model something it isn’t already good at, which could lead to business opportunities.</p><p><strong>Jupyter notebooks:</strong></p><ol><li><a href="https://github.com/stevenaldinger/generative-ai/blob/main/notebooks/blog-title-generation/blog-title-generation.ipynb">Blog Title Generation</a></li><li><a href="https://github.com/stevenaldinger/generative-ai/blob/main/notebooks/blog-article-generation/blog-article-generation.ipynb">Blog Article Generation</a></li><li><a href="https://github.com/stevenaldinger/generative-ai/blob/main/notebooks/blog-article-supervised-tuning/blog-article-supervised-tuning.ipynb">Blog Article Supervised Tuning</a></li></ol><h3>Wikipedia-Connected ReAct Agent</h3><p>The simplest example of Retrieval Augmented Generation (RAG) in the repository is a tap into Wikipedia (surely you didn’t ignore their <a href="https://donate.wikimedia.org/w/index.php?title=Special:LandingPage">donation request</a> this year, right?).</p><p>One of the most limiting factors people ran into early on with ChatGPT was that it wasn’t aware of anything after the last date of the data it was trained on. The general problem of wanting LLMs to search or process information outside of its original training set, is solved with the RAG technique.</p><p>This example isn’t particularly useful on its own, but it’s a great way to tip-toe into understanding how you can build something unique on top of common models like GPT.</p><p>This also demonstrates creating a ReAct agent, which means that that when we ask it a question, it’ll reason about what extra information it needs, fetch that extra context, and pass it into the next prompt alongside our question.</p><p><strong>Jupyter notebook:</strong> <a href="https://github.com/stevenaldinger/generative-ai/blob/main/notebooks/langchain-react-docstore-wikipedia/react-docstore-wikipedia-source.ipynb">ReAct Wikipedia Source with LangChain</a></p><h3>Valorant FAQ and News Question-Answering</h3><p>If your company has taken the time to compile a page or site dedicated to frequently asked questions or customer help, I have great news for you.</p><p>Google has an offering called <a href="https://programmablesearchengine.google.com/about/">Programmable Search Engine</a> that lets you easily configure a custom search engine for whatever site or collection of sites you’d like it to cover. Pair that with our beloved RAG technique, and you can instantly turn your FAQ pages and other content into a question-answering chain that, in my experience, works magnitudes better than whatever search bar may already exist on the page, and can instantly provide an answer instead of a having potentially aggravated customer sift through search result links.</p><p>Just like the supervised tuning example earlier, this strategy can be extended to make it your own. Programmable Search Engine supports any public site. Swap out the FAQ page in favor of the Studio Ghibli Fandom Wiki, and suddenly your LLM will be able to confidently answer your deepest questions about <a href="https://ghibli.fandom.com/wiki/Totoro">Totoro</a>.</p><p><strong>Jupyter notebook:</strong> <a href="https://github.com/stevenaldinger/generative-ai/blob/main/notebooks/langchain-react-zero-shot-custom-search-engine/react-zero-shot-custom-search-engine.ipynb">Programmable Search Engine with LangChain</a></p><h3>World Pool-Billiard Association Rule Book Chat Bot</h3><p>The Wikipedia and Valorant FAQ examples both rely on 3rd party resources for the content they’re retrieving. That limits us a lot in what we can build as a tradeoff for the convenience of writing a simpler application.</p><p>Many tools such as <a href="https://www.atlassian.com/software/confluence">Confluence</a> support PDF exports, so being able to integrate LLMs with arbitrary PDF files can create some interesting opportunities. The downside of having our own PDF files to search is that we need to introduce some complexity to make the data understandable and searchable to the LLM.</p><p>Making the data LLM-friendly requires creating <a href="https://www.cloudflare.com/learning/ai/what-are-embeddings/">embeddings</a>, and then storing those embeddings in a queryable database. This example uses <a href="https://www.trychroma.com/">ChromaDB</a> as the database and also demonstrates persisting the embeddings so you can re-run notebooks without spending the time and money creating them multiple times. Generating embeddings for a single page PDF is nearly instant and won’t burn a hole in your pocket, but one of my real-world experiments took over <em>8 hours</em> to create and store the embeddings for. Getting comfortable with persistence concerns up front even with smaller projects can make quality of life a noticeable bit better.</p><p>This example reads in the World Pool-Billiard Association’s rule book, answers questions like “Who shoots first in pool?” or “What is eight ball?”, and also features a chat bot user interface.</p><p><strong>Jupyter notebook</strong>: <a href="https://github.com/stevenaldinger/generative-ai/blob/main/notebooks/langchain-react-zero-shot-pdf/react-zero-shot-pdf-source.ipynb">ReAct Zero-Shot from PDF Source with LangChain</a></p><h3>YouTube Presentation Question-Answering</h3><p>My wonderful mother is Queen of the Genealogy Nerds (Marshal of the <a href="https://www.magnacharta.com/bomc/">Baronial Order of Magna Charta</a>) and told me about our ancestor William Marshal (coincidental last name). I wanted to tie something in that she’d be able to relate to, so this trio of examples demonstrates a handful of useful concepts while working with a transcript pulled from YouTube’s API for <a href="https://www.youtube.com/watch?v=cTjQp_TQlXo">The Greatest Knight That Ever Lived: William Marshal</a>, published by <a href="https://www.youtube.com/@DanDavisHistory">DanDavisHistory</a>.</p><p>There are two individual Jupyter notebooks covering this topic, one using <a href="https://cloud.google.com/vertex-ai/docs/generative-ai/model-reference/text">text-bison</a>, and the other <a href="https://cloud.google.com/vertex-ai/docs/generative-ai/model-reference/text-chat">chat-bison</a>, and each makes use of a different method for implementing retrieval augmentation with LangChain. This is the only topic that was covered with two different models (one for regular text input, and one specialized for chat bots), so it’s a valuable example to look at to better understand which pieces of code and concepts are identical between the two models and which pieces required changes.</p><p>Additionally, this shows how to create and query a vector database directly by similarity and max marginal relevance, and how to create and query a retrieval question-answering LLM chain (2 different strategies) as well as another zero-shot ReAct agent.</p><p>AI code aside, one of the more useful pieces of this is that it demonstrates how to put a convenient graphical user interface in front of LLM code for nice looking demonstrations with minimal effort.</p><p>Arguably the best part, since it’s no fun sending screenshots of localhost to parents, is that the chat-bison example was used to create a containerized chat bot application with a user interface that can be deployed on Google Cloud Run with the included Terraform code. It’s absolutely not a production-ready example, but it gives a working example of what deployed code might look like compared to a notebook, even with it’s local vector database baked into the Docker image.</p><p><strong>Jupyter notebooks:</strong></p><ol><li><a href="https://github.com/stevenaldinger/generative-ai/blob/main/notebooks/langchain-react-zero-shot-youtube/react-zero-shot-youtube-transcript.ipynb">ReAct Zero-Shot from YouTube Transcript</a></li><li>R<a href="https://github.com/stevenaldinger/generative-ai/blob/main/notebooks/langchain-react-zero-shot-youtube/react-zero-shot-youtube-transcript-chat.ipynb">eAct Zero-Shot from YouTube Transcript Chat Bot</a></li></ol><h3>Competitive Analysis Question-Answering</h3><p>The ability to ask questions about websites is useful for things like searching Wikis, but with just a little bit of supporting code on the side, can also help you with competitive analysis. Keep an eye out for competition and automatically extract information about their offerings and pricing.</p><p>This example demonstrates fetching marketing page content to feed into the LLM, with <a href="https://www.selenium.dev/">Selenium</a> driving a headless Firefox browser. The modern web makes heavy use of Javascript for rendering content, and Selenium is a perfect tool to handle that reality.</p><p>A list of URLs get passed into one of LangChain’s document loaders for this example, and the end result is the ability to ask questions about the site content like “What services are offered?” and “What pricing tiers are available?” It would take some work, but this example could be extended to run weekly searches for new and existing competitors in a space, and then automatically generate summarized reports of its discoveries.</p><p><strong>Jupyter notebook:</strong> <a href="https://github.com/stevenaldinger/generative-ai/blob/main/notebooks/langchain-selenium-url/react-zero-shot-selenium-url.ipynb">React Zero-Shot from URL Sources with LangChain</a></p><h3>Engineering Incident Response Question-Answering</h3><p>Depending on how your team/company/group of friends operate, slack channels may or may not be a gold mine of information, with the stream of valuable discussions and knowledge-sharing consistently getting buried in chaos the day after it’s written.</p><p>If that resonates with you at all, go through <a href="https://slack.com/help/articles/201658943-Export-your-workspace-data">Slack’s export steps</a> and give this Jupyter notebook a try. I can confirm it’s possible to export all of the text from public channel conversations and threads, so let your mind run wild.</p><p>You might be able to create an AI assistant that knows how to respond to incidents that have had solutions discussed in Slack, or that can look up the support context for a particular customer.</p><p>This example reads in incident response channels and responds to questions like “What should I do if an anomaly monitor resolves?” based on historical conversations from the channels.</p><p><strong>Jupyter notebook:</strong> <a href="https://github.com/stevenaldinger/generative-ai/blob/main/notebooks/langchain-react-zero-shot-slack/react-zero-shot-slack-source.ipynb">ReAct Zero-Shot from Slack Chat History with LangChain</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/822/1*U0aV29a3Caqd9JdmMNHvAA.png" /></figure><h3>Repository-Aware Code Generation</h3><p>Last but certainly not least, you may be interested in trying to integrate LLMs with your code bases. There are two examples available to play with here, with code repositories either ingested from files on your computer, or from scraping public or private GitHub repositories.</p><p><a href="https://github.com/features/copilot">Copilot</a> has boosted my productivity tremendously, and it is one of my favorite tools. <em>However, </em>as we discovered with the other examples in the companion repository, LLMs have limited power when we’re only able to work with prompts. The real fun starts when we introduce an embeddings database and are suddenly able to search over way more context than could ever have fit in a prompt.</p><p>These examples demonstrate reading in and generating embeddings for entire code bases, to be stored in ChromaDB for more powerful generation. Copilot combines chat bot features with code generation, but the focus for these notebooks is solely on quality code generation with <a href="https://cloud.google.com/vertex-ai/docs/generative-ai/model-reference/code-generation">code-bison</a>. I had decent luck generating code that was conforming to the style the rest of the code base adhered to, as well as code that was importing and integrating existing code from other files. I was also able to generate React components for one of my front-end repos using this method that managed to use the right <a href="https://redux-toolkit.js.org/rtk-query/usage/queries">RTK Query</a> calls to make use of my existing API client code, which makes me optimistic about the near future of code generation.</p><p>LangChain doesn’t appear to support Google’s <a href="https://cloud.google.com/vertex-ai/docs/generative-ai/model-reference/code-chat">codechat-bison</a> yet, but if I notice that available at some point I’ll update this to show how to make your own repo-aware Copilot chat experience.</p><p>Jupyter notebooks:</p><ol><li><a href="https://github.com/stevenaldinger/generative-ai/blob/main/notebooks/langchain-local-repo-code-generation/langchain-local-repo-code-generation.ipynb">Local Code Repo Context for Code Generation with LangChain</a></li><li><a href="https://github.com/stevenaldinger/generative-ai/blob/main/notebooks/langchain-github-repo-code-generation/langchain-github-repo-code-generation.ipynb">Remote GitHub Repo Context For Code Generation with LangChain</a></li></ol><h3>Next Steps for Non-Developers</h3><p>If you’re inspired and want to run these examples and potentially work with some code:</p><ol><li>Learn <a href="https://support.apple.com/guide/terminal/open-or-quit-terminal-apd5265185d-f365-44cb-8b09-71a064a42125/mac">how to open a terminal in MacOS</a> or <a href="https://www.geeksforgeeks.org/how-to-open-terminal-in-linux/">Linux</a></li><li>Learn <a href="https://www.geeksforgeeks.org/cd-command-in-linux-with-examples/">how to move to different folders</a> in the terminal</li><li>Learn <a href="https://www.geeksforgeeks.org/ls-command-in-linux/">how to list the contents of a folder</a> in the terminal</li><li>Install <a href="https://docs.github.com/en/desktop/installing-and-authenticating-to-github-desktop/installing-github-desktop?platform=mac">GitHub Desktop</a> and <a href="https://docs.github.com/en/desktop/adding-and-cloning-repositories/cloning-and-forking-repositories-from-github-desktop?platform=mac">clone (download) the code repository</a></li><li>Optionally go through <a href="https://www.learnpython.org/">https://www.learnpython.org/</a> from <em>Hello, World! </em>through<em> Modules and Packages</em></li><li>Dive into the repository’s <a href="https://github.com/stevenaldinger/generative-ai/blob/main/README.md">READM</a>E and try using ChatGPT to better understand what the instructions are telling you to do</li></ol><h3>Next Steps for Developers</h3><p>Play with the examples and change a few things to make them your own. Try modifying examples to work with your own prompts, PDFs, Slack workspace exports, or your own <a href="https://programmablesearchengine.google.com/about/">Programmable Search Engine</a> to point to your company’s FAQ page.</p><p>Think about the blog generation article and the power of using the generated output of one prompt as the input into another. Something that seems like it can’t be automated might be possible with a clever chain of various fine-tuned models or specialized models.</p><p>Find a PDF rule book for a board game you want to play and have an AI assistant to make it easier to get the hang of or settle disagreements if you’re an extra competitive bunch.</p><p>Try combining several examples. The examples only pass in a single tool to the ReAct agents, but you could combine the Slack export example and the PDF example for instance, but swapping in a PDF Confluence export or other knowledge base, to create an internal question-answering bot.</p><p>Create embeddings from your own GitHub repositories and have a context aware AI code generator.</p><p>Check out <a href="https://python.langchain.com/docs/integrations/document_loaders">LangChain’s supported document loaders</a> and see if it inspires some innovative thoughts.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f23c5d0a4088" width="1" height="1" alt=""><hr><p><a href="https://medium.com/teamsnap-engineering/practical-applications-of-generative-ai-f23c5d0a4088">Practical Applications of Generative AI</a> was originally published in <a href="https://medium.com/teamsnap-engineering">TeamSnap Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Consuming a KMP dependency on iOS using SPM]]></title>
            <link>https://medium.com/teamsnap-engineering/consuming-a-kmp-dependency-on-ios-using-spm-c45c343e406b?source=rss----c8de247e26d7---4</link>
            <guid isPermaLink="false">https://medium.com/p/c45c343e406b</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[kmp]]></category>
            <category><![CDATA[spm]]></category>
            <dc:creator><![CDATA[Alejandro Moya]]></dc:creator>
            <pubDate>Tue, 05 Sep 2023 13:22:35 GMT</pubDate>
            <atom:updated>2023-09-05T13:22:35.658Z</atom:updated>
            <content:encoded><![CDATA[<p>In our previous post, <a href="https://medium.com/teamsnap-engineering/consuming-a-private-kmp-dependency-from-github-f91264346879">consuming a Private KMP dependency from GitHub</a>, we explained how to consume the iOS version of the KMP library using cocoapods. After writing that post and before writing <a href="https://medium.com/teamsnap-engineering/the-kmp-implementation-at-teamsnap-6b8b146f003f">The KMP implementation at TeamSnap</a> we switched to using SPM as we want to stop using `cocoapods`. An attentive reader pointed this out, and since we want to help everyone in the community that would need it, here we go!</p><p>If you went through <a href="https://medium.com/teamsnap-engineering/setting-up-a-kmp-shared-library-5f596afc6e09">Setting up a KMP shared library</a> there are 2 sections that talk about configuring the specifics of the library compilation, one is the version catalogs and the other is the gradle scripts, we didn’t cover the iOS `cocoapods` configuration on the version catalogs as we wanted to give you the freedom of being able to put what you like on catalogs and what you prefer to have on the scripts.</p><p>In this post we are going to use version catalogs as they are now a supported feature on Android Studio since Giraffe.</p><h4>Version catalogs</h4><p>We are going to add a new version catalog file named strings.versions.toml . Below is an example of the catalog contents:</p><pre>[versions]<br><br>ios-summary = &quot;My library&quot;<br>ios-authors = &quot;My company&quot;<br>ios-homepage = &quot;https://myhomepage.com/path&quot;<br>ios-deployment-target = &quot;14.0&quot;<br>ios-basename = &quot;MySharedLibrary&quot;<br></pre><p>You can add any text definition on this file that would be used on the scripts, this will reduce having fixed texts on the scripts.</p><h4>Gradle scripts</h4><p>Don’t forget to add this new version catalog to the list that you have on settings.gradle.kts at the project root:</p><pre>dependencyResolutionManagement {<br>...<br>  versionCatalogs {<br>    ...<br>    create(&quot;strings&quot;) {<br>      from(files(&quot;./catalogs/strings.versions.toml&quot;)<br>    }<br>    ...<br>  }<br>  ...<br>}</pre><p>Now sync your Gradle files and you should have the new version catalog available.</p><p>Now we can add the configuration from the version catalog to the required places, open build.gradle.kts on the shared module, in the Kotlin section you’ll find this or something similar:</p><pre>kotlin {<br>  ...<br>  configure(listOf(iosX64, iosArm64, iosSim)) {<br>    binaries {<br>      framework {<br>        // Any dependecy you add for ios should be added here using export()<br>        export(commonlibs.kotlin.stdlib)<br>        xcf.add(this)<br>      }<br>    }<br>  }<br>  ...<br>  cocoapods {<br>    val iosDefinitions = commonlibs.versions.ios<br>    name = iosDefinitions.basename.get()<br>    summary = iosDefinitions.summary.get()<br>    homepage = iosDefinitions.homepage.get()<br>    authors = iosDefinitions.authors.get()<br>    version = commonlibs.versions.library.version.get()<br>    ios.deploymentTarget = iosDefinitions.deployment.target.get()<br>    framework {<br>      baseName = iosDefinitions.basename.get()<br>      isStatic = false<br>      transitiveExport = true<br>      embedBitcode(BITCODE)<br>    }<br>    specRepos {<br>      url(https://medium.com/&quot;https://github.com/user/repo.git&quot;) // Use your repo here<br>    }<br>    publishDir = rootProject.file(&quot;./&quot;)<br>  }<br>  ...<br>}<br></pre><p>This previous snippet is part of what we left as an example on the previous post but we didn’t dive into the specifics of the configuration, this is the new setup:</p><pre>kotlin {<br>  val iosStrings = strings.versions.ios<br>  ...<br>  configure(listOf(iosX64, iosArm64, iosSim)) {<br>    binaries {<br>      framework {<br>        // Any dependecy you add for ios should be added here using export()<br>        export(commonlibs.kotlin.stdlib)<br>        xcf.add(this)<br>        baseName = iosStrings.basename<br>      }<br>    }<br>  }<br>  ...<br>  cocoapods {<br>    name = iosStrings.basename.get()<br>    summary = iosStrings.summary.get()<br>    homepage = iosStrings.homepage.get()<br>    authors = iosStrings.authors.get()<br>    version = commonlibs.versions.library.version.get()<br>    ios.deploymentTarget = iosStrings.deployment.target.get()<br>    framework {<br>      baseName = iosStrings.basename.get()<br>      isStatic = false<br>      transitiveExport = true<br>      embedBitcode(BITCODE)<br>    }<br>    specRepos {<br>      url(https://medium.com/&quot;https://github.com/user/repo.git&quot;) // Use your repo here<br>    }<br>    publishDir = rootProject.file(&quot;./&quot;)<br>  }<br>  ...<br>}</pre><p>We switched to the new strings catalog and also applied the existing configurations, but we also added a new one on the binaries.framework section, as you can see, you have 3 places that share the same configuration:</p><ol><li>binaries.framework.basename</li><li>cocoapods.name</li><li>cocoapods.framework.basename</li></ol><p>It’s important to sync these names, otherwise, the library won’t compile and you would also find difficult to know the name of the framework package.</p><p>Now once you process the release the library should be available on your repo as MySharedLibrary.xcframework , with your podspec file as usual.</p><p>Now, let’s create the Package.swift file to enable SPM to look for the framework binary:</p><pre>// swift-tools-version: 5.6<br>// The swift-tools-version declares the minimum version of Swift<br>// required to build this package.<br>import PackageDescription<br><br>let package = Package(<br>  name: &quot;MySharedLibrary&quot;,<br>  platforms: [.iOS(.v14)],<br>  products: [<br>    .library(<br>      name: &quot;MySharedLibrary&quot;,<br>      targets: [&quot;MySharedLibrary&quot;]<br>    ),<br>  ],<br>  dependencies: [],<br>  targets: [<br>    .binaryTarget(name: &quot;MySharedLibrary&quot;,<br>            path: &quot;./MySharedLibrary.xcframework&quot;),<br>  ]<br>)</pre><p>Save Package.swift at the root of the project/repo, push the changes and release a new version of your library. This first version that contains the Package.swift file will be visible to SPM.</p><p>Now remove the cocoapods setup for the library on your ios project by removing the dependency on the podfile and running pod install. After this, on Xcode, go to File -&gt; Add packages, on the search field paste the url of your private git repo, it will ask you for your github credentials if you didn’t add them, it would be a good idea to add them on the Xcode settings prior to doing it as this prevents any issue on installing and updating the library later, this won’t be a problem on the CI as it will use the existing git configuration. You should see the package available in the list of packages, set the dependency rule to either exact version or to any desired version tag range setting, don’t use commit or branch as you already release the library using version tags. Set the minimum or exact version to the one you just processed and set the add to project option to the project you had setup the library using cocoapods previously. Now hit the Add package button and enjoy consuming the KMP library from SPM.</p><p>As you might have guessed, the most important thing is to set the library basename, use that on the Package.swift file and release a version that contains this package file on the repo. Once you do all this, you’ll have an SPM compatible library, and the best of all is that this is a binary libary, the package file is set to consume the library as a binary target and you will get it in that way on the project, no need to compile the sources again and again!.</p><p>We love sharing the knowledge we got from implementing KMP with the community, if you have any question just leave a comment and we will give our best to answer them.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c45c343e406b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/teamsnap-engineering/consuming-a-kmp-dependency-on-ios-using-spm-c45c343e406b">Consuming a KMP dependency on iOS using SPM</a> was originally published in <a href="https://medium.com/teamsnap-engineering">TeamSnap Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The KMP implementation at TeamSnap]]></title>
            <link>https://medium.com/teamsnap-engineering/the-kmp-implementation-at-teamsnap-6b8b146f003f?source=rss----c8de247e26d7---4</link>
            <guid isPermaLink="false">https://medium.com/p/6b8b146f003f</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[kmp]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Alejandro Moya]]></dc:creator>
            <pubDate>Thu, 24 Aug 2023 17:49:57 GMT</pubDate>
            <atom:updated>2023-08-24T17:49:57.288Z</atom:updated>
            <content:encoded><![CDATA[<p>On previous posts we explained how to <a href="https://medium.com/teamsnap-engineering/setting-up-a-kmp-shared-library-5f596afc6e09">setup a KMP library</a> and <a href="https://medium.com/teamsnap-engineering/consuming-a-private-kmp-dependency-from-github-f91264346879">consume it from our iOS and Android projects</a>. Now we are going to show you some details on the TeamSnap implementation, as we are moving our business logic to KMP in small steps and without breaking the existing codebase in the process.</p><p>Our original codebase is, as with many of the native apps that we can find in the app stores on Android and iOS, built using the respective SDKs. This means that we have a project for each platform, and each project has it’s own codebase. While the UX on each platform could be different as the standards differ, the business logic is the same, the connection to the backend, the business logic, the databases and objects we use to handle all the UX interactions, everything under the hood is or could be the same.</p><p>In cross-platform there are different options for building mobile apps. You have frameworks that use html and other web languages to build these apps and you also have frameworks that use native solutions to build them. We prefer to stay native, to avoid consuming more resources on the users device, and since we want to keep the experience on each platform as close to the UX standards as possible, we found that keeping our existing projects for the UX would be ideal, and merging the business logic into one codebase would be the wise move. Compared to other solutions, KMP was an easy choice. Here are a few reasons why:</p><p>Flexibility on the implementation:</p><ul><li>You can choose to implement any part of your business logic or even go full cross-platform with KMP.</li><li>You can start a new project or integrate the KMP project in different ways on your existing projects.</li><li>You can build common and specific platform code on the KMP project.</li></ul><p>Language benefits:</p><ul><li>On KMP you can reuse much of the Android code on KMP, meaning that you will find yourself often just copy/pasting your existing Android code.</li><li>Similarities with Swift make the learning curve more friendly for iOS developers.</li></ul><p>Performance:</p><ul><li>For Android a KMP library is just a regular Android library, no extra integrations needed.</li><li>For iOS a KMP library is an Objective C compiled library with Swift friendly implementations. In some cases we might have to add a few extra dependencies to implement cool features, but nothing we don’t usually do on native coding.</li><li>One more thing to note on the performance side is that on iOS the perceived performance is superior to other solutions.</li></ul><p>So, we originally had our projects setup in the following way:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rkeRGGRqkk5VqTtiZaJ2Vw.png" /></figure><p>Each with their own repository, each with their own codebase.</p><p>One of the issues when making a decision about an existing codebase is how many changes you’ll have to make to integrate something on your existing architecture, and also, you don’t want to degrade the UX and the development experience. If you have to build an entire new codebase or move your current codebase in one step, that would probably result in many issues for both, end users and developers.</p><p>This is why we started slowly, in fact we started by just adding some constants on the shared codebase. Our own experience showed us that the best is always to start on the smallest possible project you can take to share code, and the smallest thing would be just a few constants that would be used on both platforms. It’s even better if these constants are new, something you didn’t have previously.</p><p>After that you can start by adding the new architecture you want to implement, always in small steps, do not try to go full Jedi mode on the first pass, it’s like building your new dream home in the same grounds of your existing one (For the home renovations shows fans).</p><p>Another thing you need when starting a shared codebase is to have all the team involved, everyone needs to review these changes, the more eyes the better. Make sure that at least one Android and iOS developer are looking at the new code, and make as many iterations as needed to check that the changes are accepted and working on both platforms, this will ensure the success of the new implementation.</p><p>After these initial iterations we were able to add the foundations of the new architecture and started to implement small pieces of business logic, now we can take bigger projects that will live on the shared codebase and also start to migrate the code we need from the specific platforms.</p><p>The final result is keeping our original projects intact, nothing changes there, except a few helper methods or new external dependencies. The new codebase has its own repository, much like any other external dependency we could consume like Alamofire on iOS or Retrofit on Android. This also makes the implementation on each platform more flexible as each platform team could be working on different features and could use different versions of the shared library.</p><p>You could be asking - what’s the final result?, well, the graphic below shows the target goal for our KMP implementation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QpPhvK-dRmW3QUDDXpe2Tw.png" /></figure><p>We are far from reaching this stage, but we started and all the team is excited about making these changes. As you can see, the original projects and repositories still exist, but the business logic, cache and network moves to the new repository. We still leave some specific business logic on each platform, and this is expected. One advantage in this is that we can take the best of each platform and move it to the new shared codebase, also, as this new codebase does not contain any UI code, we can add as many unit tests as we like, code coverage was never that easy. Working on a big project that contains UI and business logic tends to make code coverage a problem, the same happens with clean coding practices, you have so many things mixed that you lose track at some point. This new approach helps reduce the mix by completely separating things and also helps to review and optimize the original codebases by moving the best parts and reducing the amount of code.</p><p>Another benefit for us developers is the infamous compilation time, when you have all your code on the same project, you have to compile everything, it doesn’t matter if the code didn’t change, the compiler still has to evaluate if things changed. That takes time, and moving the code to a compiled library reduces compilation time in big numbers. Each piece of code you move to the shared codebase will get compiled for both platforms once, after that, when you consume them on each platform, you won’t need to compile them again.</p><p>We will share more KMP goodies in the future. Stay tuned.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6b8b146f003f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/teamsnap-engineering/the-kmp-implementation-at-teamsnap-6b8b146f003f">The KMP implementation at TeamSnap</a> was originally published in <a href="https://medium.com/teamsnap-engineering">TeamSnap Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Consuming a Private KMP dependency from github]]></title>
            <link>https://medium.com/teamsnap-engineering/consuming-a-private-kmp-dependency-from-github-f91264346879?source=rss----c8de247e26d7---4</link>
            <guid isPermaLink="false">https://medium.com/p/f91264346879</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[kmm]]></category>
            <category><![CDATA[github]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Alejandro Moya]]></dc:creator>
            <pubDate>Mon, 07 Aug 2023 14:02:02 GMT</pubDate>
            <atom:updated>2023-08-07T14:02:01.699Z</atom:updated>
            <content:encoded><![CDATA[<h3>Consuming a Private KMP dependency from GitHub</h3><p>Our previous post explained how to create a private KMP library on github without having to share the same repository for the Android and iOS project. This wouldn’t be complete without explaining how to consume the library from each platform. Well, this post will give you the configuration needed for the Android and iOS project to work.</p><h3>The Android configuration</h3><p>On the root build.gradle or build.gradle.kts you’ll find the repositories:</p><pre>allProjects {<br>  repositories {<br>    google()<br>    mavenCentral()<br>    ...<br>    }<br>}</pre><p>We need to add the private maven repo there:</p><ul><li>build.gradle.kts :</li></ul><pre>allprojects {<br>    repositories {<br>        ...<br>        maven {<br>            url = URI(&quot;https://maven.pkg.github.com/USER/REPO&quot;)<br>            credentials {<br>                username = System.getenv(&quot;MYUSER&quot;)<br>                password = System.getenv(&quot;MYPAT&quot;)<br>            }<br>        }<br>    }<br>}</pre><ul><li>build.gradle :</li></ul><pre>allprojects {<br>    repositories {<br>        ...<br>        maven {<br>            url &#39;https://maven.pkg.github.com/USER/REPO&#39;<br>            credentials {<br>                username = &quot;${System.getenv(&quot;MYUSER&quot;)}&quot;<br>                password = &quot;${System.getenv(&quot;MYPAT&quot;)}&quot;<br>            }<br>        }<br>    }<br>}</pre><p>As you can see on the scripts again, we see the MYUSER and MYPAT environment variables, each user will add these to their computer with their own github user and private access token with access to the private repo.</p><p>This works for mac, windows and linux, as long as the user adds the environment variables to their system environment variables configuration, they will have access to the repo.</p><p>After this, they can add the library as a regular dependency using api or implementation , depending on how you set the package name it should look like this:</p><pre>implementation(&quot;com.example.mylibrary:shared-android:0.0.1&quot;)</pre><p>This finishes the Android project configuration.</p><h3>The iOS project configuration</h3><p>There are a few options available on mac to achieve the same behaviour, you could use the same approach as on Android by using the environment variables, I’ve used that option in the past, but there’s a catch if you have a project that runs on CI. using environment variables on cocoapods exposes the information on the console output. This is due to cocoapods using git commands to retrieve the dependencies from each repo.</p><p>So, which option is better for cocoapods?</p><p>The answer is git credentials. And how?</p><p>The answer is a terminal command:</p><pre>git config --global credential.helper store</pre><p>After running this command, you can add the dependency to your pod file as any other regular dependency, in the case of the KMP library you would use the name and basename parameters under the cocoapods configuration on the gradle script file:</p><pre>pod &#39;MySharedLibrary&#39;, :git =&gt; &#39;https://github.com/USER/REPO.git&#39;, :tag =&gt; &#39;0.0.1&#39;</pre><p>Once you add this to the pod file and save it you can run pod install as usual, you’ll get asked about the credentials, once you complete the credentials those will be saved for git to use them in the future. Remember you can’t use your password on git, you’ll have to create a PAT to be able to use this feature.</p><p>Well, that completes the configuration, you can now consume your KMP library from Android and iOS, you can keep working on your projects as usual, and you can now share a codebase that is built as native libraries for each platform. We at TeamSnap use this successfully and each mobile platform team enjoys the benefits of having a single codebase for some of our architecture. As always, leave your comments and we’ll read and answer as we can.</p><p>Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f91264346879" width="1" height="1" alt=""><hr><p><a href="https://medium.com/teamsnap-engineering/consuming-a-private-kmp-dependency-from-github-f91264346879">Consuming a Private KMP dependency from github</a> was originally published in <a href="https://medium.com/teamsnap-engineering">TeamSnap Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Setting up a KMP shared library]]></title>
            <link>https://medium.com/teamsnap-engineering/setting-up-a-kmp-shared-library-5f596afc6e09?source=rss----c8de247e26d7---4</link>
            <guid isPermaLink="false">https://medium.com/p/5f596afc6e09</guid>
            <category><![CDATA[kotlin-multiplatform]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Alejandro Moya]]></dc:creator>
            <pubDate>Tue, 01 Aug 2023 18:38:40 GMT</pubDate>
            <atom:updated>2023-08-01T18:38:40.034Z</atom:updated>
            <content:encoded><![CDATA[<p>Long time no see my fellowship 😉. It’s been a while, but I have something I think many will like to read and apply to their own projects.</p><p>At TeamSnap we started using KMP (Kotlin Multiplatform) to share some common code between mobile platforms, keeping everything native so that our users enjoy the best performance on their apps. While the usual tutorials from the lords of the Jetbrains (see what I did there?) and other sources explain how to create an entire mobile project using KMP, or having the code for each platform on the same repo, this one will show you several things like, creating an independent KMP shared library, also to consume it from your existing Android and iOS projects as if it was any other regular dependency, and to top it all, to have all this done on a private repository on GitHub with tests, code coverage and publish actions; yes, it’s a lot, but this setup makes things a lot easier than having to create an entire new project or reorganize everything to have it on the same repo.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*gRB4_gT8gHLnIaG3j7e4GQ.jpeg" /></figure><p>We are going to divide this post into 5 sections to have clear steps for the setup:</p><ol><li>Create the project.</li><li>Version Catalogs</li><li>Gradle Scripts</li><li>Tests Action</li><li>Publish Action</li></ol><p>Ok, let’s start by explaining the existing setup, you already have an iOS and Android project, each has its own repo, the ios project is using cocoapods for dependencies, the Android project uses the good ol’ maven/gradle for the same purpose. This is not going to change, the idea behind this setup is that nothing changes on the existing projects, this makes the initial integration far lighter, making all the developers in the team happier.</p><h3>Create the project</h3><p>Now, let’s create the KMP shared library by using <a href="https://developer.android.com/studio">Android Studio</a>:</p><ul><li>Install the <a href="https://plugins.jetbrains.com/plugin/14936-kotlin-multiplatform-mobile">KMP plugin</a></li><li>Install the <a href="https://plugins.jetbrains.com/plugin/8195-toml">TOML plugin</a></li><li>Make sure you are using at least Android Studio Flamingo and kotlin 1.8.20 as that will ensure the best feature set available for both platforms.</li><li>Create a new project:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/549/1*g3E83tsgnb5RJzF3svYRAQ.png" /></figure><ul><li>Select the Kotlin Multiplatform Library</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1012/1*yZU8bKiLcMSlfAW9NhURUg.png" /></figure><ul><li>Configure the basics</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IGHIFJTjH2mRMSbAXQRsOA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IfIlnX53eWNUzxoVXzOYmQ.png" /></figure><ul><li>Once you finish the assistant you should have this folder structure:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/419/1*QGCUt5Az70XB2ip486cplg.png" /></figure><p>This is the basic project setup, it will leave you with a KMP library that could be built for iOS and Android, but we need more, we need to publish this library somewhere we can consume from on our iOS and Android projects. So, let’s start with the project configuration:</p><p>Lets check the gradle.properties file, it should look like the following:</p><pre>#Gradle<br>org.gradle.jvmargs=-Xmx2048M -Dfile.encoding=UTF-8 -Dkotlin.daemon.jvm.options\=&quot;-Xmx2048M&quot;<br>org.gradle.java.installations.fromEnv=JDK_17<br>org.gradle.configureondemand=true<br>org.gradle.daemon=true<br>org.gradle.parallel=true<br>org.gradle.workers.max=8<br>java.mainToolchainVersion=17<br>java.modularToolchainVersion=17<br><br>#Kotlin<br>kotlin.code.style=official<br><br>#Android<br>android.useAndroidX=true<br>android.nonTransitiveRClass=true<br><br>#MPP<br>kotlin.mpp.enableCInteropCommonization=true<br>kotlin.mpp.androidSourceSetLayoutVersion=2</pre><p>We are using java 17, setting parallel builds enabled, also we are using the new Android source set layout. With this you finished creating the project.</p><h3>The Version Catalogs</h3><p>First we will configure the project to use catalog files (<a href="https://docs.gradle.org/current/userguide/platforms.html">here is the official documentation</a>), these files help reduce the boilerplate on the script files by moving dependencies out of them and into a dedicated file that will contain groups of libraries with versions.</p><p>You’ll create a directory on the root of the project, in our case we named it catalogs, and inside this you’ll create a file named common.versions.toml, you’ll open this file and add the required libraries and versions for your project:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/582/1*Yg-Bc71d8VWrYxHhz7ePhA.png" /></figure><pre>[versions]<br>library-group = &quot;com.my.library&quot;<br>library-version = &quot;0.0.1&quot;<br>android = &quot;8.0.2&quot;<br>kotlin = &quot;1.8.20&quot;<br>kover = &quot;0.6.1&quot;<br>ksp = &quot;1.8.20-1.0.11&quot;<br><br>[libraries]<br>kotlin-stdlib = { module = &quot;org.jetbrains.kotlin:kotlin-stdlib-common&quot;, version.ref = &quot;kotlin&quot; }<br><br>[plugins]<br>multiplatform = { id = &quot;org.jetbrains.kotlin.multiplatform&quot;, version.ref = &quot;kotlin&quot; }<br>kotlin-android = { id = &quot;org.jetbrains.kotlin.android&quot;, version.ref = &quot;kotlin&quot; }<br>android-lib = { id = &quot;com.android.library&quot;, version.ref = &quot;android&quot; }<br>android-app = { id = &quot;com.android.application&quot;, version.ref = &quot;android&quot; }<br>kover = { id = &quot;org.jetbrains.kotlinx.kover&quot;, version.ref = &quot;kover&quot; }</pre><p>We left an example of the basics needed to have the project build, you can extend this by adding several multiplatform libraries, <a href="https://github.com/terrakok/kmm-awesome">here’s a link to a list of handy KMP libraries</a>.</p><p>Now you need to import this catalog on the gradle scripts. On the root of your project you’ll find a file named settings.gradle.kts , open the file and add the following snippet:</p><pre>dependencyResolutionManagement {<br>    repositories {<br>        google()<br>        mavenCentral()<br>    }<br>    versionCatalogs {<br>        create(&quot;commonlibs&quot;) {<br>            from(files(&quot;./catalogs/common.versions.toml&quot;))<br>        }<br>    }<br>}</pre><p>The versionCatalogs block imports common.versions.toml with the commonLibs name, you will use this name to access every dependency saved on this catalog. With that you have the version catalogs done!.</p><h3>Gradle Scripts</h3><p>We are getting closer to have a working KMP project. Before we get to add our code we need to setup the gradle scripts to be able to compile, test and release versions of our library, we’ll cover this configuration here.</p><p>We created this project and added the catalog files, we can commit the changes to our github repo and continue. We tried to break the post in short chunks of configurations to allow you to do this, as this will help you get things done separately and in well defined steps, the git history would also be clean and well defined. Are you feeling like this?:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2Fl3vR7aXoQX0OdHi48%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2Fl3vR7aXoQX0OdHi48%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2Fl3vR7aXoQX0OdHi48%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="244" frameborder="0" scrolling="no"><a href="https://medium.com/media/8f3bbb5ca430a6f7f81a3d9868124c88/href">https://medium.com/media/8f3bbb5ca430a6f7f81a3d9868124c88/href</a></iframe><p>Now we will open the build.gradle.kts file located at the root of the project and will change a few things.</p><pre>plugins {<br>    //trick: for the same plugin versions in all sub-modules<br>    id(&quot;com.android.library&quot;).version(&quot;8.0.2&quot;).apply(false)<br>    kotlin(&quot;multiplatform&quot;).version(&quot;1.8.21&quot;).apply(false)<br>}<br><br>tasks.register(&quot;clean&quot;, Delete::class) {<br>    delete(rootProject.buildDir)<br>}</pre><p>This is the original code, or something similar… we will use the version catalog we created to make it look like this:</p><pre>@Suppress(&quot;DSL_SCOPE_VIOLATION&quot;)<br>plugins {<br>    alias(commonlibs.plugins.multiplatform).apply(false)<br>    alias(commonlibs.plugins.kotlin.android).apply(false)<br>    alias(commonlibs.plugins.android.lib).apply(false)<br>    alias(commonlibs.plugins.android.app).apply(false)<br>    alias(commonlibs.plugins.kover).apply(false)<br>}<br><br>tasks.register(&quot;clean&quot;, Delete::class) {<br>    delete(rootProject.buildDir)<br>}<br><br>subprojects {<br>    afterEvaluate {<br>        tasks.withType&lt;org.jetbrains.kotlin.gradle.tasks.KotlinCompile&gt; {<br>            kotlinOptions {<br>                jvmTarget = JavaVersion.VERSION_17.toString()<br>            }<br>        }<br>    }<br>}</pre><p>Since we are using version catalogs the plugins block changes a little, we are also making the jvmTarget use the 17 version. We added a suppress for a <a href="https://youtrack.jetbrains.com/issue/KTIJ-19369/False-positive-cant-be-called-in-this-context-by-implicit-receiver-with-plugins-in-Gradle-version-catalogs-as-a-TOML-file">known bug</a> when using version catalogs with toml files.</p><p>Now we will change the shared project gradle script, here’s the original:</p><pre>plugins {<br>    kotlin(&quot;multiplatform&quot;)<br>    kotlin(&quot;native.cocoapods&quot;)<br>    id(&quot;com.android.library&quot;)<br>}<br><br>@OptIn(org.jetbrains.kotlin.gradle.ExperimentalKotlinGradlePluginApi::class)<br>kotlin {<br>    targetHierarchy.default()<br>    android {<br>        compilations.all {<br>            kotlinOptions {<br>                jvmTarget = &quot;1.8&quot;<br>            }<br>        }<br>    }<br>    iosX64()<br>    iosArm64()<br>    iosSimulatorArm64()<br>    cocoapods {<br>        summary = &quot;Some description for the Shared Module&quot;<br>        homepage = &quot;Link to the Shared Module homepage&quot;<br>        version = &quot;1.0&quot;<br>        ios.deploymentTarget = &quot;14.1&quot;<br>        framework {<br>            baseName = &quot;shared&quot;<br>        }<br>    }<br>    <br>    sourceSets {<br>        val commonMain by getting {<br>            dependencies {<br>                //put your multiplatform dependencies here<br>            }<br>        }<br>        val commonTest by getting {<br>            dependencies {<br>                implementation(kotlin(&quot;test&quot;))<br>            }<br>        }<br>    }<br>}<br>android {<br>    namespace = &quot;com.example.mylibrary&quot;<br>    compileSdk = 33<br>    defaultConfig {<br>        minSdk = 27<br>    }<br>}</pre><p>These are the changes:</p><pre>@file:Suppress(&quot;UnstableApiUsage&quot;)<br>import org.jetbrains.kotlin.gradle.plugin.mpp.BitcodeEmbeddingMode.BITCODE<br>import org.jetbrains.kotlin.gradle.plugin.mpp.KotlinNativeTarget<br>import org.jetbrains.kotlin.gradle.plugin.mpp.apple.XCFramework<br>import org.gradle.api.tasks.testing.logging.TestExceptionFormat<br><br>plugins {<br>    kotlin(&quot;multiplatform&quot;)<br>    kotlin(&quot;native.cocoapods&quot;)<br>    id(&quot;maven-publish&quot;)<br>    id(&quot;kover&quot;)<br>}<br><br>group = commonlibs.versions.library.group.get()<br>version = commonlibs.versions.library.version.get()<br><br>var androidTarget: String = &quot;&quot;<br><br>kotlin {<br>    val android = android {<br>        publishLibraryVariants(&quot;release&quot;)<br>    }<br>    androidTarget = android.name<br>    val xcf = XCFramework()<br>    val iosX64 = iosX64()<br>    val iosArm64 = iosArm64()<br>    val iosSim = iosSimulatorArm64()<br>    configure(listOf(iosX64, iosArm64, iosSim)) {<br>        binaries {<br>            framework {<br>                //Any dependecy you add for ios should be added here using export()<br>                export(commonlibs.kotlin.stdlib)<br>                xcf.add(this)<br>            }<br>        }<br>    }<br><br>    targets.withType&lt;KotlinNativeTarget&gt; {<br>        binaries.all {<br>            freeCompilerArgs += listOf(&quot;-Xgc=cms&quot;)<br>        }<br>    }<br><br>   cocoapods {<br>        val iosDefinitions = commonlibs.versions.ios<br>        name = iosDefinitions.basename.get()<br>        summary = iosDefinitions.summary.get()<br>        homepage = iosDefinitions.homepage.get()<br>        authors = iosDefinitions.authors.get()<br>        version = commonlibs.versions.library.version.get()<br>        ios.deploymentTarget = iosDefinitions.deployment.target.get()<br>        framework {<br>            baseName = iosDefinitions.basename.get()<br>            isStatic = false<br>            transitiveExport = true<br>            embedBitcode(BITCODE)<br>        }<br>        specRepos {<br>            url(https://medium.com/&quot;https://github.com/user/repo.git&quot;) //use your repo here<br>        }<br>        publishDir = rootProject.file(&quot;./&quot;)<br>    }<br><br>    sourceSets {<br>        val commonMain by getting {<br>            dependencies {<br>                api(commonlibs.kotlin.stdlib)<br>            }<br>        }<br>        val commonTest by getting {<br>            dependencies {<br>                implementation(kotlin(&quot;test-common&quot;))<br>                implementation(kotlin(&quot;test-annotations-common&quot;))<br>            }<br>        }<br>        val androidMain by getting {<br>            dependencies {<br>                //Add your specific android dependencies here<br>            }<br>        }<br>        val androidUnitTest by getting {<br>            dependsOn(androidMain)<br>            dependsOn(commonMain)<br>            dependencies {<br>                implementation(kotlin(&quot;test-junit&quot;))<br>                //you should add the android junit here<br>            }<br>        }<br>        val iosX64Main by getting<br>        val iosArm64Main by getting<br>        val iosSimulatorArm64Main by getting<br>        val iosMain by creating {<br>            dependsOn(commonMain)<br>            iosX64Main.dependsOn(this)<br>            iosArm64Main.dependsOn(this)<br>            iosSimulatorArm64Main.dependsOn(this)<br>            dependencies {<br>                //Add any ios specific dependencies here, remember to also add them to the export block<br>            }<br>        }<br>        val iosX64Test by getting<br>        val iosArm64Test by getting<br>        val iosSimulatorArm64Test by getting<br>        val iosTest by creating {<br>            dependsOn(commonTest)<br>            iosX64Test.dependsOn(this)<br>            iosArm64Test.dependsOn(this)<br>            iosSimulatorArm64Test.dependsOn(this)<br>        }<br>    }<br>}<br><br>android {<br>    namespace = commonlibs.versions.library.group.get()<br>    compileSdk = //create your own android versions catalog and add this version there<br>    defaultConfig {<br>        minSdk = //same as with compileSdk<br>        targetSdk = //same as with compileSdk<br>    }<br>    sourceSets[&quot;main&quot;].manifest.srcFile(&quot;src/androidMain/AndroidManifest.xml&quot;)<br>    beforeEvaluate {<br>        libraryVariants.all {<br>            compileOptions {<br>                // Flag to enable support for the new language APIs<br>                isCoreLibraryDesugaringEnabled = true<br>                sourceCompatibility = JavaVersion.VERSION_17<br>                targetCompatibility = JavaVersion.VERSION_17<br>            }<br>        }<br>    }<br>    dependencies {<br>        coreLibraryDesugaring(...)//same as with compileSdk<br>    }<br>    publishing {<br>        singleVariant(&quot;release&quot;) {<br>            withSourcesJar()<br>            withJavadocJar()<br>        }<br>    }<br>    testOptions {<br>        unitTests.isReturnDefaultValues = true<br>    }<br>}<br><br>publishing {<br>    repositories {<br>        maven {<br>            name = &quot;github&quot;<br>            url = uri(&quot;https://maven.pkg.github.com/user/repo&quot;)<br>            credentials {<br>                username = System.getenv()[&quot;MYUSER&quot;]<br>                password = System.getenv()[&quot;MYPAT&quot;]<br>            }<br>        }<br>    }<br>    val thePublications = listOf(androidTarget) + &quot;kotlinMultiplatform&quot;<br>    publications {<br>        matching { it.name in thePublications }.all {<br>            val targetPublication = this@all<br>            tasks.withType&lt;AbstractPublishToMaven&gt;()<br>                .matching { it.publication == targetPublication }<br>                .configureEach { onlyIf { findProperty(&quot;isMainHost&quot;) == &quot;true&quot; } }<br>        }<br>        matching { it.name.contains(&quot;ios&quot;, true) }.all {<br>            val targetPublication = this@all<br>            tasks.withType&lt;AbstractPublishToMaven&gt;()<br>                .matching { it.publication == targetPublication }<br>                .forEach { it.enabled = false }<br>        }<br>    }<br>}<br><br>afterEvaluate {<br>    tasks.named(&quot;podPublishDebugXCFramework&quot;) {<br>        enabled = false<br>    }<br>    tasks.named(&quot;podSpecDebug&quot;) {<br>        enabled = false<br>    }<br>    tasks.withType&lt;JavaCompile&gt;().configureEach {<br>        sourceCompatibility = JavaVersion.VERSION_17.toString()<br>        targetCompatibility = JavaVersion.VERSION_17.toString()<br>    }<br>    tasks.withType&lt;AbstractTestTask&gt;().configureEach {<br>        testLogging {<br>            exceptionFormat = TestExceptionFormat.FULL<br>            events(&quot;started&quot;, &quot;skipped&quot;, &quot;passed&quot;, &quot;failed&quot;)<br>            showStandardStreams = true<br>        }<br>    }<br>}<br><br>val buildIdAttribute = Attribute.of(&quot;buildIdAttribute&quot;, String::class.java)<br>configurations.forEach {<br>    it.attributes {<br>        attribute(buildIdAttribute, it.name)<br>    }<br>}<br><br>val moveIosPodToRoot by tasks.registering {<br>    group = &quot;myGroup&quot;<br>    doLast {<br>        val releaseDir = rootProject.file(<br>            &quot;./release&quot;<br>        )<br>        releaseDir.copyRecursively(<br>            rootProject.file(&quot;./&quot;),<br>            true<br>        )<br>        releaseDir.deleteRecursively()<br>    }<br>}<br><br>tasks.named(&quot;podPublishReleaseXCFramework&quot;) {<br>    finalizedBy(moveIosPodToRoot)<br>}<br><br>val publishPlatforms by tasks.registering {<br>    group = &quot;myGroup&quot;<br>    dependsOn(<br>        tasks.named(&quot;publishAndroidReleasePublicationToGithubRepository&quot;),<br>        tasks.named(&quot;podPublishReleaseXCFramework&quot;)<br>    )<br>    doLast {<br>        exec { commandLine = listOf(&quot;git&quot;, &quot;add&quot;, &quot;-A&quot;) }<br>        exec { commandLine = listOf(&quot;git&quot;, &quot;commit&quot;, &quot;-m&quot;, &quot;iOS binary lib for version ${commonlibs.versions.library.version.get()}&quot;) }<br>        exec { commandLine = listOf(&quot;git&quot;, &quot;push&quot;, &quot;origin&quot;, &quot;main&quot;) }<br>        exec { commandLine = listOf(&quot;git&quot;, &quot;tag&quot;, commonlibs.versions.library.version.get()) }<br>        exec { commandLine = listOf(&quot;git&quot;, &quot;push&quot;, &quot;--tags&quot;) }<br>        println(&quot;version ${commonlibs.versions.library.version.get()} built and published&quot;)<br>    }<br>}<br><br>val compilePlatforms by tasks.registering {<br>    group = &quot;myGroup&quot;<br>    dependsOn(<br>        tasks.named(&quot;compileKotlinIosArm64&quot;),<br>        tasks.named(&quot;compileKotlinIosX64&quot;),<br>        tasks.named(&quot;compileKotlinIosSimulatorArm64&quot;),<br>        tasks.named(&quot;compileReleaseKotlinAndroid&quot;)<br>    )<br>    doLast {<br>        println(&quot;Finished compilation&quot;)<br>    }<br>}</pre><p>You must be asking yourself what are all these lines of scripting code right?.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Ftenor.com%2Fembed%2F6219070&amp;display_name=Tenor&amp;url=https%3A%2F%2Ftenor.com%2Fview%2Fcalculation-math-hangover-allen-zach-galifianakis-gif-6219070&amp;image=https%3A%2F%2Fmedia.tenor.com%2F5vo_w_jDfwgAAAAN%2Fcalculation-math.png&amp;type=text%2Fhtml&amp;schema=tenor" width="600" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/da28ac5adb31a44a2c922641b6508b34/href">https://medium.com/media/da28ac5adb31a44a2c922641b6508b34/href</a></iframe><p>Let’s explain it by sections:</p><p>The <strong>kotlin</strong> section contains the:</p><ul><li><strong>targets</strong>: You’ll find the configuration for each target. There’s an important thing on the ios configuration, the exports, these are needed as we need to export the libraries we use on the kotlin code, we left an example with the kotlin standard library there.</li><li><strong>cocoapods</strong>: this block sets the information that will be saved on the podspec. and the framework package configurations. you can add the information to the version catalog and access it as it’s described on the snippet, there’s one important value to keep in mind here as it will be used later on the pod file configuration. The name on the root cocoapods configuration and basename under the framework configuration must be the same and those will configure the name used to get the library on cocoapods.</li><li><strong>sourcesets</strong>: This block configures each source set and their dependencies. You’ll notice a difference between the commonMain and the rest of the sourcesets, the use of api() instead of implementation() , this is due to the export() requirement for ios, you are exposing these dependencies on the sourceset and then embedding them on the final package.</li></ul><p>The <strong>android</strong> section contains the configuration needed for the android library package, we left some empty fields for you as an exercise, you can create your own android.versions.toml file with the required configurations and use them here. we are setting all the possible java compilations to use version 17, this ensures that there’s no conflict on what’s compiled.</p><p>The <strong>publishing</strong> section contains the maven publishing configuration. There are a few important pieces here too:</p><ul><li>url = uri(&quot;https://maven.pkg.github.com/user/repo&quot;) you should replace user and repo with your own user and repo on github.</li><li>System.getenv()[&quot;MYUSER&quot;] this will be used on the publish action, you will have to save MYUSER as an environment variable with your github username</li><li>System.getenv()[&quot;MYPAT&quot;] this will be used on the publish action, you will have to save MYPAT as an environment variable with a <a href="https://docs.github.com/en/authentication/keeping-your-account-and-data-secure/managing-your-personal-access-tokens#creating-a-personal-access-token-classic">private access token created on github</a>.</li></ul><p>The rest of the configuration in this section disables the ios publishing on maven as we will publish the ios framework using the repo as any regular cocoapods library.</p><p>The <strong>afterEvaluate</strong> section contains a few configurations that reduce the compilation time (disable the iOS debug compilation tasks) and also sets the language version to 17 on java compilation tasks. finally it sets the test logging to show when it starts and ends each task, this helps on the testing actions.</p><p>The <strong>configurations.forEach</strong> section fixes a bug on some configurations missing an id attribute that appeared after gradle 8.</p><p>We reached the final part of the build script, you can see 3 tasks created:</p><ul><li>moveIosPodToRoot moves the ios framework output to the root of the project, making it accessible when using cocoapods.</li><li>publishPlatforms is the task that triggers the publishing of the android maven package and the ios one too. This task will push a commit with the ios package on the same repo and create a new tag with the version set on the common.versions.toml version catalog.</li></ul><p>Well, this is the end of the gradle scripts configuration.</p><h3>The Test Action</h3><p>Well, the heavy project configuration is done, you pushed the code to your github repo and you can add your code and compile, now, we need to setup the github actions that will run the tests and publish new versions once we push our code. This section is about the tests action.</p><p>You should remember that we had 2 parameters as environment variables:</p><ul><li>System.getenv()[&quot;MYUSER&quot;]</li><li>System.getenv()[&quot;MYPAT&quot;]</li></ul><p>We need to add these environment variables to the actions secrets, you’ll go to https//github.com/USER/REPO/settings/secrets/actions and add them with the name you prefer, remember you will need these names later for the actions scripts.</p><p>Now that you added the secrets we can continue with the action scripts. If you need help on how to create a github actions workflow go to the <a href="https://docs.github.com/en/actions/quickstart">official docs</a>. For simplicity we are leaving the entire script and will explain each step below:</p><pre>name: Run tests<br><br>on:<br>  workflow_dispatch:<br>  pull_request:<br><br>concurrency:<br>  group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }}<br>  cancel-in-progress: true<br><br>jobs:<br>  tests:<br>    name: Run tests<br>    runs-on: [macos-12]<br>    timeout-minutes: 90<br>    env:<br>      DEVELOPER_DIR: /Applications/Xcode_14.2.app/Contents/Developer<br><br>    steps:<br>      - name: Checkout<br>        uses: actions/checkout@v1<br><br>      - name: Set up JDK 17<br>        uses: actions/setup-java@v2<br>        with:<br>          java-version: &#39;17&#39;<br>          distribution: &#39;adopt&#39;<br><br>      - name: Setup Gradle<br>        uses: gradle/gradle-build-action@v2<br><br>      - name: Grant execute permission for gradlew<br>        run: chmod +x gradlew<br><br>      - name: Run Android Tests<br>        run:  ./gradlew shared:testReleaseUnitTest<br><br>      - name: Run iOS Tests<br>        run:  ./gradlew shared:iosX64Test<br><br>      - if: github.event_name == &#39;pull_request&#39;<br>        name: Create code coverage<br>        run:  ./gradlew shared:koverXmlReport<br><br>      - if: github.event_name == &#39;pull_request&#39;<br>        name: Add coverage report to PR<br>        id: kover<br>        uses: mi-kas/kover-report@v1<br>        with:<br>          path: ${{ github.workspace }}/shared/build/reports/kover/xml/report.xml<br>          token: ${{ secrets.GITHUB_TOKEN }}<br>          title: Code Coverage<br>          update-comment: true<br>          min-coverage-overall: 80<br>          min-coverage-changed-files: 80<br>          coverage-counter-type: LINE</pre><ul><li>The initial configuration sets this action to be triggered on pull requests, and also to be manually run when needed.</li><li>We set the action to cancel any existing runs if it’s triggered in parallel, this is useful when pushing code to the same PR in short time spans.</li><li>We are setting the action to run on macos 12 as we need this for the ios framework to be compiled.</li><li>we set a timeout of 90 minutes and set the xcode version to be 14.2</li></ul><p>Now let’s check the steps:</p><ol><li>We checkout the code.</li><li>We run the JDK 17 configuration.</li><li>We setup the gradle configuration and caching, this will save us some time after the initial run.</li><li>We grant execute permissions to the gradle executable.</li><li>We run the android tests.</li><li>We run the iOS tests.</li><li>If the action is triggered from a PR we build the code coverage xml report.</li><li>Again, if the action is triggered from a PR, we publish the coverage report to the PR.</li><li>When you see the tests running, you’ll find the result of the tests logging setup we did on the previous post, each test will have a START and PASSED or FAILED log.</li><li>When you see the action running, there will be some extra step for the gradle caching, this is the 3 step saving the cache after the run.</li></ol><h3>The Publish Action</h3><p>This is the final step in the setup, you might have already started to add your code, and you have your first PR, the tests have passed, you updated the version of the library in the common.versions.toml catalog, everything’s ready for the version to be published and consumed from each platform.</p><p>As on the previous section, here’s the script for you to see/use, we’ll explain the steps below so you can understand the process:</p><pre>name: Publish version<br><br>on:<br>  workflow_dispatch:<br>jobs:<br>  testflight:<br>    name: Publish libraries<br>    runs-on: [macos-12]<br>    timeout-minutes: 90<br>    env:<br>      MYUSER: ${{ secrets.MYUSER }}<br>      MYPAT: ${{ secrets.MYPAT }}<br>      DEVELOPER_DIR: /Applications/Xcode_14.2.app/Contents/Developer<br>    if: github.ref == &#39;refs/heads/main&#39;<br>    steps:<br>      - name: Checkout<br>        uses: actions/checkout@v1<br><br>      - name: Set up JDK 17<br>        uses: actions/setup-java@v2<br>        with:<br>          java-version: &#39;17&#39;<br>          distribution: &#39;adopt&#39;<br><br>      - name: Setup Gradle<br>        uses: gradle/gradle-build-action@v2<br><br>      - name: Github credentials<br>        uses: extractions/netrc@v1<br>        with:<br>          machine: github.com<br>          username: ${{ secrets.MYUSER }}<br>          password: ${{ secrets.MYPAT }}<br><br>      - name: Github config<br>        run: |<br>            git config --global user.name &quot;${{ env.MYUSER }}&quot;<br>            git config --global user.email &quot;YOUREMAIL@YOURDOMAIN.COM&quot;<br>            git checkout -b main<br><br>      - name: Grant execute permission for gradlew<br>        run: chmod +x gradlew<br><br>      - name: Publish version<br>        run:  ./gradlew publishPlatforms</pre><ul><li>This workflow will be triggered manually and will <strong>ONLY</strong> run on the main branch, this is done to avoid versions being spread across branches.</li><li>We get the user and private access token that we saved on the previous post, as we will push the result of the ios framework compilation to the repo and have the tag added too on the release process.</li></ul><p>Now the steps:</p><ol><li>The regular checkout.</li><li>We setup the JAVA JDK.</li><li>We setup gradle</li><li>We save the user and pat on the github configuration, since the VM gets wiped once the action is completed we don’t have to worry about deleting this later and nothing is published or left anywhere accessible to the public.</li><li>We add the user and e-mail to the github configuration.</li><li>We give execute permissions to the gradle executable.</li><li>we run the publishPlatforms gradle task that we added to the gradle scripts on the 3rd post of these series.</li></ol><p>Depending on your development flow you might publish a new version every time you merge a PR on main or you might have a development branch where you work on several features at the same time and merge to main once in a while, so, each time you merge to main this github workflow will work as a deploy, compiling the libraries for each platform and publishing them to the respective places.</p><p>Remember to update the library version on the version catalog before merging to main or you will get an error when running the publish version action.</p><p>This is the last step in the process of setting up a private KMP library on github. Next you’ll find one more post that explains how to configure your iOS and Android projects to consume the library.</p><p>Hope this post was useful and well written/explained, if you have any question please leave a comment and we’ll read and answer as we can.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5f596afc6e09" width="1" height="1" alt=""><hr><p><a href="https://medium.com/teamsnap-engineering/setting-up-a-kmp-shared-library-5f596afc6e09">Setting up a KMP shared library</a> was originally published in <a href="https://medium.com/teamsnap-engineering">TeamSnap Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>