<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Phil Blenkinsop on Medium]]></title>
        <description><![CDATA[Stories by Phil Blenkinsop on Medium]]></description>
        <link>https://medium.com/@philblenk6?source=rss-566bad7db29d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Vzk_8SqqBFlGlI7gqk3zgQ.jpeg</url>
            <title>Stories by Phil Blenkinsop on Medium</title>
            <link>https://medium.com/@philblenk6?source=rss-566bad7db29d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 02:39:26 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@philblenk6/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[(2/2) E2E Testing Android Apps With ADB In The Cloud Using Genymotion Device Image]]></title>
            <link>https://medium.com/@philblenk6/android-automated-testing-in-the-cloud-using-genymotion-device-image-359f1024aece?source=rss-566bad7db29d------2</link>
            <guid isPermaLink="false">https://medium.com/p/359f1024aece</guid>
            <category><![CDATA[genymotion]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[genymotion-cloud]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Phil Blenkinsop]]></dc:creator>
            <pubDate>Mon, 18 Dec 2023 11:45:22 GMT</pubDate>
            <atom:updated>2023-12-18T14:07:35.841Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/436/0*EBCUb89HrljHSnPy" /><figcaption>Genymotion Device Image Logo</figcaption></figure><p>This article follows on from my first post about <a href="https://medium.com/@philblenk6/e2e-testing-android-apps-with-adb-b0d667cfe44b">E2E Testing Android Apps With ADB</a>. It demonstrated how to do blackbox e2e testing on an android app using the Android Emulator and ADB.</p><p>Being able to run these tests locally is useful, but the ability to run these in the cloud means that they can be included in an automated release cycle. This means we need an android device in the cloud to target with the tests.</p><p>There are a few options here:</p><ol><li>Use a device farm which expose real devices in the cloud</li><li>Use an Android Emulator virtual device in the cloud</li></ol><p>Device farms provide the most realistic testing as it’ll be on a real device, but they are often costly and have limits on concurrency and availability. Using a virtual device won’t be able to guarantee exact behaviour on a device, but are cheaper and more flexible than device farms.</p><p>To run an android virtual device in the cloud again there are a few options:</p><ol><li>Self run an emulator on a cloud compute service by downloading all the necessary software and dependencies.</li><li>Use a prebuilt solution to run on a cloud compute service.</li></ol><p>Trying to reliably self run an Android Emulator on cloud compute is very difficult as doing virtualisation within an already virtualised environment leads to lots of teething issues. Luckily, Genymotion provide a Device Image offering that allows you to run Android OS on cloud compute reliably and we will be exploring that in this article.</p><p><strong>Table of contents:</strong></p><ol><li>Genymotion Introduction</li><li>Using Device Image to run Android on EC2 in AWS</li><li>Connecting to EC2 and running tests against it</li><li>Wrap Up</li></ol><p>— — —</p><ol><li><strong>Genymotion Introduction</strong></li></ol><p>Genymotion are an “Android as a service platform” offering a number of solutions to running Android virtual devices locally and in the cloud.</p><p>They offer two Android in the cloud solutions:</p><ul><li>Genymotion SaaS<br>- Full cloud platform with billing, usage reports and virtual devices.<br>- Pay per minute at $0.05 per minute working out to $3 per hour.<br>- 2 concurrent devices maximum</li><li>Genymotion Device Image<br>- Prebuilt images to run Android OS on cloud provider compute services<br>- Pay per hour at $0.5 per hour, plus cloud provider compute charges working out to roughly $0.65 per hour based on compute instance sizes.<br>- Unlimited concurrency</li></ul><p>You should pick the solution best suited to the needs of your application and test suite. For example, if your test suite runs for longer than 10 minutes, then it becomes more cost effective to pay for an hour of a Device Image compared to using the SaaS offering.</p><p>This article will focus on the Device Image offering, as it provides the functionality needed to run our tests over ADB and reduces the need to work with software outside of AWS. <em>If Genymotion SaaS is better suited to your needs then there are some great articles on integrating it into CircleCI provider for automated testing </em><a href="https://medium.com/genymobile/run-your-mobile-automated-tests-on-genymotion-cloud-android-virtual-devices-with-circleci-7575dbc1052b"><em>here</em></a><em>. Most other CI/CD providers are </em><a href="https://www.genymotion.com/partners/"><em>also supported</em></a><em>.</em></p><p>2. <strong>Using Device Image to run Android on EC2 in AWS</strong></p><p>Genymotion Device Images are run in AWS by running an EC2 instance from a precreated AMI found on the <a href="https://aws.amazon.com/marketplace/seller-profile?id=933724b4-d35f-4266-905e-e52e4792bc45&amp;ref=dtl_B01MREUQPU">AWS Marketplace</a>. However, the devices don’t have ADB enabled by default. Therefore, we need to run a device and enable ADB before creating our own custom AMI from the instance.</p><p>Firstly to run a device image instance, we can follow this <a href="https://docs.genymotion.com/paas/02_Getting_Started/021_AWS/">tutorial</a> on the Genymotion documentation. Note that you will need permission to subscribe to AWS Marketplace items if it is your first time using Genymotion. They offer a free trial of 5 days, and there is no fixed charges following that. This will also create a security group to allow inbound traffic to the instance.</p><p>Once the device is running, we need to enable ADB on it. Again, Genymotion provide a <a href="https://docs.genymotion.com/paas/Access/04_ADB/">tutorial</a> on how to achieve this.</p><p>Once ADB is enabled, we can create our own AMI of the running device. This means that whenever we launch an instance, it will have ADB automatically enabled. Again Genymotion have a section on how to do this on their <a href="https://docs.genymotion.com/paas/06_Create_preconfigured_images/">documentation</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*p-Bhba8uHjtRhUa3.png" /><figcaption>Running Genymotion Device Image</figcaption></figure><p>3. <strong>Connecting to EC2 and running tests against it</strong></p><p>Now we have an AMI containing the Genymotion Android instance with ADB enabled, we can launch an instance from the AMI using the AWS CLI or SDK and then connect to it via ADB in our tests.</p><p>For this example, we’re going to use the AWS SDK as we are already running a Javascript file for the tests. We can use the RunInstancesCommand from the @aws-sdk/client-ec2 to launch an instance. When the instance is first launched it doesn’t get assigned an IP address straightaway, so we need to wait for it to initialise and be assigned the IP using waitUntilInstanceRunning. Then we can use the DescribeInstancesCommand to fetch the IP address of the instance.</p><pre>import {<br>  DescribeInstancesCommand,<br>  RunInstancesCommand,<br>  waitUntilInstanceRunning,<br>  EC2Client,<br>} from &quot;@aws-sdk/client-ec2&quot;;<br><br>// This is the ID of the AMI created in part 1<br>const CUSTOM_GENYMOTION_AMI_ID = &quot;ami-xxxxxx&quot;;<br>// This is the ID of the security group that was created during part 1<br>const SECURITY_GROUP_ID = &quot;sg-xxxxxx&quot;;<br><br>const ec2Client = new EC2Client({ region: &quot;us-east-2&quot; });<br><br>console.log(&quot;Launching Genymotion Device Image EC2&quot;);<br>const { Instances } = await ec2Client.send(<br>  new RunInstancesCommand({<br>    MinCount: 1,<br>    MaxCount: 1,<br>    ImageId: CUSTOM_GENYMOTION_AMI_ID,<br>    InstanceType: &quot;c6g.xlarge&quot;,<br>    BlockDeviceMappings: [<br>      {<br>        DeviceName: &quot;/dev/sda1&quot;,<br>        Ebs: {<br>          VolumeSize: 10,<br>          VolumeType: &quot;gp2&quot;,<br>          DeleteOnTermination: true,<br>        },<br>      },<br>    ],<br>    SecurityGroupIds: [SECURITY_GROUP_ID],<br>    TagSpecifications: [<br>      {<br>        ResourceType: &quot;instance&quot;,<br>        Tags: [<br>          {<br>            Key: &quot;Name&quot;,<br>            Value: &quot;Genymotion-ADB-Testing&quot;,<br>          },<br>        ],<br>      },<br>    ],<br>  })<br>);<br>const genymotionInstanceId = Instances?.[0]?.InstanceId ?? &quot;&quot;;<br><br>console.log(&quot;Waiting for Genymotion Device Image EC2 to initialise&quot;);<br>await waitUntilInstanceRunning(<br>  {<br>    client: ec2Client,<br>    maxWaitTime: 30,<br>  },<br>  {<br>    Filters: [{ Name: &quot;instance-id&quot;, Values: [genymotionInstanceId] }],<br>  }<br>);<br><br>console.log(&quot;Fetching Genymotion Device Image EC2 public IP address&quot;);<br>const instance = await ec2Client.send(<br>  new DescribeInstancesCommand({<br>    Filters: [{ Name: &quot;instance-id&quot;, Values: [genymotionInstanceId] }],<br>  })<br>);<br><br>const genymotionPublicIpAddress =<br>  instance?.Reservations?.[0]?.Instances?.[0]?.PublicIpAddress || &quot;&quot;;</pre><p>Now that the instance is running and we have the public IP address, we can connect to it using adb connect . We have to specify port 5555 as that is the default ADB port for Genymotion Device Images.</p><pre>...<br><br>const genymotionPublicIpAddress =<br>  instance?.Reservations?.[0]?.Instances?.[0]?.PublicIpAddress || &quot;&quot;;<br><br>await execCommand(`adb connect ${genymotionPublicIPAddress}:5555`)</pre><p>Once we’re connected to the Genymotion device, we can run the exact same test script to install and sign into the app using ADB without any modifications.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V0GiiP-ixRBxZ92q9W17WQ.gif" /><figcaption>Sign in test using Genymotion Virtual Device</figcaption></figure><p>The final thing to do once the tests are complete is to terminate the EC2 instance we created so that we don’t get charged any more than necessary. This can be done using the TerminateInstancesCommand from the @aws-cdk/client-ec2</p><pre>import {<br>  TerminateInstancesCommand,<br>  EC2Client,<br>} from &quot;@aws-sdk/client-ec2&quot;;<br><br>const ec2Client = new EC2Client({ region: &quot;us-east-2&quot; });<br><br>console.log(&quot;Terminating Genymotion Device Image EC2&quot;);<br>await ec2Client.send(<br>  new TerminateInstancesCommand({<br>    InstanceIds: [genymotionInstanceId], // this is the variable created earlier<br>  })<br>);</pre><p>4. <strong>Wrap up</strong></p><p>We’ve learnt how to run our automation tests using ADB against an Android virtual device in the cloud for easily repeatable and consistent automation testing.</p><p>These tests can be run during CI/CD in a release cycle to ensure that any broken features are detected without manual testing before they reach the hands of your users.</p><p>Thanks for reading and please check out the sample repo for the whole code, which can be found in the part-two-cloud-genymotion folder.</p><p><a href="https://github.com/blenky36/adb-automated-testing">https://github.com/blenky36/adb-automated-testing</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=359f1024aece" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[(1/2) E2E Testing Android Apps With ADB]]></title>
            <link>https://medium.com/econify/e2e-testing-android-apps-with-adb-b0d667cfe44b?source=rss-566bad7db29d------2</link>
            <guid isPermaLink="false">https://medium.com/p/b0d667cfe44b</guid>
            <category><![CDATA[test-automation]]></category>
            <category><![CDATA[adb]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[testing]]></category>
            <dc:creator><![CDATA[Phil Blenkinsop]]></dc:creator>
            <pubDate>Fri, 08 Dec 2023 10:05:34 GMT</pubDate>
            <atom:updated>2023-12-20T15:19:32.037Z</atom:updated>
            <content:encoded><![CDATA[<p>Testing your main user journeys to find any issues before they reach your end users is a critical requirement of any release cycle. These can include sign in and sign up flows or purchasing a product. Automating these journeys reduces the burden of manual testing on your team, increases the repeatability and minimises the risk of human error.</p><p>In order to test user journeys, you need to run the app on a device. To avoid the overhead of managing a fleet of real devices to test on, the <a href="https://developer.android.com/studio/run/emulator">Android Emulator</a> provides access to a range of virtual devices which can be run locally as well as in CI pipelines.</p><p><a href="https://adbshell.com/">ADB</a> (Android Debug Bridge) is a great utility for communicating with the emulated device and allows installing APKs and simulating user input such as typing and screen presses.</p><p>Using both of these tools in tandem creates a platform to run android apps and simulate user journeys in a repeatable and automated manner. Running your tests in this way is considered <a href="https://www.geeksforgeeks.org/difference-between-black-box-vs-white-vs-grey-box-testing/">black box testing</a>. In my opinion this is the best way to run your E2E tests, as it means the test interacts with the app in exactly the same way a user would.</p><p>This guide will walk through the process of automating a Sign In journey using ADB for the <a href="https://zoom.us/">Zoom</a> app.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/482/1*InfBetmAHVwVe7uzal1hgg.png" /><figcaption>Zoom app welcome screen</figcaption></figure><p><strong>Table of Contents:</strong></p><ol><li>Installing and running the app</li><li>Simulating user input</li><li>Example sign in test</li><li>Wrap up and next steps</li></ol><p>— — —</p><p><em>If you want to skip straight to the sample repository there is a link at the bottom!</em></p><ol><li><strong>Installing and running the app</strong></li></ol><p><em>(This guide assumes you already have the Android Emulator configured and a virtual device created. Setup steps can be found for the Emulator </em><a href="https://developer.android.com/studio/run/emulator"><em>here</em></a><em> if needed. This guide was created using a Nexus 5X using Android 13 Playstore SDK </em><em>system-images;android-33;google_apis_playstore;arm64-v8a )</em></p><p>Installing your app is a simple process thanks to <a href="https://adbshell.com/commands/adb-install">adb install</a> . Simply provide the path to the APK file(s) saved locally. In our case, the Zoom app utilises <a href="https://developer.android.com/build/configure-apk-splits">split APKs</a> so we need to use adb install-multiple to install all parts of the split APK. We pass the path of the folder where the APK files are installed, and add a wilcard to pick up all of the files in one install command:</p><p>adb install-multiple ./zoom-apk/*.apk</p><p>Normally to run an app on a phone, you’d find it by scrolling around on the screen and tapping on the icon to open it. This wouldn’t be an ideal approach for automated tests as you can’t guarantee the screen’s state at any given moment which could result in flakey tests. Therefore we need to be able to open the app using ADB commands.</p><p>We can use adb shell and the <a href="https://developer.android.com/tools/adb#am">Android Activity manager</a> to start the app with adb shell am start , which starts an activity on the device. In order to know what activity to start, we need find the ‘Launcher’ activity of the Zoom app which can be done using adb shell cmd package resolve-activity . Combining both together, we can launch the app in a single command where us.zoom.videomeetings is the package name of the app.</p><p>adb shell am start &quot;us.zoom.videomeetings/$(adb shell cmd package resolve-activity -c android.intent.category.LAUNCHER us.zoom.videomeetings | sed -n &#39;/name=/s/^.*name=//p&#39;)&quot;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BNtT2FfcWxPFBLI-_MCSnQ.gif" /><figcaption>Launching Zoom app with one CLI command</figcaption></figure><p>2.<strong> Simulating user input</strong></p><p>Using adb shell input there are a few options for simulating user input including text and touching coordinates on screen:</p><ul><li>adb shell input tap x y (where x &amp; y are coordinates on the screen)</li><li>adb shell input type &quot;z” (where z is a word or phrase)</li></ul><p>In order to execute these reliably, we first need to find the elements on screen we want to target.</p><p>For example, to press a button on screen we ideally want to find it by text as a user would with their eyes, and then find it’s coordinates on screen to tap. This is a preferable method over hardcoding fixed coordinates so that the test doesn’t break when the layout changes on different screen sizes.</p><p>To find an element, we can use the <a href="https://developer.android.com/training/testing/other-components/ui-automator">Android UI Automator</a> together with adb exec-out which executes a command on the device and returns the output to our stdout. The UI Automater provides a dump command which will return an XML tree of all the elements on screen. This normally outputs to a file, so instead dumping to/dev/tty will return it to our stdout .</p><p>adb exec-out uiautomator dump /dev/tty</p><p>This also includes a string to say the UI was dumped to our requested location. We can pipe the output into awk to remove it, so that we are left with valid XML to crawl.</p><p>adb exec-out uiautomator dump /dev/tty | awk &#39;{gsub(&quot;UI hierchary dumped to: /dev/tty&quot;, &quot;&quot;);print}&#39;</p><p>We can then use a utility such as <a href="https://linuxcommandlibrary.com/man/xmllint">xmllint</a> to crawl the outputted XML and find elements. <em>Another option is converting the XML to JSON and crawling that, which is what I do in the sample repo (link at bottom).</em></p><p>We want to find elements by their text as a user would, so we have to search the XML elements where the node’s text property is what we are looking for, in this case the ‘Sign In’ button.</p><p>adb exec-out uiautomator dump /dev/tty | awk &#39;{gsub(&quot;UI hierchary dumped to: /dev/tty&quot;, &quot;&quot;);print}&#39; | xmllint --xpath &#39;//*[@text=&quot;Sign In&quot;]&#39; -</p><p>From the above command, we get the following XML node:</p><pre>&lt;node index=&quot;1&quot; text=&quot;Sign In&quot; resource-id=&quot;us.zoom.videomeetings:id/btnLogin&quot; class=&quot;android.widget.Button&quot; package=&quot;us.zoom.videomeetings&quot; content-desc=&quot;&quot; checkable=&quot;false&quot; checked=&quot;false&quot; clickable=&quot;true&quot; enabled=&quot;true&quot; focusable=&quot;true&quot; focused=&quot;false&quot; scrollable=&quot;false&quot; long-clickable=&quot;false&quot; password=&quot;false&quot; selected=&quot;false&quot; bounds=&quot;[63,1626][1017,1752]&quot;/&gt;</pre><p>Each of the nodes have a bounds property in the format bounds=[minX, minY][maxX, maxY] . Using these values we can calculate the centre of the button. In the above case it would be</p><pre>bounds=&quot;[63,1626][1017,1752]&quot;<br><br>centerXCoordinate -&gt; (63 + 1017) / 2 = 540<br>centerYCoordinate -&gt; (1626 + 1752) / 2 = 1689</pre><p>Then using the adb shell input tap 540 1689 , we can press the centre of that button. Similarly for text inputs, we can find and tap it in the same way, and then once it’s focused we can type an email address adb shell input type example@email.com.</p><p>3. <strong>Example sign in test</strong></p><p>Combining the commands from sections 1 and 2, we can create a automated test to install and sign in to the Zoom app in a reliable manner, with an assertion to ensure we are signed in and directed to the home screen.</p><p><em>The below code is written in Javascript and uses some simple utility functions which can be found in the sample repo link at the bottom of the article. They provide some basic abstraction and retry-ability of the adb commands described in sections 1 &amp; 2.</em></p><pre>import { assertScreenContains, clickOnElement, execCommand } from &quot;./util.mjs&quot;;<br><br>const ZOOM_PACKAGE_NAME = &quot;us.zoom.videomeetings&quot;;<br>const EMAIL = &quot;&quot; // add your zoom email here<br>const PASSWORD = &quot;&quot; // add your zoom password here<br><br>// Assumes emulator is already running<br><br>console.log(&quot;Installing APK...&quot;);<br>await execCommand(&quot;adb install-multiple ./zoom-apk/*.apk&quot;);<br>console.log(&quot;APK Installed!&quot;);<br>console.log(&quot;Launching APK...&quot;);<br>await execCommand(<br>  `adb shell am start &quot;${ZOOM_PACKAGE_NAME}/$(adb shell cmd package resolve-activity -c android.intent.category.LAUNCHER ${ZOOM_PACKAGE_NAME} | sed -n &#39;/name=/s/^.*name=//p&#39;)&quot;`<br>);<br>console.log(&quot;APK Launched!&quot;);<br><br>await clickOnElement(&quot;Sign In&quot;)<br>await clickOnElement(&quot;Email&quot;)<br>await execCommand(`adb shell input text &quot;${EMAIL}&quot;`)<br>await clickOnElement(&quot;Password&quot;)<br>await execCommand(`adb shell input text &quot;${PASSWORD}&quot;`)<br>await clickOnElement(&quot;Sign In&quot;)<br><br>await assertScreenContains(`Meetings`)<br><br>console.log(&quot;Uninstalling APK...&quot;);<br>await execCommand(`adb uninstall ${ZOOM_PACKAGE_NAME}`);<br>console.log(&quot;APK Uninstalled!&quot;);<br></pre><p>Running the above script results in an automated test that starts the Zoom app, signs in with a username and password and then asserts the content on the home screen is correct.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UyJr956KirGTjl5LhyZxFA.gif" /><figcaption>Testing the Zoom app Sign In</figcaption></figure><p>4. <strong>Wrap up and next steps</strong></p><p>Running these tests locally is the easy part, but being able to run them during CI or in the cloud without manual intervention is where the real value will be gained.</p><p>For CI, the script can be easily reworked to fit in a <a href="https://devcenter.bitrise.io/en/steps-and-workflows/workflow-recipes-for-android-apps/-android--run-tests-using-the-emulator.html">Bitrise pipeline</a> which allows you to run tests against an Android emulator. Similarly, CircleCI <a href="https://support.circleci.com/hc/en-us/articles/360000028928-Testing-with-the-Android-emulator-on-CircleCI">also supports android emulators</a>, and ADB can be configured to communicate with a device anywhere through <a href="https://adbshell.com/commands/adb-connect">adb connect</a> .</p><p>Another possibility is using <a href="https://www.genymotion.com/">Genymotion</a> virtual devices which provide a virtual android device in the cloud on a pay per use basis. Feel free to read the second part of this series detailing how to run the tests against a Genymotion Device Image instance in AWS!</p><p><a href="https://medium.com/@philblenk6/android-automated-testing-in-the-cloud-using-genymotion-device-image-359f1024aece">Read part two here!</a></p><p>Thanks for reading and please check out the sample repo for the whole code including the utility functions, which can be found in the part-one-local-emulator folder.</p><p><a href="https://github.com/blenky36/adb-automated-testing">https://github.com/blenky36/adb-automated-testing</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b0d667cfe44b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/econify/e2e-testing-android-apps-with-adb-b0d667cfe44b">(1/2) E2E Testing Android Apps With ADB</a> was originally published in <a href="https://medium.com/econify">Econify</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[CircleCI Config Splitting]]></title>
            <link>https://medium.com/@philblenk6/circleci-config-splitting-7024bad400e3?source=rss-566bad7db29d------2</link>
            <guid isPermaLink="false">https://medium.com/p/7024bad400e3</guid>
            <category><![CDATA[ci-cd-pipeline]]></category>
            <category><![CDATA[cli]]></category>
            <category><![CDATA[continuous-delivery]]></category>
            <category><![CDATA[continuous-integration]]></category>
            <category><![CDATA[circleci]]></category>
            <dc:creator><![CDATA[Phil Blenkinsop]]></dc:creator>
            <pubDate>Wed, 06 Dec 2023 22:14:04 GMT</pubDate>
            <atom:updated>2023-12-08T12:25:40.353Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FdN3Dn8q0EXykLiUkeNaUQ.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@rstar50?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Roger Starnes Sr</a> on <a href="https://unsplash.com/photos/a-close-up-of-a-bunch-of-pipes-on-a-wall-uSfiDo13ois?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Unsplash</a></figcaption></figure><p>CircleCI is one of the most popular CI/CD providers and offers a lot of features when it comes to building pipelines.</p><p>However, in large projects and monorepos, the main .circleci/config.yml file can become very long and difficult to maintain. This is because CircleCI requires all the configuration to be in a single config.yml file, often leading to a file thousands of lines long.</p><p>Fortunately, CircleCI provide a <a href="https://circleci.com/docs/how-to-use-the-circleci-local-cli/#packing-a-config">CLI</a> to help solve this problem which offers functions to validate and ‘pack’ your configuration together which we will explore in this article.</p><p><em>If you’d rather skip straight to the example, there’s a link to a sample repository at the end of the article. It is a simple monorepo using </em><a href="https://bun.sh/"><em>Bun</em></a><em> and </em><a href="https://classic.yarnpkg.com/lang/en/docs/workspaces/"><em>Yarn Workspaces</em></a><em> to manage two packages. The pipeline runs a test and types command in each package</em>.</p><p><strong>Table of Contents</strong></p><ol><li>Splitting Config</li><li>Pack and Validate</li><li>Example project and wrap up</li></ol><p>— — —</p><ol><li><strong>Splitting Config</strong></li></ol><p>A typical CircleCI file is made up of 6 main sections, of which commands, jobs and workflows tend to be the largest.</p><pre>version: 2.1<br>orbs:<br>   ...<br>executors:<br>   ...<br>parameters:<br>   ...<br>commands:<br>   ...<br>jobs:<br>   ...<br>workflows:<br>   ...</pre><p>To split the config.yml into separate files we need to create a folder to house everything together which for this example will be .circleci/src .</p><p>We have the option of housing each section in one file, or a folder of smaller files. For the smaller sections such as orbs, parameters and executors, it makes sense to house them in a one file as as each declaration is very short. To tell the CLI to pack a single file, it needs to be prefixed with an @ symbol.</p><p>Creating a file for each smaller section will leave us with a folder structure should look like the below. There is also a @version.yml file to include the version field of the config.</p><pre>.circleci/<br>|__ src/<br>    |__@version.yml<br>    |__@orbs.yml<br>    |__@executors.yml<br>    |__@parameters.yml</pre><p>For the larger sections of the config we can split them into a folder of files. This is particularly useful for projects with complex and lengthy workflow, command and job definitions.</p><p>When splitting into a folder of files, the content of the files will be packed under parent keys of the folder name and file name. For that reason the files do not need to be prefixed with a @ but must be named as the workflow/job/command name.</p><p>For example, extracting jobs named test and types into our existing folder structure results in the following:</p><pre>.circleci/<br>|__ src/<br>    |__@version.yml<br>    |__@orbs.yml<br>    |__@executors.yml<br>    |__@parameters.yml<br>    |__jobs/<br>       |__test.yml<br>       |__types.yml      <br>        </pre><p>Once repacked, this would result in the following config.yml :</p><pre>version: 2.1<br>orbs:<br>  ...<br>executors:<br>  ...<br>parameters:<br>  ...<br>jobs:<br>  test:<br>    ...test job definition<br>  types:<br>    ...types job definition</pre><p>The same method can be applied to split up the workflows and commands to leave a final folder structure like the below:</p><pre>.circleci/<br>|__ src/<br>    |__@version.yml<br>    |__@orbs.yml<br>    |__@executors.yml<br>    |__@parameters.yml<br>    |__jobs/<br>       |__test.yml<br>       |__types.yml<br>    |__workflows/<br>       |__example-workflow.yml<br>    |__commands/<br>       |__example-command.yml</pre><p>2. <strong>Pack and Validate</strong></p><p>Once the config is split into separate files, before pushing it into source control, it needs to be packed together using the CircleCI CLI. (You can install it <a href="https://circleci.com/docs/local-cli/">here</a>)</p><p>One method of doing this is using a Makefile to run the pack and validate commands. Create your Makefile in .circleci/Makefile and add the following function. This tells the CircleCI CLI to pack everything in the src folder created together, before validating it to make sure the config is correct.</p><pre>build_circleci_config:<br> @echo &quot;Compiling circleci config&quot;<br> @circleci config pack src &gt; config.yml<br> @echo &quot;Validating circleci config&quot;<br> @circleci config validate config.yml</pre><p>Then from the root of your repository you can run cd .circleci &amp;&amp; make. The config.yml will then be generated and validated locally ready for commit.</p><p><em>As a bonus you could configure </em><a href="https://www.npmjs.com/package/pre-commit"><em>precommit hooks</em></a><em> for this to be run automatically on commit!</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/976/1*XXli4tAioVhFKY897LFREg.png" /><figcaption>Running the Makefile</figcaption></figure><p>3. <strong>Finish and wrap up</strong></p><p>To conclude, we’ve learnt how to split a typical CircleCI config.yml file into smaller files to make it easier to maintain, and how to pack it back together again.</p><p>Below is a link to an example repository using a split config. It is a simple monorepo using <a href="https://bun.sh/">Bun</a> and <a href="https://classic.yarnpkg.com/lang/en/docs/workspaces/">Yarn Workspaces</a> to manage two packages. The pipeline has one workflow which runs a test and types job in each package.</p><p><a href="https://github.com/blenky36/circleci-config-splitting">GitHub - blenky36/circleci-config-splitting: Split your circleci config.yml into separate files</a></p><p>Thanks for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7024bad400e3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[HTML to PDF using Typescript & AWS Lambda]]></title>
            <link>https://medium.com/@philblenk6/html-to-pdf-using-aws-lambda-a61abcdd50d4?source=rss-566bad7db29d------2</link>
            <guid isPermaLink="false">https://medium.com/p/a61abcdd50d4</guid>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[pdf]]></category>
            <category><![CDATA[aws-cdk]]></category>
            <category><![CDATA[aws-lambda]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Phil Blenkinsop]]></dc:creator>
            <pubDate>Fri, 03 Nov 2023 16:49:23 GMT</pubDate>
            <atom:updated>2023-11-06T20:40:11.485Z</atom:updated>
            <content:encoded><![CDATA[<p>Creating a PDF is a requirement of many applications whether it be a receipt or report. They can often have complex layouts making HTML and CSS a great candidate for designing them.</p><p>In Javascript, there are a few packages for creating PDFs such as <a href="https://www.npmjs.com/package/jspdf">jsPDF</a> and <a href="https://www.npmjs.com/package/pdfkit">PDFKit</a> which require you to add content to the PDF using Javascript functions like doc.text(&quot;Hello world!&quot;, 10, 10) . This makes it tricky to generate new PDFs without lots of code changes. However, <a href="https://www.npmjs.com/package/puppeteer">Puppeteer</a> is an ideal candidate as it can convert HTML to a PDF using a headless browser.</p><p>Unfortunately, Puppeteer is tricky to run in a serverless environment due to the binaries it needs to run a headless browser. <a href="https://github.com/Sparticuz/chromium">@sparticuz/chromium</a> solves this problem by providing the binaries needed to run chromium in a serverless environment.</p><p>For this tutorial we will be building an API that will accept a HTML string, create a PDF of the HTML, upload it to S3 and then return a download url for the PDF.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_AoFlukjRWEy_wrEsm0Y7w.png" /><figcaption>Architecture Diagram</figcaption></figure><ol><li><strong>Project Setup and Dependencies</strong></li></ol><p>Before we begin, we need to make sure we have Node.js installed. I would recommend using <a href="https://github.com/nvm-sh/nvm">node version manager</a> to do this and for this tutorial we are using version 18.18.2 of node. Now we also need to install the AWS CDK in order to use the CLI to initialise and deploy our app. I also prefer using yarn as the package manager so to install both we can run the following command.</p><pre>npm i -g aws-cdk yarn</pre><p>Once installed, make sure you have configured your AWS account with the CDK. <a href="https://docs.aws.amazon.com/cdk/v2/guide/getting_started.html">https://docs.aws.amazon.com/cdk/v2/guide/getting_started.html</a></p><p>Next we’re going to create a directory to house the project and then initialise it using the AWS CDK CLI. This will create all the files and folders we need to organise the project.</p><pre>mkdir html-pdf-serverless &amp;&amp; cd &quot;$_&quot; &amp;&amp; cdk init app --language typescript</pre><p>Once the project is initialised, we can install the dependencies needed for our lambda function to generate a PDF and upload it to S3. As we are using yarn we can delete the package-lock.json before installing.</p><p><em>Note it’s important to install fixed versions of puppeteer-core and @sparticuz/chromium as puppeteer ships with a preferred version of chromium which are detailed on the </em><a href="https://pptr.dev/chromium-support"><em>puppeteer support page.</em></a></p><pre>yarn add @aws-sdk/client-s3 @aws-sdk/s3-request-presigner @aws-sdk/lib-storage puppeteer-core@19.6.0 @sparticuz/chromium@110.0.0 </pre><p>There are also some dev dependencies needed for build and typescript support.</p><pre>yarn add -D @types/aws-lambda aws-lambda  esbuild</pre><p>We need to make two changes to the tsconfig.json by adding skipLibCheck: true and esModuleInterop: true to the compiler options object. This allows our installed dependencies to work with typescript.</p><p>The last setup step we need to do is get the binaries needed to run the chromium headless browser in AWS Lambda. To achieve this, we will use a <a href="https://docs.aws.amazon.com/lambda/latest/dg/chapter-layers.html">lambda layer</a> which contains the necessary binaries torun chromium.As we installed version 19.6.0 of puppeteer, we need version 110.0.0 of chromium. Head to <a href="https://github.com/Sparticuz/chromium/releases">https://github.com/Sparticuz/chromium/releases</a>, find version 110.0.0 and download chromium-v110.0.0-layer.zip , saving it to the root of the repository.</p><p><strong>2. Create the API</strong></p><p>Our rest API will be made up of 2 routes, one as a health check so we can confirm it has deployed properly, and the second to generate the PDF.</p><p>We’ll start by creating the healthcheck endpoint and deploying it. Create a healthcheck lambda handler in lambdas/healthcheck-lambda/index.ts and add the following code to return a successful response.</p><pre>import { APIGatewayProxyHandler } from &quot;aws-lambda&quot;<br><br>export const handler: APIGatewayProxyHandler = async () =&gt; {<br>    return {<br>        statusCode: 200,<br>        body: &quot;Ok&quot;<br>    }<br>}</pre><p>Now we can create the CDK resources to handle the lambda code. We modify lib/html-pdf-serverless-stack.ts to add a rest API, lambda and lambda integration. This will mean our healthcheck lambda is executed at the root path of the api.</p><pre>import { Stack, StackProps } from &#39;aws-cdk-lib&#39;;<br>import { NodejsFunction } from &#39;aws-cdk-lib/aws-lambda-nodejs&#39;<br>import { Construct } from &#39;constructs&#39;;<br>import { LambdaIntegration, RestApi } from &#39;aws-cdk-lib/aws-apigateway&#39;;<br><br>export class HtmlPdfServerlessStack extends Stack {<br>  constructor(scope: Construct, id: string, props?: StackProps) {<br>    super(scope, id, props);<br><br>    const healthcheckLambda = new NodejsFunction(this, &#39;HealthcheckLambda&#39;, {<br>      entry: &#39;lambdas/healthcheck-lambda/index.ts&#39;<br>    })<br><br>    const api = new RestApi(this, &#39;HtmlToPdfRestApi&#39;, {<br>      restApiName: &#39;HTML PDF API&#39;,<br>    })<br><br>    api.root.addMethod(&quot;GET&quot;, new LambdaIntegration(healthcheckLambda, {<br>      requestTemplates: { &#39;application/json&#39;: &#39;{ &quot;statusCode&quot;: &quot;200&quot; }&#39; }<br>    }))<br>  }<br>}</pre><p>Now we can run cdk deploy and our rest API will be deployed to AWS. The stack should output the url of the api which we can use to test. Opening the outputted url in a browser should return the ‘Ok’ message we configured in the handler code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zCXU-Z1-eLU88i9zPNIGgQ.png" /></figure><p><strong>3. Add the HTML to PDF Lambda</strong></p><p>We can now create the handler for our HTML to PDF lambda in lambdas/html-pdf-lambda/index.ts . In the following code we take in the request body, convert the HTML string to a PDF buffer, upload it to S3 and then generate a presigned url to download the saved PDF. The request body the API accepts will include the HTML string and the name of the file that will be stored in S3.</p><pre>import { S3Client, GetObjectCommand } from &#39;@aws-sdk/client-s3&#39;<br>import { getSignedUrl } from &#39;@aws-sdk/s3-request-presigner&#39;<br>import { Upload } from &#39;@aws-sdk/lib-storage&#39;<br>import { APIGatewayProxyEvent, APIGatewayProxyHandler } from &#39;aws-lambda&#39;<br>import { generatePdfBuffer } from &#39;./generatePdfBuffer&#39;<br><br>// process.env.AWS_REGION is a default env var provided in lambdas by AWS<br>const s3Client = new S3Client({ region: process.env.AWS_REGION })<br><br>export const handler: APIGatewayProxyHandler = async (event: APIGatewayProxyEvent) =&gt; {<br>    if (!event.body) {<br>        return {<br>            statusCode: 400,<br>            body: &quot;Invalid request body&quot;<br>        }<br>    }<br>    try {<br>        const requestBody = JSON.parse(event.body) as { html: string, s3Key: string }<br><br>        const pdfBuffer = await generatePdfBuffer(requestBody.html)<br><br>        if(!pdfBuffer) {<br>            throw new Error(&#39;Failed to created PDF buffer from HTML&#39;)<br>        }<br><br>        const s3Upload = new Upload({<br>            client: s3Client,<br>            params: {<br>                Bucket: process.env.S3_PDF_BUCKET,<br>                Body: pdfBuffer,<br>                Key: requestBody.s3Key<br>            }<br>        })<br>        s3Upload.on(&quot;httpUploadProgress&quot;, (progress) =&gt; {<br>            console.log(progress);<br>        });<br>        await s3Upload.done()<br><br>        const presignedUrl = await getSignedUrl(<br>            s3Client,<br>            new GetObjectCommand({ Bucket: process.env.S3_PDF_BUCKET, Key: requestBody.s3Key }),<br>            { expiresIn: 3600 }<br>        )<br><br>        return {<br>            statusCode: 200,<br>            body: JSON.stringify({<br>                pdfUrl: presignedUrl<br>            })<br>        }<br>    } catch (error) {<br>        console.log(&quot;Error converting HTML to PDF&quot;, error)<br>        return {<br>            statusCode: 500,<br>            body: &quot;Internal server error&quot;<br>        }<br>    }<br>}</pre><p>We also need to add the function that will handle converting the HTML string to a PDF buffer. Add the following code to lambdas/html-pdf-lambda/generatePdfBuffer.ts to launch a headless browser, set the content of the page as the provided HTML and then convert it to a PDF buffer.</p><pre>import chromium from &#39;@sparticuz/chromium&#39;<br>import puppeteer from &#39;puppeteer-core&#39;<br><br>export const generatePdfBuffer = async (<br>  html: string,<br>): Promise&lt;Buffer | undefined&gt; =&gt; {<br>  let result = undefined<br>  let browser = null<br>  try {<br>    console.log(&#39;Launching browser&#39;)<br>    browser = await puppeteer.launch({<br>      args: chromium.args,<br>      defaultViewport: chromium.defaultViewport,<br>      executablePath: await chromium.executablePath(),<br>      headless: chromium.headless,<br>      ignoreHTTPSErrors: true,<br>    })<br>    <br>    console.log(&#39;Browser launched&#39;)<br>    const page = await browser.newPage()<br><br>    await page.setContent(html, {<br>      waitUntil: [&#39;domcontentloaded&#39;, &#39;networkidle0&#39;, &#39;load&#39;],<br>    })<br><br>    await page.evaluate(&#39;window.scrollTo(0, document.body.scrollHeight)&#39;)<br><br>    result = await page.pdf({ format: &#39;a4&#39;, printBackground: true })<br>  } catch (e) {<br>    console.log(&#39;Chromium error&#39;, { e })<br>  } finally {<br>    if (browser !== null) {<br>      await browser.close()<br>    }<br>  }<br>  return result<br>}</pre><p>Now our lambda code is ready, we can wire it up to the API we created in the previous step. We need to add the S3 bucket to save the PDFs to, the HTML to PDF lambda, the chromium lambda layer and the rest api integration to wire it together. This leaves our lib/html-pdf-serverless-stack.ts looking like the below:</p><pre>import { Duration, Stack, StackProps } from &#39;aws-cdk-lib&#39;;<br>import { Code, LayerVersion, Runtime } from &#39;aws-cdk-lib/aws-lambda&#39;;<br>import { Bucket } from &#39;aws-cdk-lib/aws-s3&#39;;<br>import { NodejsFunction } from &#39;aws-cdk-lib/aws-lambda-nodejs&#39;<br>import { Construct } from &#39;constructs&#39;;<br>import { LambdaIntegration, RestApi } from &#39;aws-cdk-lib/aws-apigateway&#39;;<br><br>export class HtmlPdfServerlessStack extends Stack {<br>  constructor(scope: Construct, id: string, props?: StackProps) {<br>    super(scope, id, props);<br><br>    const pdfsS3Bucket = new Bucket(this, &#39;PDFsS3Bucket&#39;)<br><br>    const chromeAwsLambdaLayer = new LayerVersion(this, &#39;ChromeAWSLambdaLayer&#39;, {<br>      layerVersionName: &#39;ChromeAWSLambdaLayer&#39;,<br>      compatibleRuntimes: [<br>        Runtime.NODEJS_18_X<br>      ],<br>      code: Code.fromAsset(&#39;chromium-v110.0.0-layer.zip&#39;)<br>    })<br><br>    const htmlToPdfLambda = new NodejsFunction(this, &#39;HtmlToPdfLambda&#39;, {<br>      entry: &#39;lambdas/html-pdf-lambda/index.ts&#39;,<br>      environment: {<br>        S3_PDF_BUCKET: pdfsS3Bucket.bucketName<br>      },<br>      layers: [chromeAwsLambdaLayer],<br>      bundling: {<br>        externalModules: [<br>          &#39;aws-sdk&#39;<br>        ],<br>        nodeModules: [&#39;@sparticuz/chromium&#39;],<br>      },<br>      timeout: Duration.seconds(30),<br>      runtime: Runtime.NODEJS_18_X,<br>      memorySize: 1024<br>    })<br>    pdfsS3Bucket.grantReadWrite(htmlToPdfLambda)<br><br>    const healthcheckLambda = new NodejsFunction(this, &#39;HealthcheckLambda&#39;, {<br>      entry: &#39;lambdas/healthcheck-lambda/index.ts&#39;<br>    })<br><br>    const api = new RestApi(this, &#39;HtmlToPdfRestApi&#39;, {<br>      restApiName: &#39;HTML PDF API&#39;,<br>    })<br><br>    api.root.addMethod(&quot;GET&quot;, new LambdaIntegration(healthcheckLambda, {<br>      requestTemplates: { &#39;application/json&#39;: &#39;{ &quot;statusCode&quot;: &quot;200&quot; }&#39; }<br>    }))<br>    api.root.addMethod(&quot;POST&quot;, new LambdaIntegration(htmlToPdfLambda, {<br>      requestTemplates: { &#39;application/json&#39;: &#39;{ &quot;statusCode&quot;: &quot;200&quot; }&#39; }<br>    }))<br><br>  }<br>}<br><br></pre><p>On the HTML to PDF lambda, we’ve added the name of the S3 bucket as an environment variable so we can upload the PDFs to it. Adding @sparticuz/chromium to the nodeModules array of the bundling config tells the bundler not to include this package during the bundling process as it’s already available in the runtime due to our lambda layer. Finally, we’ve registered the lambda layer so that it’ll be attached during runtime and increased the timeout and memory size of the lambda. This is because launching the browser is an intensive task that needs processing power and we don’t want our lambda to return before it has finished.</p><p>Again we can run cdk deploy and our changes will be deployed to AWS. Using the same outputted url from the stack, we can test it using a REST client such as Insomnia or Postman with the following body.</p><pre>{<br> &quot;s3Key&quot;: &quot;html-to-pdf.pdf&quot;,<br> &quot;html&quot;: &quot;&lt;!DOCTYPE html&gt;&lt;html&gt;&lt;body&gt;&lt;div style=\&quot;height:90vh;display:flex;justify-content:center;align-items:center;\&quot;&gt;&lt;h1&gt;HTML TO PDF&lt;/h1&gt;&lt;/div&gt;&lt;/body&gt;&lt;/html&gt;&quot;<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D11f_d49dplcYEtvwO6WOQ.png" /><figcaption>Test using Insomina</figcaption></figure><p>Then clicking the returned presigned URL to download the PDF shows us our HTML converted into the PDF document!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7JnHmkRsmDGdMaHcfg48wA.png" /><figcaption>Generated PDF from HTML</figcaption></figure><p>Thanks for reading and you can check out the sample repo for the full code! <a href="https://github.com/blenky36/html-pdf-serverless">https://github.com/blenky36/html-pdf-serverless</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a61abcdd50d4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deploying Typescript Lambdas to AWS with the CDK]]></title>
            <link>https://engineering.dunelm.com/deploying-typescript-lambdas-to-aws-with-the-cdk-ffa5519c16c5?source=rss-566bad7db29d------2</link>
            <guid isPermaLink="false">https://medium.com/p/ffa5519c16c5</guid>
            <category><![CDATA[aws-cdk]]></category>
            <category><![CDATA[graphql]]></category>
            <category><![CDATA[aws-lambda]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[typescript]]></category>
            <dc:creator><![CDATA[Phil Blenkinsop]]></dc:creator>
            <pubDate>Wed, 26 Jan 2022 08:31:08 GMT</pubDate>
            <atom:updated>2022-01-26T08:31:08.125Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/794/1*jqwm_lp0XLNDQuFimoa8Zw.png" /></figure><p>It’s never been easier to write typescript lambdas thanks to the <a href="https://docs.aws.amazon.com/cdk/api/latest/docs/aws-lambda-nodejs-readme.html">@aws-cdk/aws-lambda-nodejs</a> package, which uses <a href="https://esbuild.github.io/">esbuild</a> under the hood to automatically bundle your typescript into javascript! 🛠</p><p>To demonstrate this, I’m going to use the <a href="https://aws.amazon.com/cdk/#:~:text=The%20AWS%20Cloud%20Development%20Kit,resources%20using%20familiar%20programming%20languages.&amp;text=AWS%20CDK%20uses%20the%20familiarity,languages%20for%20modeling%20your%20applications.">AWS CDK</a> to deploy a simple GraphQL lambda written in typescript to AWS, with very minimal config! All you have to do is pass the path to the handler of your lambda and the <a href="https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-lambda-nodejs.NodejsFunction.html">NodejsFunction</a> will do the rest!</p><h4>Table of Contents:</h4><ol><li>Project Setup</li><li>Building the GraphQL lambda</li><li>Building AWS resources with the CDK</li><li>Deploying to AWS with the CDK</li><li>Bonus! Running the stack locally</li><li>Wrap up</li></ol><h4>Project Setup</h4><p><em>This tutorial was written using node v14.14. You can use the </em><a href="https://github.com/nvm-sh/nvm"><em>Node Version Manager</em></a><em> to make sure you’re using the right node version.</em></p><p>Begin by opening a terminal, creating a folder for the project and initialising an npm project using <a href="https://classic.yarnpkg.com/en/docs/cli/init/">yarn init</a>.</p><p>mkdir aws-graphql-cdk &amp;&amp; cd &quot;$_&quot; &amp;&amp; yarn init -y</p><p>Next, in order to write our code in typescript, we need to create a tsconfig.json . We are going to use <a href="https://www.npmjs.com/package/tsconfig.json">tsconfig.json</a> to truly take this project to the moon 🚀.</p><p>Run npx tsconfig.json and select ‘node’ from the technology list.</p><p>Finally, add the packages for typescript.</p><p>yarn add typescript @types/node</p><p>Now we’re ready to start coding! 💻</p><h4>Building the GraphQL Lambda</h4><p>First, install the <a href="https://www.npmjs.com/package/apollo-server-lambda">apollo-server-lambda</a> and graphql packages to create our GraphQL server with.</p><p>yarn add apollo-server-lambda graphql</p><p>Next, add a new file in src/graphql-lambda/index.ts and create a GraphQL server. This is using <a href="https://www.apollographql.com/docs/apollo-server/">ApolloServer</a> to create a simple server that exposes a ‘hello’ query. Then finally we export the lambda handler as the AWS specific integration exposed on the ApolloServer.</p><pre>import { ApolloServer, gql } from &#39;apollo-server-lambda&#39;</pre><pre>const typeDefs = gql`<br>  type Query {<br>    hello: String<br>  }<br>`</pre><pre>const resolvers = {<br>  Query: {<br>    hello: () =&gt; &#39;Hello from the CDK and typescript lambda!&#39;<br>  }<br>}</pre><pre>const server = new ApolloServer({<br>  typeDefs,<br>  resolvers, <br>  introspection: true,<br>})</pre><pre>export const handler = server.createHandler()</pre><h4>Building AWS Resources with the CDK</h4><p>First, install the core, apigateway and lambda aws cdk packages.</p><p>yarn add @aws-cdk/core @aws-cdk/aws-apigateway @aws-cdk/aws-lambda-nodejs</p><p>Then, create a <a href="https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/stacks.html">cloudformation stack</a> to house all of the resources. Add the following code to src/cdk/stack.ts to setup an empty stack.</p><pre>import { App, Construct, Stack } from &#39;@aws-cdk/core&#39;</pre><pre>const serverlessGraphQLStack = (construct: Construct) =&gt; {<br>  const stack = new Stack(construct, &#39;ServerlessGraphQLStack&#39;)<br>}</pre><pre>const app = new App()<br>serverlessGraphQLStack(app)</pre><p>Now we’re ready to start adding the resources!</p><p>Add the following files for the lambda and api gateway.</p><p>src/cdk/lambda.ts</p><pre>import { Runtime } from &#39;@aws-cdk/aws-lambda&#39;<br>import { NodejsFunction } from &#39;@aws-cdk/aws-lambda-nodejs&#39;<br>import { Construct } from &#39;@aws-cdk/core&#39;<br>import path from &#39;path&#39;</pre><pre>export const nodeJSLambda = (stack: Construct, id: string, codePath: string) =&gt; {<br>  return new NodejsFunction(stack, id, {<br>    entry: path.join(__dirname, codePath),<br>    runtime: Runtime.NODEJS_14_X,<br>    bundling: {<br>      externalModules: [&#39;aws-sdk&#39;]<br>    }<br>  })<br>}</pre><p>This function returns the <a href="https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-lambda-nodejs.NodejsFunction.html">NodejsFunction</a> construct. We pass in a path to where the handler is, and set some defaults like the node version. The externalModules property allows you to specify modules that are already available in the runtime to avoid unnecessary duplication of modules in the bundle. As this is a lambda, the aws-sdk module is already available.</p><p>src/cdk/restApi.ts</p><pre>import { RestApi, LambdaIntegration } from &#39;@aws-cdk/aws-apigateway&#39;<br>import { IFunction } from &#39;@aws-cdk/aws-lambda&#39;<br>import { Construct } from &#39;@aws-cdk/core&#39;</pre><pre>export const restApi = (stack: Construct, id: string) =&gt; {<br>  return new RestApi(stack, id, {<br>    restApiName: id<br>  })<br>}</pre><pre>export const lambdaIntegration = (handler: IFunction) =&gt; new            LambdaIntegration(handler)</pre><p>This exposes two functions; one returns the <a href="https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-apigateway.RestApi.html">RestApi</a> construct and the other returns a <a href="https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-apigateway.LambdaIntegration.html">LambdaIntegration</a> construct to connect the lambda to the api.</p><p>To add these to the stack it’s a simple case of importing and invoking them!</p><pre>import { App, Construct, Stack } from &#39;@aws-cdk/core&#39;<br>import { nodeJSLambda } from &#39;./lambda&#39;<br>import { restApi, lambdaIntegration } from &#39;./restApi&#39;</pre><pre>const serverlessGraphQLStack = (construct: Construct) =&gt; {<br>  const stack = new Stack(construct, &#39;ServerlessGraphQLStack&#39;)<br>  <br>  const graphQLServerLambda = nodeJSLambda(stack, &#39;GraphQLServerLambda&#39;, &#39;../graphql-lambda/index.ts&#39;)</pre><pre>  const graphQLServerRestApi = restApi(stack, &#39;GraphQLServerRestApi&#39;)</pre><pre>  const graphQLServerLambdaIntegration = lambdaIntegration(graphQLServerLambda)</pre><pre>}</pre><pre>const app = new App()<br>serverlessGraphQLStack(app)</pre><p>Next, we need to integrate the lambda with the api gateway so that we can invoke it over a /graphql endpoint.</p><p>Add a resource to the api, and then add a GET and POST method, passing in the integration defined earlier.</p><pre>import { App, Construct, Stack } from &#39;@aws-cdk/core&#39;<br>import { nodeJSLambda } from &#39;./lambda&#39;<br>import { restApi, lambdaIntegration } from &#39;./restApi&#39;</pre><pre>const serverlessGraphQLStack = (construct: Construct) =&gt; {<br>  const stack = new Stack(construct, &#39;ServerlessGraphQLStack&#39;)<br>  <br>  const graphQLServerLambda = nodeJSLambda(stack, &#39;GraphQLServerLambda&#39;, &#39;../graphql-lambda/index.ts&#39;)</pre><pre>  const graphQLServerRestApi = restApi(stack, &#39;GraphQLServerRestApi&#39;)</pre><pre>  const graphQLServerLambdaIntegration = lambdaIntegration(graphQLServerLambda)</pre><pre>  const graphQL = graphQLServerRestApi.root.addResource(&#39;graphql&#39;)<br>  graphQL.addMethod(&#39;GET&#39;, graphQLServerLambdaIntegration)<br>  graphQL.addMethod(&#39;POST&#39;, graphQLServerLambdaIntegration)</pre><pre>}</pre><pre>const app = new App()<br>serverlessGraphQLStack(app)</pre><p>Finally we need to create a cdk.json config file to tell the cdk where our app lives!</p><pre>{<br>  &quot;app&quot;: &quot;npx ts-node --prefer-ts-exts ./src/cdk/stack.ts&quot;<br>}</pre><p>That’s the stack complete, now we’re ready to deploy!</p><h4>Deploying to AWS with the CDK</h4><p>In order to deploy to AWS via the CDK we need the following tools installed:</p><ul><li>aws-cli → <a href="https://aws.amazon.com/cli/">aws.amazon.com/cli</a></li><li>aws-cdk cli → npm i -g aws-cdk</li></ul><p><em>(This tutorial used v1.119 of aws-cdk and 2.2.20 of the aws-cli)</em></p><p>Once they are installed, make sure you have also configured your AWS environment in the aws-cli by running aws configure and entering your <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_access-keys.html">access keys</a>.</p><p>The next step is to <a href="https://docs.aws.amazon.com/cdk/latest/guide/bootstrapping.html">bootstrap</a> the AWS account being used, which will automatically provision resources the CDK needs to deploy the stack.</p><p>cdk bootstrap aws://&lt;aws_account_id&gt;/&lt;aws_region&gt;</p><p>E.g. cdk bootstrap aws://03057671267/us-east-1</p><p>Finally, add a script to the package.json that can be run to deploy the stack.</p><pre>{  <br>  &quot;name&quot;: &quot;aws-graphql-cdk&quot;,  <br>  &quot;version&quot;: &quot;1.0.0&quot;,  <br>  &quot;license&quot;: &quot;MIT&quot;,  <br>  &quot;dependencies&quot;: {    <br>    &quot;@aws-cdk/aws-apigateway&quot;: &quot;^1.119.0&quot;,    <br>    &quot;@aws-cdk/aws-lambda-nodejs&quot;: &quot;^1.119.0&quot;,    <br>    &quot;@aws-cdk/core&quot;: &quot;^1.119.0&quot;,    <br>    &quot;@types/node&quot;: &quot;^16.6.2&quot;,    <br>    &quot;apollo-server-lambda&quot;: &quot;^3.1.2&quot;,    <br>    &quot;graphql&quot;: &quot;^15.5.1&quot;,    <br>    &quot;typescript&quot;: &quot;^4.3.5&quot;  <br>  },  <br>  &quot;scripts&quot;: {    <br>    &quot;cdk&quot;: &quot;cdk synth &amp;&amp; cdk deploy --require-approval never&quot;,<br>  }<br>}                         </pre><p>This will <a href="https://docs.aws.amazon.com/cdk/latest/guide/hello_world.html#hello_world_tutorial_synth">synthesise</a> your CDK code into a CloudFormation template and then deploy it, authorising the changes.</p><p>Now comes the exciting part! Run yarn cdk and watch the magic happen. Once it’s finished deploying, you will get an output on the terminal of the endpoint to invoke the api gateway on.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/866/1*Y1T0zOgpldi3jxWRda65mQ.png" /><figcaption>CDK deploy output</figcaption></figure><p>You can test it out in Postman by sending a POST request to https://&lt;your_endpoint&gt;/graphql with the following body:</p><pre>query {<br>  hello<br>}</pre><p>E.g. https://mu1iuirj4j.execute-api.us-east-1.amazonaws.com/prod/grahpql</p><p>You should receive a successful response back ✅</p><pre>{<br>  &quot;data&quot;: {<br>    &quot;hello&quot;: &quot;Hello from the CDK and typescript lambda!&quot;<br>  }<br>}</pre><h4>Bonus! Running the stack locally</h4><p>It’s possible to run the stack locally using <a href="https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-cdk-getting-started.html">sam-beta-cdk</a> if you don’t have access to an AWS environment whilst developing. To install it, run the following command: (you’ll need <a href="https://brew.sh/">homebrew</a> 🍺 for this, and you may need to run brew tap aws/tap beforehand)</p><p>brew install aws-sam-cli-beta-cdk</p><p>Then add another script to your package.json to run it locally.</p><pre>{  <br>  &quot;name&quot;: &quot;aws-graphql-cdk&quot;,  <br>  &quot;version&quot;: &quot;1.0.0&quot;,  <br>  &quot;license&quot;: &quot;MIT&quot;,  <br>  &quot;dependencies&quot;: {    <br>    &quot;@aws-cdk/aws-apigateway&quot;: &quot;^1.119.0&quot;,    <br>    &quot;@aws-cdk/aws-lambda-nodejs&quot;: &quot;^1.119.0&quot;,    <br>    &quot;@aws-cdk/core&quot;: &quot;^1.119.0&quot;,    <br>    &quot;@types/node&quot;: &quot;^16.6.2&quot;,    <br>    &quot;apollo-server-lambda&quot;: &quot;^3.1.2&quot;,    <br>    &quot;graphql&quot;: &quot;^15.5.1&quot;,    <br>    &quot;typescript&quot;: &quot;^4.3.5&quot;  <br>  },  <br>  &quot;scripts&quot;: {    <br>    &quot;cdk&quot;: &quot;cdk synth &amp;&amp; cdk deploy --require-approval never&quot;,<br>    &quot;dev&quot;: &quot;cdk synth &amp;&amp; sam-beta-cdk local start-api&quot;<br>  }<br>}</pre><p>This will again synthesise your cdk code into a CloudFormation template and then run it locally using sam-beta-cdk.</p><p>Before running it locally, you will need <a href="https://docs.docker.com/get-docker/">docker</a> 🐳 installed and running.</p><p>Run yarn dev and then you can test it out with Postman by sending the same POST request as earlier, just swapping out your AWS url with the url output in the terminal, normally http://localhost:3000/graphql .</p><p>You should receive the same successful response back ✅</p><pre>{<br>  &quot;data&quot;: {<br>    &quot;hello&quot;: &quot;Hello from the CDK and typescript lambda!&quot;<br>  }<br>}</pre><h4>Wrap up</h4><p>That’s it! The CDK constructs used in this article take away a lot of the hassle in deploying your code to AWS, and they’re available for other languages such as Python and Go!</p><p>Happy building! 🏠</p><p><a href="https://github.com/blenky36/aws-graphql-cdk">Check out the sample repo</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ffa5519c16c5" width="1" height="1" alt=""><hr><p><a href="https://engineering.dunelm.com/deploying-typescript-lambdas-to-aws-with-the-cdk-ffa5519c16c5">Deploying Typescript Lambdas to AWS with the CDK</a> was originally published in <a href="https://engineering.dunelm.com/">Dunelm Technology</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>