<?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 Jackson Bowe on Medium]]></title>
        <description><![CDATA[Stories by Jackson Bowe on Medium]]></description>
        <link>https://medium.com/@jacksonbowe98?source=rss-c2f9a8700fb5------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*KVSPqSA95OIjcl0-</url>
            <title>Stories by Jackson Bowe on Medium</title>
            <link>https://medium.com/@jacksonbowe98?source=rss-c2f9a8700fb5------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 10:54:59 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@jacksonbowe98/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[Thingsboard Version Control with Bitbucket]]></title>
            <link>https://medium.com/@jacksonbowe98/thingsboard-version-control-with-bitbucket-23e1ec8db880?source=rss-c2f9a8700fb5------2</link>
            <guid isPermaLink="false">https://medium.com/p/23e1ec8db880</guid>
            <category><![CDATA[iot-platform]]></category>
            <category><![CDATA[bitbucket]]></category>
            <category><![CDATA[iot]]></category>
            <category><![CDATA[thingsboard]]></category>
            <dc:creator><![CDATA[Jackson Bowe]]></dc:creator>
            <pubDate>Mon, 29 Jul 2024 01:41:37 GMT</pubDate>
            <atom:updated>2024-07-29T01:41:37.548Z</atom:updated>
            <content:encoded><![CDATA[<p>Quick tutorial on how to use Bitbucket as the Git provider for Thingsboard Version Control</p><p>Requirements:</p><ul><li>Bitbucket account with repository write permissions</li><li>Thingsboard account with Version Control: All / Write permissions</li></ul><p>To begin either create or navigate to your target Bitbucket repo. Ensure that it is empty. Then follow the below:</p><ol><li>(Left sidebar) Repository Settings</li><li>(Left sidebar) Security &gt; Access Tokens</li><li>Create Repository Access Token</li><li>Set Repositories: Read, Write and Pull Requests: Read, Write</li><li>Create —<strong> COPY THE KEY</strong></li></ol><p>Next go to Thingsboard and do the following:</p><ol><li>(Left sidebar) Settings</li><li>Repository Settings</li><li>Copy in your Bitbucket repo url — it should be in the formal https://bitbucket.org/&lt;workspace&gt;/&lt;repo&gt;.git</li><li>Branch: main</li><li>Authentication Method: Password / Access Token</li><li>Username: x-token-auth</li><li>Password: &lt;bitbucket_acess_token&gt;</li><li><strong>Check Access</strong> and then <strong>Save</strong></li></ol><p>Finally, consider configuring some auto-commit settings for Dashboard/Rule Chains/Data Converters.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=23e1ec8db880" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SSTv2 & Python — Project Setup]]></title>
            <link>https://medium.com/@jacksonbowe98/sstv2-python-project-setup-82beefc00cde?source=rss-c2f9a8700fb5------2</link>
            <guid isPermaLink="false">https://medium.com/p/82beefc00cde</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[serverless]]></category>
            <category><![CDATA[aws-lambda]]></category>
            <dc:creator><![CDATA[Jackson Bowe]]></dc:creator>
            <pubDate>Sat, 06 Jul 2024 22:55:05 GMT</pubDate>
            <atom:updated>2024-07-06T22:55:05.791Z</atom:updated>
            <content:encoded><![CDATA[<h3>SSTv2 &amp; Python — Project Setup</h3><p><em>This is the start of a series of tutorials detailing my recommendations for using SST with Python. It is assumed that readers have basic knowledge of SST, AWS, and serverless principles.</em></p><blockquote>SST version used: 2.43.3<br>Document last updated: 7/07/2024</blockquote><blockquote>Git repo for this article: <a href="https://github.com/JacksonBowe/sst-examples/tree/main/python-base-template">https://github.com/JacksonBowe/sst-examples/tree/main/python-base-template</a></blockquote><h4>Recommended Reading:</h4><ul><li><a href="https://medium.com/@jacksonbowe98/aws-for-the-solo-developer-getting-started-301a62c9caa6">AWS for the Solo Developer</a></li></ul><h4>Covered</h4><ul><li>Initializing a new project</li><li>Configuring Python as the default Lambda runtime</li><li>Creating a basic REST API</li><li>Verifying successful local dev and prod deployment</li><li>Recommended architecture</li></ul><h4>Prerequisites</h4><ul><li>Docker installed and running</li><li>AWS CLI installed and correctly configured</li><li>Node, NPM, Python, PIP</li></ul><h3>Python Project Setup</h3><h4>Bootstrapping</h4><p>We start by creating a new SST project</p><pre>npx create-sst@latest &lt;project-directory&gt;</pre><p>By default create-sst spins up a Typescript template like below</p><pre>sst-project<br>|-- packages/<br>    |-- core/<br>     |-- &lt;sub-files&gt;<br>    |-- functions/<br>     |-- &lt;sub-files&gt;<br>|-- stacks/<br>   |-- MyStack.py<br>|-- sst.config.ts<br>|-- &lt;other-files&gt;</pre><p>We’re going to heavily modify this template into the following:</p><pre>sst-project<br>|-- packages/<br>    |-- functions/<br>     |-- core/<br>      |-- modA.py<br>     |-- rest/<br>      |-- requirements.txt     !! IMPORTANT<br>      |-- main.py<br>|-- stacks/<br>   |-- Api.ts<br>|-- sst.config.ts<br>|-- &lt;other-files&gt;</pre><p>Next, overwrite the contents of stacks/Api.ts with the following:</p><pre>import { StackContext, Api } from &quot;sst/constructs&quot;;<br><br>export function API({ stack }: StackContext) {<br> const api = new Api(stack, &quot;api&quot;, {<br>  routes: {<br>   &quot;GET /&quot;: &quot;packages/functions/rest/main.handler&quot;,<br>  },<br> });<br><br> stack.addOutputs({<br>  ApiEndpoint: api.url,<br> });<br>}</pre><p>We also need to ensure that sst.config.ts is updated with our new stacks/Api.ts</p><pre>// sst.config.ts<br>import { SSTConfig } from &quot;sst&quot;;<br>import { API } from &quot;./stacks/Api&quot;;<br><br>export default {<br> config(_input) {<br>  return {<br>   name: &quot;sst-python-base&quot;,<br>   region: &quot;ap-southeast-2&quot;, // Your region<br>  };<br> },<br> stacks(app) {<br>  app.stack(API);<br> },<br>} satisfies SSTConfig;</pre><p>Finally we need to declare that out functions will be using Python (default is Typescript).</p><p>There’s two ways we can do this:</p><ol><li>Change the default runtime to Python (recommended)</li><li>Change the function runtime’s individually (is using a mix of languages)</li></ol><p>For option 1 we would update sst.config.ts like so:</p><pre>import { SSTConfig } from &quot;sst&quot;;<br>import { API } from &quot;./stacks/Api&quot;;<br><br>export default {<br> config(_input) {<br>  return {<br>   name: &quot;sst-examples&quot;,<br>   region: &quot;ap-southeast-2&quot;,<br>  };<br> },<br> stacks(app) {<br>  // Set default runtime globally<br>  app.setDefaultFunctionProps({<br>   runtime: &quot;python3.12&quot;,<br>  });<br><br>  app.stack(API);<br> },<br>} satisfies SSTConfig;</pre><p>For option 2 we would update stacks/Api.ts like so:</p><pre>import { StackContext, Api } from &quot;sst/constructs&quot;;<br><br>export function API({ stack }: StackContext) {<br> const api = new Api(stack, &quot;api&quot;, {<br>  // Set default runtime locally<br>        defaults: {<br>            function: {<br>                runtime: &quot;python3.12&quot;<br>            }<br>        },<br>  routes: {<br>   &quot;GET /&quot;: &quot;packages/functions/rest/main.handler&quot;,<br>  },<br> });<br><br> stack.addOutputs({<br>  ApiEndpoint: api.url,<br> });<br>}</pre><p>The rest of this tutorial assumes that Option 1 was used.</p><h3>Preparing for Local Development</h3><p>To use SST’s Live Lambda development with Python functions we need to do a few additional steps:</p><ol><li>Create an activate a Python virtual environment</li><li>Install node dependencies</li><li>Install and save Python dependencies</li><li>Minimum code for a Lambda function</li><li>Optional: Specify AWS profile to use</li></ol><p>Steps 1–3 are below:</p><pre>$ python -m venv .venv<br>$ .venv\Scripts\activate<br>$ npm i<br>$ pip install boto3<br>$ pip freeze &gt; requirements.txt</pre><p>Notice that we’re installing the boto3 Python package. We won’t be using it in this simple tutorial, but it is required to do anything meaningful in your Python Lambdas. It comes preinstalled in AWS Lambda environments using the Python runtime.</p><p>We’re now going to write the most basic of basic lambda functions</p><pre># packages/functions/main.py<br>def handler(event, context):<br>    return {&quot;statusCode&quot;: 200, &quot;body&quot;: &quot;Hello, World!&quot;}</pre><h4>For developers that use multiple AWS Profiles with SSO</h4><p>Modify your package.json to have the following scripts:</p><pre>&quot;scripts&quot;: {<br> &quot;auth&quot;: &quot;aws sso login --profile sandbox&quot;,<br> &quot;dev&quot;: &quot;sst dev --profile sandbox&quot;,<br> &quot;build&quot;: &quot;sst build --profile sandbox&quot;,<br> &quot;deploy&quot;: &quot;sst deploy --stage prod --profile sandbox&quot;,<br> &quot;remove:local&quot;: &quot;sst remove --profile sandbox&quot;,<br> &quot;remove:prod&quot;: &quot;sst remove --stage prod --profile sandbox&quot;,<br> &quot;console&quot;: &quot;sst console&quot;,<br> &quot;typecheck&quot;: &quot;tsc --noEmit&quot;<br>}</pre><h3>Local Development</h3><p>Start the SST dev session. If running for the first time you will need to enter a stage name. It is recommended to use your name (eg. jackson).</p><blockquote>Ensure that you have the Python virtual environment activated</blockquote><p>Once it has finished deploying you should see the following output</p><pre>&gt; sst dev --profile sandbox<br><br>SST v2.43.3  ready!<br><br>➜  App:     sst-examples<br>   Stage:   jackson<br>   Console: https://console.sst.dev/local/sst-examples/jackson<br><br>|  API PUBLISH_ASSETS_COMPLETE<br><br>✔  Deployed:<br>   API<br>   ApiEndpoint: https://&lt;api_id&gt;.execute-api.&lt;region&gt;.amazonaws.com</pre><p>Navigating to the ApiEndpoint URL should respond with Hello World! as we declared in our Lambda code.</p><p>Modify the Lambda code to respond with a different string and refresh your browser. You should see the changes reflected instantly.</p><h4>Recommended Architecture</h4><p>While it is certainly possible to write all of your logic inside main.py this approach does not promote good code reuse.</p><p>What we want is a clear separation between our application logic, and our Api endpoints, like shown in the below diagram.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/501/1*OFw5EqSeDRXrFeT1_7dU_A.png" /></figure><p>Notice that in the diagram ApiGateway is simple one of many possible event sources. With this architecture core business logic is accessible by any Lambda function without the need to rewrite implementation details.</p><p>To set this up with Python we need to make a few modifications to both our Lambda and infrastructure.</p><p>First, if you don’t already have it create a packages/functions/core/modA.py with the following placeholder function:</p><pre># packages/functions/core/modA.py<br>def mod_a_test_func():<br>    &quot;&quot;&quot;<br>    This function is used for testing purposes.<br>    It prints the string &quot;mod_a_test_func&quot; to the console, and returns it.<br>    &quot;&quot;&quot;<br>    print(&quot;mod_a_test_func&quot;)<br>    return &quot;mod_a_test_func&quot;</pre><blockquote>Next, we need to perform a little bit of Python sacrilege.</blockquote><p>Notice that if we try to import this function into main.py we encounter a No module names &#39;core&#39; error.</p><pre>from core import modA<br><br>def handler(event, context):<br>    print(modA.mod_a_test_func())<br>    return {&quot;statusCode&quot;: 200, &quot;body&quot;: &quot;Hello, World!&quot;}<br><br>&gt;&gt;  Error: No module named &#39;core&#39;</pre><p>When SST invokes a local script, the directory of that script is the root. In Python files can only naturally import other files in the same or sub-directories.</p><pre>|-- packages/<br>    |-- functions/<br>     |-- core/<br>      |-- modA.py<br>     |-- rest/   &lt;&lt; Root dir, can only import from here down<br>      |-- requirements.txt<br>      |-- main.py &lt;&lt; SST invokes this</pre><p>To resolve this import error we need to inject packages/functions/core into the scope of our script. (This is where the sacrilege comes in)</p><pre>import os<br>import sys<br><br>if os.getenv(&quot;IS_LOCAL&quot;):  # In local dev add packages/ to path<br> # Use as many nested os.path.dirname as you need<br>    sys.path.append(<br>        os.path.dirname(os.path.dirname(os.path.abspath(__file__)))<br>    )<br><br>from core import modA<br><br>def handler(event, context):<br>    print(modA.mod_a_test_func())<br>    return {&quot;statusCode&quot;: 200, &quot;body&quot;: &quot;Hello, World!&quot;}</pre><blockquote>Experienced Python developers may look at this and recoil in disgust. I feel the same way. If there is a better way I have yet to find it.</blockquote><p>Now when we hit out Api endpoint we can see that it returns successfully, and that we have two logs in our terminal.</p><pre>|  Invoked packages/functions/rest/main.handler<br>|  +80ms   mod_a_test_func<br>|  +80ms   mod_a_test_func<br>|  Done in 81ms</pre><p>Finally, because we’re modifying the scope of our local script, we need to ensure that we do the same for our deployed bundles. We can use the copyFiles props of sst.Function to copy files into the lambda bundle at build time.</p><pre>import { SSTConfig } from &quot;sst&quot;;<br>import { API } from &quot;./stacks/Api&quot;;<br><br>export default {<br> config(_input) {<br>  return {<br>   name: &quot;sst-examples&quot;,<br>   region: &quot;ap-southeast-2&quot;,<br>  };<br> },<br> stacks(app) {<br>  app.setDefaultFunctionProps({<br>   // I&#39;m new!!<br>   copyFiles: [{ from: &quot;packages/functions/core&quot;, to: &quot;core&quot; }],<br>   runtime: &quot;python3.12&quot;,<br>  });<br><br>  app.stack(API);<br> },<br>} satisfies SSTConfig;</pre><h3>Deploying</h3><p>When creating an app we want to deploy as often as we can. Occasionally there will be instances where something works in local dev but not in production. The longer you go without deploying, the more of these issues stack up.</p><p>Lets deploy our simple app to make sure our dev environment is working end-to-end.</p><pre>npm run deploy<br><br>&gt; sst-examples@0.0.0 deploy<br>&gt; sst deploy --stage prod --profile sandbox<br><br>SST v2.43.3<br><br>➜  App:     sst-examples<br>   Stage:   prod<br>   Region:  ap-southeast-2<br>   Account: 691249328599<br><br>✔  Building...<br>|  API PUBLISH_ASSETS_COMPLETE<br>|  API api/Api AWS::ApiGatewayV2::Api CREATE_COMPLETE<br>|  API api/Parameter_url AWS::SSM::Parameter CREATE_COMPLETE<br>|  API api/LogGroup AWS::Logs::LogGroup CREATE_COMPLETE<br>|  API api/Api/DefaultStage AWS::ApiGatewayV2::Stage CREATE_COMPLETE<br>|  API api/Lambda_GET_--/ServiceRole AWS::IAM::Role CREATE_COMPLETE<br>|  API CustomResourceHandler/ServiceRole AWS::IAM::Role CREATE_COMPLETE<br>|  API CustomResourceHandler AWS::Lambda::Function CREATE_COMPLETE<br>|  API api/Lambda_GET_--/ServiceRole/DefaultPolicy AWS::IAM::Policy CREATE_COMPLETE<br>|  API api/Lambda_GET_-- AWS::Lambda::Function CREATE_COMPLETE<br>|  API api/Route_GET_--/Integration_GET_-- AWS::ApiGatewayV2::Integration CREATE_COMPLETE<br>|  API api/Route_GET_-- AWS::Lambda::Permission CREATE_COMPLETE              <br>|  API api/Route_GET_-- AWS::ApiGatewayV2::Route CREATE_COMPLETE<br>|  API AWS::CloudFormation::Stack CREATE_COMPLETE<br><br>✔  Deployed:<br>   API<br>   ApiEndpoint: https://nv4jh3wvn5.execute-api.ap-southeast-2.amazonaws.com</pre><p>And to test we can simply paste that APIEndpoint URL into our web browser like before.</p><h3>Common Deployment Errors</h3><p>If everything worked, then this section can be skipped</p><h4>No Docker Daemon</h4><pre>ERROR: error during connect: this error may indicate that the docker daemon is not running: Get &quot;http://%2F%2F.%2Fpipe%2Fdocker_engine/_ping&quot;: open //./pipe/docker_engine: The system cannot find the file specified.<br><br>Error: docker exited with status 1<br>--&gt; Command: docker build -t cdk-374967bfbf2e0ce993e3bc1a020ca6df1b996462444755c7505ff13baf40ba99 -f &quot;C:\\Users\\USER\\AppData\\Local\\Temp\\python-bundling-ILp8Ls\\Dockerfile.dependencies&quot; --build-arg &quot;IMAGE=public.ecr.aws/sam/build-python3.12&quot; &quot;C:\\Users\\USER\\AppData\\Local\\Temp\\python-bundling-ILp8Ls&quot;   <br><br>Trace: Error: docker exited with status 1</pre><p>Ensure that Docker is installed and running in the background.</p><h4>yum: command not found</h4><pre>&gt; ERROR [2/9] RUN yum -q list installed rsync &amp;&gt;/dev/null || yum install -y rsync                                                                                                                                                                                                                                1.2s <br>------<br> &gt; [2/9] RUN yum -q list installed rsync &amp;&gt;/dev/null || yum install -y rsync:<br>0.256 /bin/sh: line 1: yum: command not found<br>------<br>Dockerfile.dependencies:7<br>--------------------<br>   5 |<br>   6 |     # Ensure rsync is installed<br>   7 | &gt;&gt;&gt; RUN yum -q list installed rsync &amp;&gt;/dev/null || yum install -y rsync<br>   8 |<br>   9 |     # Upgrade pip (required by cryptography v3.4 and above, which is a dependency of poetry)<br>--------------------<br>ERROR: failed to solve: process &quot;/bin/sh -c yum -q list installed rsync &amp;&gt;/dev/null || yum install -y rsync&quot; did not complete successfully: exit code: 127<br><br>Error: docker exited with status 1</pre><p>At time of writing, SST currently does not support Python 3.12 bundling with Docker. Please refer to this <a href="https://github.com/sst/sst/pull/3803">pull request</a>.</p><p>For workarounds you can try either:</p><ol><li>Lowering the Python runtime</li><li>Disabling Docker bundling entirely</li></ol><p>To disable Docker bundling your Python functions modify you app.setDefaultFunctionProps with the following</p><pre>app.setDefaultFunctionProps({<br> copyFiles: [{ from: &quot;packages/functions/core&quot;, to: &quot;core&quot; }],<br> runtime: &quot;python3.12&quot;,<br> // I&#39;m new!!<br> python: {<br>  noDocker: true,<br> },<br>});</pre><blockquote>This is what I do</blockquote><h4>Error: Invalid src or dest</h4><pre>Error: Invalid src or dest: cp returned EINVAL (cannot copy \\?\C:\Users\USER\Projects\sst-examples to a subdirectory of self \\?\C:\Users\USER\Projects\sst-examples\.sst\artifacts\c8d6e306086eabf1c90728e1c792479c0c82a524fe) \\?\C:\Users\USER\Projects\sst-examples\.sst\artifacts\c8d6e306086eabf1c90728e1c792479c0c82a524fe</pre><p>When building Python functions SST expects there to be a requirements.txt in the same directory as the Python file. Refer to the !! IMPORTANT comment in the directory structure in the Bootstrapping section above.</p><h3>Cleanup, Comments, and Next Steps</h3><p>We’ve now got ourselves a deployed and working SST project using Python for the backend. This is a solid foundation for future expansion in application logic.</p><p>Before we forget, lets be sure to clean up all the resources we’ve created</p><pre>npm run remove:prod<br><br>and<br><br>npm run remove:local</pre><p>This template, while a solid foundation, still lacks much of the functionality that I believe is required for productive development. However, the goal of this tutorial/template is to be the “bare minimum”.</p><p>In future tutorials I will be covering how to use more AWS features with SST + Python, although they will inevitably contain my opinions on project structure and business logic. The topics I intend to cover:</p><ul><li>Extending the Api (Validation, Authentication)</li><li>Typesafe DynamoDB with Python</li><li>Typesafe EventBridge with Python</li></ul><p>If these topics interest you, drop a follow. I’ll be getting to them in the near future.</p><blockquote>Git repo for this article: <a href="https://github.com/JacksonBowe/sst-examples/tree/main/python-base-template">https://github.com/JacksonBowe/sst-examples/tree/main/python-base-template</a></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=82beefc00cde" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Adding a Lobby System to my Serverless Multiplayer Game]]></title>
            <link>https://medium.com/@jacksonbowe98/adding-a-lobby-system-to-my-serverless-multiplayer-game-60bbd2661a0e?source=rss-c2f9a8700fb5------2</link>
            <guid isPermaLink="false">https://medium.com/p/60bbd2661a0e</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[game-development]]></category>
            <category><![CDATA[serverless]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Jackson Bowe]]></dc:creator>
            <pubDate>Tue, 08 Aug 2023 04:56:17 GMT</pubDate>
            <atom:updated>2023-08-08T04:56:17.564Z</atom:updated>
            <content:encoded><![CDATA[<p>This is the third post in a series of articles documenting my process creating a serverless multiplayer game — Mafia.</p><p>This article covers how I created a basic lobby system, expanding on the foundation from my previous post.</p><h3>Lambda Design</h3><p>As I mentioned in my first article about this project, I have chosen to group code based on the entity if affects. Each Lambda function in my app performs a specific task, and groups of Lambdas are called Controllers.</p><p>All Lambda function in a Controller share the same files and code, but have alternate entry points.<br><em>This may be a bad approach, however I find it intuitive so far.</em></p><p>To maintain consistent API code and response structure I have committed to using <a href="https://github.com/aws-powertools/powertools-lambda-python">Powertools for AWS Lambda</a>. This package will also allow me to easily implement Lambda traffic tracing if I choose to do so in the future.</p><h4>API Example</h4><p>Below is an example snippet from the API to handle Lobby actions. Note that while the code contains two API routes, the deployment process will create a dedicated lambda for each one.</p><pre># very basic api example<br><br># Controller that handles all Lobby actions<br>from core.controllers import LobbyController<br><br># API route and target function<br>@app.get(&#39;/lobby&#39;)<br>def get_lobbies():<br>  return LobbyController().get_lobbies()<br><br>@app.post(&#39;/lobby/host&#39;)<br>def host_lobby():<br>  details = ... # from payload<br>  return LobbyController().host_lobby()</pre><h3>Defining the LobbyController</h3><p>The API exposes the following methods to users:</p><ul><li>HostLobby</li><li>JoinLobby</li><li>GetLobby</li><li>GetLobbies</li><li>LeaveLobby</li><li>StartLobby (if Host)</li><li>TerminateLobby (if Admin)</li></ul><p>These methods read/write to the DynamoDB table and retrieve/update/create Lobby records as needed. Certain actions like joining or leaving a lobby require informing all other users in the lobby. To achieve this I chose to use AWS IoT Core — more on that later.</p><p>This is the new AWS Infrastructure diagram after the LobbyController addition (grey is planned):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/909/1*03kH5adFvaRv6L642ODgEg.png" /></figure><h4>DynamoDB Entity Schema</h4><p>One of the rough edges when dealing with DynamoDB is that all the items are returned as JSON. This structure was manageable at small scale, but I found that it was not viable as the complexity of the project grew.</p><p>To sum up my struggles in simple terms; when reading an item from DynamoDB there was no way to know what fields the item contained without:</p><ul><li>A — assuming the field exists and handling the errors</li><li>B — remembering all fields for all items</li><li>C — looking at the database as a reminder</li></ul><p>To mitigate the mental strain caused by the above I opted to declare all DynamoDB items as dataclasses — analogous to a typical relational database schema.</p><p>With this goal in mind I settled on the base Entity:</p><pre>@dataclass<br>class Entity:<br>  id: str<br>  createdAt: int<br><br>  def to_dict(self, exclude_none=True) -&gt; dict:<br>    # exclude_none=True removes all keys from the output dict where the value is None<br>    if exclude_none: return {k: v for k, v in asdict(self).items() if v is not None}<br>    else: return asdict(self)</pre><p>All further items inherit from the base Entity. Below is what the User entity looks like:</p><pre>@dataclass<br>class User(Entity):<br>    displayName: str<br>    lobby: Optional[str] = None<br>    game: Optional[str] = None<br>    isAdmin: Optional[bool] = None<br>    type: str = &quot;USER&quot;<br>    <br>    @classmethod<br>    def new(cls, user_id: str, name: str) -&gt; User:<br>        return cls(id=user_id, displayName=name, createdAt=timestamp())<br>        <br>    @classmethod<br>    def from_primary(cls, user: dict) -&gt; User:<br>        return cls(**id(user))<br><br>    @classmethod<br>    def from_gsi1(cls, user: dict) -&gt; User:<br>      pass<br><br>    def to_ddb(self) -&gt; dict:<br>        item = self.to_dict(exclude_none=True)<br>        item[&#39;PK&#39;] = item.pop(&#39;id&#39;)<br>        item[&#39;SK&#39;] = &#39;A&#39;<br>        return item</pre><p>I’ve also opted to use @classmethod&#39;s as show in that code snippet. The @classmethod decorator allows for alternate class constructors, which I use depending on the data source. For example, the from_primary() function specifies how the User entity should be constructed when reading from the Primary Index of the Dynamo table.</p><p>I have Entities for Lobby and LobbyUser provisioned in a similar style.</p><h4>Push Notifications</h4><p>I have adopted AWS IoT Core for all my push notifications for the following reasons:</p><ul><li>Simplicity</li><li>Scalability</li><li>Speed</li><li>Sprice? (I don’t actually know about this one for sure)</li></ul><p><strong>Simplicity<br></strong>IoT Core is a WebSocket service provided by default with every AWS account. It uses the MQTT protocol which follows a pub/sub structure. Clients subscribe to a ‘topic’ and receive all messages published to the topic.</p><p><strong>Scalability</strong><br>IoT Core was designed to support millions of devices and as a fully managed service all scaling is handled by AWS. The consumer (me 😭) simply pays based on the usage amount.</p><p><strong>Speed and Sprice</strong><br>This is where I have made some assumptions.</p><p>A non-IoT Core solution would be to use a Lambda function configured as a WebSocket connector. When users connect the Lambda would store their connectionId into a Dynamo table and when messages need to be sent to the user, their connectionId could be retrieved.</p><p>The downsides of this approach, and why I ultimately chose IoT Core, is that for every message to sent by a user, all targets would need to be read from the DB. I felt that this would be to slow, and most likely very expensive.</p><p>It is my opinion that IoT Core will be faster and cheaper than the basic Lambda WebSocket option, but time will tell.</p><h3>Frontend</h3><p>Lobby functionality on the frontend is a mix of API data fetching and IoT updates.</p><p>Fetching, hosting, joining, and leaving lobbies are all actions that can be resolved independently of other clients, thus are done via the HTTP API.</p><p>Here’s a short YouTube video showcasing the Lobby system from the perspective of two users, including transitioning from a Lobby to a Game (more on Games in the next post)</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FYfsaubXHLp8%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DYfsaubXHLp8&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FYfsaubXHLp8%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/c38f172eb1afbeee3daf1ffc0d9eeebb/href">https://medium.com/media/c38f172eb1afbeee3daf1ffc0d9eeebb/href</a></iframe><p>That’s all for this update. I’ve made heaps more progress, but not quite ready to package into a write-up.</p><p>If you’re interested in the project and want smaller more frequent updates, check out the discord server (<a href="https://discord.gg/EcGx9h2fwy">https://discord.gg/EcGx9h2fwy</a>). As always, happy to answer any questions, technical or game related.</p><p>Cheers</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=60bbd2661a0e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creating Our Serverless Multiplayer Mafia Game: Adding User Authentication]]></title>
            <link>https://medium.com/better-programming/mafia-1-user-authentication-7ab77883ba9c?source=rss-c2f9a8700fb5------2</link>
            <guid isPermaLink="false">https://medium.com/p/7ab77883ba9c</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[serverless]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[game-development]]></category>
            <dc:creator><![CDATA[Jackson Bowe]]></dc:creator>
            <pubDate>Fri, 21 Apr 2023 04:32:47 GMT</pubDate>
            <atom:updated>2023-05-03T07:59:37.779Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/956/1*wis3-7eNzwhY17RMUbwzXA.png" /></figure><p>This is the second post in a series of articles documenting my process of creating a serverless multiplayer game — Mafia. This article covers adding User Authentication and Authorization to the game.</p><h3>Setting up AWS for a new project</h3><p>If you search online for AWS project best practices you will find a dozen different guidelines all espousing their method to be the “best”. I’d like to avoid pushing my methodology on you here, but this is a quick rundown of the process that I used.</p><p>My main AWS account (the one that I first created) is an empty shell containing no resources. In this account I created an AWS Organization. Under an organization, you can create groups — I’ve made a group for Mafia. Inside the Mafia group I make two more groups; <strong>dev</strong> and <strong>prod</strong>. These two groups each have an AWS account in them.</p><p>In my root AWS account I then configured IAM Identity Center for Single-Sign-On (SSO) and created an SSO profile for myself with Admin Access to the two Mafia accounts. This new SSO account can now generate AWS CLI access keys for each of the deployments (<strong>prod</strong>/<strong>dev</strong>).</p><h3>Infrastructure Overview</h3><p>In this game users will have individual profiles. Logging in retrieves the associated profile from the database and tags all future API calls with the users’ ID. The API will then use the provided ID to determine if the caller has permission to perform whichever action they’re attempting.</p><p>AWS has all the tools to create a robust serverless user authentication system and SST makes it super easy to get started. For this project I’m going to be using the following AWS services:</p><ol><li>AWS Cognito — to handle user authentication (validate passwords)</li><li>AWS ApiGateway — to route frontend actions to backend functions</li><li>AWS Lambda — the logic</li><li>AWS DynamoDB — to store user profiles</li></ol><p>There are two main ‘routes’ to the API for authentication; /noauth and /{other}. The /noauth route is exclusively used for signup/signin/recovery/etc actions (may be expanded in future).</p><p>The /{other} route is simple a placeholder for all other routes. Each of these calls is processed through a custom Lambda Authorizer which validates the user&#39;s access token and then forwards it to the AuthController Lambda.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/971/1*-ViO57ZDAmTeDRX1vcH5bw.png" /><figcaption>Resource flow for User Authentication</figcaption></figure><h4>DynamoDB setup</h4><p>DynamoDB is a NoSQL database that offers huge horizontal scaling for a relatively low price point, following a pay-per-request model. There are plenty of ways to use DynamoDB but for this project, I’m attempting to follow Single-Table Design (STD??) principles as best I can.</p><p>The goal of STD is one big boy DynamoDB table that holds all entity data in one place. The benefits of this approach are speed (apparently?) and increasing the complexity of your business logic by a few magnitudes. I’ll try until it gets too hard I guess.</p><p>With the single table approach, it’s important to have a good grasp on what the access patterns are going to be. That is, in what ways do I intend to query data? Theoretically, by knowing how you intend to <em>query</em> the data you can infer the optimal way to <em>store</em> it. If you are unfamiliar with DynamoDB this next part might be a bit confusing.</p><p>Currently, my access patterns are as follows:</p><pre>- [GET] Item by exact ID (PK + SK) — To retrieve a single record: User/Lobby/Game/etc<br>- [QUERY] Items by partition ID — To retrieve all records under a partition key: eg. A Lobby and all Users in it<br>- [QUERY] Items by type (GSI1) — To retrieve all records of a type Users/Lobby/Game<br><br>PK = PartitionKey, SK = SortKey (Dynamo terminology, dw about it)</pre><p>GET calls to return exactly one record whereas QUERY’s return all records that match.</p><p>In NoSQL Workbench I made a mock-up of the data structure to visualize my GSIs.</p><p>Primary projection: The red marking shows that Lobby(PK=2143) contains records for itself (SK=A) and the user UncleGenghi (SK=U#1234). Note that I’m encoding the entity type into the SK.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kf1GvaGZWt2MszWVGZVjiw.png" /><figcaption>DDB Primary Projection</figcaption></figure><p>GSI1 (itemsByType): Projects all records into their TYPE grouping.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*q5-iN1-cfYPA7sDK1Po8RQ.png" /><figcaption>GSI1: itemsByType</figcaption></figure><h3>User Authentication</h3><p>As mentioned previously, I am using AWS Cognito to handle user registration and validation. The Cognito functions are exposed to the front end via HTTPS API using ApiGateway. Calls such as /noauth/auth pass directly to the AuthController, in this example returns a JWT access token (providing supplied email and password are valid). The JWT token must then be used in the headers of all future requests.</p><h3>User Authorization</h3><p>I decided to use a custom Lambda Authorizer for this project with these two resources for reference: <a href="https://aws.amazon.com/blogs/security/building-fine-grained-authorization-using-amazon-cognito-api-gateway-and-iam/">AWS Article</a>, <a href="https://github.com/aws-samples/amazon-cognito-api-gateway/blob/main/custom-auth/lambda.py">Code</a>.</p><p>Custom Lambda Authorizers are great for adding fine-grain authorization but come with some noticeable performance reductions and cost increases.</p><p>For starters, in terms of AWS resources a Lambda Authorizer is identical to a standard lambda function. This means that all API Gateway routes that flow through a Lambda Authorizer now count as 2 lambda invocations. Two invocations mean an increase in time and cost. The more complex the authorizer, the slower every API route that uses it gets.</p><p>Below is an example of an API call that returns a list of all open lobbies. As we can see, before the GET /lobby/list call we must first be authorized.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/732/1*NdE_2KSgpEoWKR4MslL_Wg.png" /><figcaption>Example of Custom Lambda Authorizer</figcaption></figure><p>Overall, while the authorizer definitely adds overhead to the API I believe that the ability to have granular access is crucial.</p><h3>Quasar frontend</h3><p><a href="https://quasar.dev/">Quasar framework</a> is my go-to when building complex web apps. It uses VueJS under the hood but comes with so many useful utilities that it’s hard for me to justify not using it.</p><p>I think that both the best and worst thing about Quasar is how easy it is to create visually appealing and responsive frontends. I say “and worst” because to be honest, using Quasar feels like cheating. Prior to using Quasar, I had very little frontend experience with vanilla Javascript and CSS, essentially zero foundational knowledge. Quasar lets me get away with not learning the basics and still succeed. Still not sure how I feel about that, but anyway…</p><p>This is my attempt at a log in page. It’s probably nothing fancy to any experienced WebDev’s reading, but it’s pretty up there for me. I linked it up to the backend and it works great. I may remove the self-signup feature temporarily in place of an invite-only system so I can do some controlled public testing, but that’s unimportant to this article.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/956/1*wis3-7eNzwhY17RMUbwzXA.png" /><figcaption>Mafia login page</figcaption></figure><p>To ensure that my design is appropriately responsive I’m using an app called <a href="https://responsively.app/">ResponsivelyApp</a>. The app lets me select several target screen sizes and validate my design on all of them on the same screen. Check it out.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0DjIwYcUMWZf5Xz39wHCMA.png" /><figcaption>Mafia in ResponsivelyApp</figcaption></figure><p>That pretty much wraps up everything I wanted to cover in this article. In my estimation, the main educational aspect of this article series is going to be the AWS design and integration. Frontend design/development is very much a necessary chore to me while API and cloud infrastructure design is where the real interesting stuff happens.</p><p>At the time of writing this, I’ve made significant progress towards a lobby hosting/joining system. It’s not quite at the stage where I can confidently write about it, but what I can say is that it leverages AWS IoT Core to facilitate real-time push notifications to the front end.</p><p>If you’re interested in this project I’ve made a discord (<a href="https://discord.gg/EcGx9h2fwy">https://discord.gg/EcGx9h2fwy</a>) where I post updates as I go. Happy to answer any questions whether technical or game related.</p><p>Cheers,</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7ab77883ba9c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/mafia-1-user-authentication-7ab77883ba9c">Creating Our Serverless Multiplayer Mafia Game: Adding User Authentication</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mafia — A Serverless Multiplayer Game]]></title>
            <link>https://medium.com/better-programming/mafia-a-serverless-multiplayer-game-95427fb25fba?source=rss-c2f9a8700fb5------2</link>
            <guid isPermaLink="false">https://medium.com/p/95427fb25fba</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[gaming]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Jackson Bowe]]></dc:creator>
            <pubDate>Mon, 27 Feb 2023 00:58:39 GMT</pubDate>
            <atom:updated>2023-03-05T19:37:55.335Z</atom:updated>
            <content:encoded><![CDATA[<h3>Mafia — A Serverless Multiplayer Game</h3><h4>Using AWS to host a serverless multiplayer game</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XCT-7FgGM5yGCjrjqQ_FwQ.png" /><figcaption>The village at night | by Se<a href="https://www.shutterstock.com/image-illustration/small-fairy-tale-town-night-fiction-1267216252">ra Elsden</a></figcaption></figure><p>This is the first article (of hopefully many) where I will be documenting my journey in creating a serverless multiplayer game, Mafia (name not final… unless???).</p><p>I will use this first article to cover the tools I intend to use and give a general idea of what this game should look like at the end. So, here we go.</p><h3>What Is This Game?</h3><p>I’m basing this game heavily on the popular tabletop game by the same name. It’s a <a href="https://en.wikipedia.org/wiki/Social_deduction_game#:~:text=A%20social%20deduction%20game%20is,and%20another%20being%20%22bad%22">social deduction game</a> in which a majority team, the Town, tries to root out the opposing minority team, the Mafia.</p><p>Members of the Mafia are aware of their allies and must work together to mislead the Town and avoid suspicion. Town players are unaware of anyone else’s role and must use their deductive reasoning to locate evildoers.</p><h4>Mechanics</h4><p>The game isn’t strictly turn-based. However, it follows a similar principle. There are four states: Morning, Day, Evening, and Night.</p><p>During the Day, all town members (including the mafia members) gather to discuss what leads they have found on the Mafia. At this time, they may also decide to remove a player suspected of being a member of the Mafia.</p><p>In the Evening, the public forum closes, and players are given time to process the day’s conversation, and if possible, with their role, they can chose a player to target that night. For example, a detective may choose to follow another player and see who they visit that night. Mafia members are able to converse amongst themselves during this time.</p><p>During the Night, the game processes all the player’s actions.</p><p>In the Morning, the events of the previous Night are revealed to the town.</p><p>The cycle repeats until there is a winner.</p><h3>Games Are for Nerds. What’s the Tech Stack?</h3><p>Heavy sarcasm :).</p><h4>What I’m using</h4><p>I want the game to be playable in the web browser at this stage, which may change in future. Also, I’m primarily using AWS for the backend.</p><p><strong>Backend</strong></p><ul><li><a href="https://aws.amazon.com/api-gateway/">AWS ApiGateway</a> for player-to-backend communication</li><li><a href="https://aws.amazon.com/dynamodb/">AWS DynamoDB</a> as a database following <a href="https://aws.amazon.com/blogs/compute/creating-a-single-table-design-with-amazon-dynamodb/">Single Table Design</a> principles</li><li><a href="https://aws.amazon.com/cognito/">AWS Cognito</a> for user authentication</li><li><a href="https://aws.amazon.com/s3/">AWS S3</a> for medium/large file storage (images, etc.)</li><li><a href="https://aws.amazon.com/iot/">AWS IoT Core</a> for the pub/sub functionality (live updates)</li><li><a href="https://www.postman.com/">Postman</a> to test and document the API</li></ul><p>All application logic will be written in Python.</p><p><strong>Frontend<em><br></em></strong>The frontend will be made with <a href="https://quasar.dev/">Quasar Framework</a> — a Vue.js wrapper. Quasar comes bundles with a wide array of prebuilt components and very thorough documentation. Another benefit is that Quasar streamlines the process of packaging a single codebase into multiple deployment formats: web, mobile, and desktop. This sparks joy.</p><p><strong>The Glue<em><br></em></strong>As I previously stated, my goal with this project is 100% serverless. However, another requirement is just as important — 100% Infrastructure as Code. IaC is exactly as it reads. All the infrastructure covered in the backend section should be provisioned in code, with nothing needing to be created in AWS manually.</p><p>There are several benefits to this approach:</p><ol><li>Changes to infrastructure can be tracked with Git. Manual editing via the AWS console is untrackable and generates no history.</li><li>The project can be deployed with a single command. If I deploy in Australia, and then have reason to deploy in North America, I must be able to do so with confidence and speed.</li><li>The project can be destroyed with a single command. This is extremely important. If I determine the cost becomes unsustainable, I must be able to completely eradicate all traces of it with no remnants remaining—scorched earth.</li></ol><p>The IaC framework I will be using for this project is <a href="https://serverless-stack.com/">Serverless Stack (SST)</a>.</p><p>SST is a cloud architecture development kit that lets you provision Infrastructure as Code by leveraging the base <a href="https://docs.aws.amazon.com/cdk/v2/guide/home.html">AWS CDK</a> with improvements geared towards serverless applications. If you’ve used any IaC providers in the past, like Terraform, AWS CDK, Serverless, SAM, etc. — I seriously recommend checking out SST. It’s next level.</p><h3>Process, MVP, and Timeline</h3><p>This project is my way of diving headfirst into serverless cloud development. I’m using something I’m passionate about to motivate and upskill myself in a field I think is the future. For this reason, I will attempt to follow as many best practices as possible and share them here as I adopt them.</p><p>Below is a flow chart with my rough architecture plan. This will no doubt change as the project matures.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/950/1*_TSsgjHAgWx0FmtUsLV_wQ.png" /><figcaption>Mafia architecture diagram</figcaption></figure><h4>Process</h4><p>User actions are sent via REST API to an AWS API Gateway. This distributes requests to the appropriate lambda microservice, called *Controllers.* The Controllers handle all application logic between frontend and backend services such as the database.</p><p>As there is no server, I cannot maintain a continuous state. All user actions must be written to the database. During the Night sequence, all user actions will be read from the database and combined with data about the game (settings, etc.).</p><p>The combined user actions and game settings will be resolved using my custom MafiaEngine. This will return the resolved game state to be communicated back to the users.</p><h4>Minimum viable product</h4><p>The maximum number of players in a game is 15. A typical game will have nine Town players, three Mafia players, and three Neutrals. A fully featured game will have large role diversity between the players. However, as players can share the same role, I will be aiming for the following:</p><ul><li>Town: Citizen, Doctor, Bodyguard, Detective, Escort</li><li>Mafia: Mafioso, Liaison (evil Escort)</li><li>Neutral: Serial Killer, Survivor, Jester (of course)</li></ul><p>The game will need a fully functioning lobby system, stage transitioning (morning/night/etc.), and state resolution.</p><h4>Timeline</h4><p>I began routine work in early January 2023 and have maintained decent weekly progress. I hope to have a playable version of this game out within two months (the end of April). Between now and then, I will aim for regular updates and cover technical roadblocks and solutions.</p><h3>Conclusion</h3><p>I don’t particularly want this series to be a generic game “devlog” thing. The real motivation behind this project was to get familiar with serverless cloud development, and I think it will be a massive learning opportunity.</p><p>I’m more interested in writing about how I’ve implemented some serverless features and provided a legitimate use case that is fulfilling.</p><p>If this project sounds interesting, I’d love to hear from you, especially if you see me running headlong into a classic pitfall.</p><p>Note: I’m keeping somewhat up-to-date technical documentation for the project at <a href="https://mafia-sdg.netlify.app/">https://mafia-sdg.netlify.app/</a>.</p><p>Cheers.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=95427fb25fba" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/mafia-a-serverless-multiplayer-game-95427fb25fba">Mafia — A Serverless Multiplayer Game</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AWS for the Solo Developer: Getting Started]]></title>
            <link>https://medium.com/@jacksonbowe98/aws-for-the-solo-developer-getting-started-301a62c9caa6?source=rss-c2f9a8700fb5------2</link>
            <guid isPermaLink="false">https://medium.com/p/301a62c9caa6</guid>
            <category><![CDATA[guides-and-tutorials]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[serverless]]></category>
            <category><![CDATA[amazon-web-services]]></category>
            <dc:creator><![CDATA[Jackson Bowe]]></dc:creator>
            <pubDate>Fri, 02 Dec 2022 06:03:33 GMT</pubDate>
            <atom:updated>2022-12-02T06:03:33.531Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*MRqC8MFY2hFmqZsf" /><figcaption>Photo by <a href="https://unsplash.com/@glenncarstenspeters?utm_source=medium&amp;utm_medium=referral">Glenn Carstens-Peters</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>This is the start of a series of short form articles covering my recommendations (and justifications) for setting up and managing your AWS projects as a solo developer.</p><h4>Prerequisites</h4><p>Technically there are no requirements for getting started with AWS, but I’m going to suggest some because I feel it’s important.<br>- Know why you are creating an AWS account (learning/business/whatever)<br>- Read this (and subsequent) article fully before you decide to implement breaking changes<br>- Don’t blindly accept what I’m saying. These recommendations are what I found to be best suited for my needs. You may differ. Go have a think and if you don’t like it, don’t do it.</p><p>For each of the sections I write about, I’ll attempt to link to the official documentation I initially followed.</p><h3>Foundation</h3><p>This link covers getting your account created and CLI set up correctly. <a href="https://aws.amazon.com/getting-started/guides/setup-environment/?pg=gs&amp;sec=gtkaws">https://aws.amazon.com/getting-started/guides/setup-environment/?pg=gs&amp;sec=gtkaws</a></p><p>I recommend following steps 1–3.</p><p>Congrats, you now have an AWS account and should be logged into the Management Console.</p><p><strong>Note the word <em>Management</em>. The console is for Viewing Infrastructure and <em>Managing Resources</em>. It is NOT for creating/provisioning Infrastructure. If I catch you doing this I will smack you, understand?</strong></p><h4>Why can’t I create Infrastructure on the Console? The buttons make it so easy.</h4><p>Console has no version control. You’re a developer. You like version control. The fastest way to rack up an AWS bill is to click check boxes that you don’t understand and have no way to roll back.</p><h4>How do I use it without the Console?</h4><p>We’ll get to that later. Little thing the cool kids refer to as Infrastructure as Code (IaC).</p><h4>Is it expensive?</h4><p>It can be if you don’t know what you’re doing. All pricing information is provided to you, but if you don’t have a proper understanding you can incur unforeseen costs. That’s why you have this guide.</p><h3>Exploring the Console</h3><p>Don’t take my earlier warning of the Console to mean that you should never use it. For management tasks it’s where you want to be. Lets run through some of what I consider to be the most important features of the console.</p><p>If you’ve followed the official AWS Getting started link I provided above you should have a created a user in IAM with administrator privileges. This is the user you will use for management tasks. Before logging in to that user there are a few things I recommend.</p><h4>Billing</h4><p><strong>Access Billing dashboard<br></strong>You’re going to want to create some Billing alerts. You could do this from the <strong>root </strong>account, but that’s not ideal. Instead what you should do is give Billing access to that IAM user you created for regular use.</p><p>Follow the steps 1–4 here: <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/tutorial_billing.html#tutorial-billing-step1">https://docs.aws.amazon.com/IAM/latest/UserGuide/tutorial_billing.html#tutorial-billing-step1</a></p><p>Attach the BillingFullAccess policy to your Adminitrators IAM User Group. You can now log out of the root user into your regular access user to complete the rest of the steps.</p><p><strong>Setting a Budget<br></strong>The Billing Dashboard is pretty full on and I’ll leave it to you to explore in depth. The main thing we’re going to do here is set up a Budget. On the left navigation panel click <strong>Budgets</strong>. From here you can create a Budget to your specs. For myself I’ve got a $10 budget set and have not yet hit it.</p><h4>CloudWatch</h4><p>Search it in the bar up the top. This is where the bulk of your monitoring happens. You can set up Alarms and view event Logs. Don’t create anything yet, but click around and get familiar with the different dashboards.</p><h3>AWS Organisations</h3><p><a href="https://us-east-1.console.aws.amazon.com/organizations/v2/home/accounts">AWS Organisations</a> are a collection of AWS accounts under one Root (Management) Account. Organisations allow you to quickly spin up new AWS accounts without going through the whole manual process.</p><p>I recommend creating an Organisation at the outset for several reasons.</p><ol><li>Infrastructure segregation</li><li>Bill breakdown</li><li>Ability to sell projects</li></ol><p>Each of those points deserve some creative elaboration.</p><h4>Infrastructure Segregation</h4><p>One of the many problems with a single account setup is that you will most likely have more than a single project. That leaves you with two options; deal with it and name things in a way you understand, or make a separate account for each project.</p><p>Speaking from experience, it’s extremely enticing to go with the single account approach because it’s the least complicated and it gets you up and running fast. The problem is that it doesn’t scale. Each new project you start will be competing for screen space with all that came before it, and you <strong>will</strong> get confused, especially when resources are named like this: <strong>prod-my-function-name — apiLambdaPOSTmiles-Vcki7fM1rFqI</strong>.</p><p>Imagine looking through a list of 50 things named like that.</p><h4>Bill Breakdown</h4><p>I mentioned the term “Management Account”. In an AWS Organisation, this is the account that handles the payments. It’s the top of the umbrella, and all the accounts under it pass their Bills up. By having an Organisation, you can see which accounts (or projects if you create 1 account per project) are contributing to your monthly bill and by how much. In a single account setup all costs are aggregated across all projects into a single Bill.<br><strong>Note: with an Organisation you will still get a single bill, but inside it will tag which account/s contributed to the line item and by how much</strong></p><h4>Selling</h4><p>Say you have an idea for a product. You log into your single AWS account full of all your dead hopes and dreams and get to work. By some stroke of luck you actually manage to stick to something for more than 3 weeks and you get a production ready product up and running.</p><p>Now I come along with my Scrooge McDuck money and I give you the golden offer to buy your product. What’s your play?</p><p>If you’ve made the whole thing by clicking buttons in the console are you really going to be able to give me the 400 point process to replicate what you did? Maybe you did the whole Infrastructure as Code thing and you can give me the code repo. But wait, all your users are connected to your current deployment. Taking that down and letting me spin it up could inconvenience users.</p><p>You’d like to just offer me the whole account, but you can’t do that either because it’s full of the corpses of projects past. You’re doomed, and I’ve just used the silo of money I was going to give you to get my own developers to copy your product.</p><p>Same scenario but you keep all of your projects in a dedicated AWS account. I ask to buy you out, we agree on a price, and you transfer ownership of the AWS account and code Repo to me in exchange for a million pennies. You can now move onto the next project.</p><p>This is why I recommend AWS Organisations.</p><p><em>Disclaimer: I am not a duck. I do not have silo’s of gold bullion at my disposal to purchase your products.</em></p><h3>Setting up your Organisation</h3><p>This is how my personal AWS accounts are set up.</p><h4>Organisation</h4><p>I have a number of different projects deployed on AWS. To keep them separate, each project is split between two AWS accounts. One of the accounts holds the <strong>dev</strong> environment and the other holds the <strong>prod</strong> environment. You can have more environments, but I wouldn&#39;t suggest less.</p><p>To keep track of these accounts I leverage AWS Organisations. Inside Organisations I create an <a href="https://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_ous.html">Organisational Unit (OU)</a> to wrap the project. Inside the project OU are my environment OU’s (dev/prod) with an AWS account in each.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*aV685XaRd6F-43VMPF-L2Q.png" /><figcaption>Sample AWS Organisation</figcaption></figure><h4>IAM Identity Center (SSO)</h4><p>The issue with having multiple AWS accounts is that you would typically need at least one user account for each. Instead of this I recommend <a href="https://ap-southeast-2.console.aws.amazon.com/singlesignon/identity/home?region=ap-southeast-2#!/dashboard">IAM Identity Center</a>.</p><p>IAM Identity Center is basically an active directory. It functions similarly to IAM, with a couple extra features.</p><p><strong>Create a User<br></strong>From this service I recommend creating a Permission Set called AdministratorAccess and attaching it to a User (or group if you want). This will give your IAM Identity Center user Admin permissions to any AWS account they have access to.</p><p>I recommend setting the email address to an alias of your management account address (gmail uses the + symbol).<br>e.g <a href="/service/mailto:jacksonbowe123+aws-sso-admin@gmail.com">jacksonbowe123+aws-sso-admin@gmail.com</a></p><p>It’ll send you a welcome email. Login in a new tab.</p><p><strong>Grant Access to AWS Accounts as needed<br></strong>In the <strong>AWS accounts</strong> tab of Identity Center select all the AWS accounts in your Organisation (bar the management account) and assign your new user to them.</p><p>You now have an Administrator level user who can access all your AWS accounts with a single set of login credentials. To visualise this, go to the tab you opened previously and relog. You should see something that looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/915/1*ugXERkqowiV3aE80BOVyGw.png" /><figcaption>AWS SSO Example</figcaption></figure><p>From here you can log in to the Management Console for each account and bask in the clean environment, free of clutter.</p><h3>That’s it for setup</h3><p>If you followed the above recommendations you should have an AWS account which has the following:</p><ol><li>An IAM user with AdminFullAccess and BillingFullAccess permissions</li><li>A Budget</li><li>An Organisation with sub-AWS accounts</li><li>An IAM Identity Center user with AdministratorAccess to all sub-accounts in the Organisation</li></ol><p>In a follow up post to this I’ll cover how to set up your development environment to begin provisioning AWS resources through Infrastructure as Code.</p><p>Thanks for reading</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=301a62c9caa6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AWS CDK — Provisioning a Rest API (Python)]]></title>
            <link>https://medium.com/@jacksonbowe98/aws-cdk-provisioning-a-rest-api-python-5294a70ba945?source=rss-c2f9a8700fb5------2</link>
            <guid isPermaLink="false">https://medium.com/p/5294a70ba945</guid>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[serverless]]></category>
            <category><![CDATA[aws-cdk]]></category>
            <category><![CDATA[aws-lambda]]></category>
            <dc:creator><![CDATA[Jackson Bowe]]></dc:creator>
            <pubDate>Thu, 08 Sep 2022 05:47:11 GMT</pubDate>
            <atom:updated>2022-09-08T05:47:11.321Z</atom:updated>
            <content:encoded><![CDATA[<h3>AWS CDK — Provisioning a Rest API (Python)</h3><p>Date: 08–09–2022</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/825/1*lKGJrgLgSMshYoTpusdYzg.png" /><figcaption>Photo by <a href="https://unsplash.com/ja/@cazat69?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Victor Lu</a> on <a href="https://unsplash.com/s/photos/gateway?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a>. Then edited by me.</figcaption></figure><p>This is a short tutorial on how to provision a <a href="https://docs.aws.amazon.com/cdk/api/v1/python/aws_cdk.aws_apigateway/LambdaRestApi.html">LambdaRestApi</a> with <a href="https://aws.amazon.com/api-gateway/">AWS ApiGateway</a> via the <a href="https://docs.aws.amazon.com/cdk/v2/guide/home.html">AWS CDK</a>. The goal of this article is to cover some of the basics in a more verbose format than the official docs.</p><p><em>Covered:</em></p><ul><li>Provisioning an API</li><li>Adding routes to API</li><li>Enabling CORS on API</li></ul><h3>Prerequisites</h3><ul><li>AWS CDK project initialised. Doesn’t need to be fresh if you already have one.</li></ul><h4><strong><em>Directory Structure:</em></strong></h4><p>This is the directory structure that I’ve found works best for me. You don’t need to copy it, but this is what I’ll be using as a reference.</p><pre>cdk-project<br>|-- lambdas/<br>    |-- default/<br>	|-- main.py<br>    |-- ping_controller/<br>        |-- main.py<br>|-- project/<br>    |-- components/<br>	|-- api.py<br>    |-- __init__.py<br>    |-- project_stack.py</pre><h3>Process</h3><p>Step by step process based on the above project structure. The file names I’ll be using in these steps directly relate to the files in the above Directory Structure.</p><p>Note: Starting in the root directory of your CDK prokect ../#/cdk-project&gt;</p><h4>Create the API Construct</h4><ol><li>In api.py create a new Construct called <em>Api</em></li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9778b004d4492ac8b2f9f430b6355faa/href">https://medium.com/media/9778b004d4492ac8b2f9f430b6355faa/href</a></iframe><p>2. Provision a “default” lambda function. This is required to provision a LambdaRestApi.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3751a76914dbeb0445b29a9f6805c518/href">https://medium.com/media/3751a76914dbeb0445b29a9f6805c518/href</a></iframe><p>3. Provision the API</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/94aa8c54acfb33c49ae7065bdcb079ac/href">https://medium.com/media/94aa8c54acfb33c49ae7065bdcb079ac/href</a></iframe><p>4. Add a route to the API</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b6b2e859b7e56d1ea5e649d6a146686c/href">https://medium.com/media/b6b2e859b7e56d1ea5e649d6a146686c/href</a></iframe><p>I recommend manually adding the routes to API Gateway. It’s possible to use “greedy” routes (these are catch-alls) but personally I believe that manually adding all routes leads to a more readable API. See <a href="https://docs.aws.amazon.com/apigateway/latest/developerguide/http-api-develop-routes.html#http-api-routes-path-variables">here</a> for more info.</p><p>5. Edit the ping_controller/main.py file to respond appropriately.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dfba3c4f329ca90c63014bc67aca319a/href">https://medium.com/media/dfba3c4f329ca90c63014bc67aca319a/href</a></iframe><p>You now have an API with a single route /ping . To hit your API endpoint you will need to deploy it with cdk deploy</p><h4>Add the API to the Stack</h4><p>Now that the API Construct is created we need to add it into the CDK Stack and initialise an instance of it.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/19ae7b4b9a9bb980fe1bd175c97835a7/href">https://medium.com/media/19ae7b4b9a9bb980fe1bd175c97835a7/href</a></iframe><h4>Enabling CORS (Optional)</h4><p>CORS (<a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS">Cross Origin Resource Sharing</a>) is a super useful mechanism that prevents baddies from doing stuff to your API. Or something like that, I don’t know I’m not an internet expert. What I do know however is that it’s a real pain when you’re trying to develop a frontend application and consume a deployed API. CORS by default will block all API requests from https://localhost:xyz. That&#39;s lame, lets turn it off (only do this if you know what you&#39;re doing... obviously).</p><ol><li>Edit your API to have the following</li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1f5edb8bfcf7fbf47f4ed11433fa13fd/href">https://medium.com/media/1f5edb8bfcf7fbf47f4ed11433fa13fd/href</a></iframe><p>2. Edit the ping_controller/main.py file to respond with the appropriate CORS headers.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c1f1a5cc534d5647c215db05b596f67f/href">https://medium.com/media/c1f1a5cc534d5647c215db05b596f67f/href</a></iframe><p>That should allow you to test from localhost without running into CORS errors. Should you use this in production? No. You know you shouldn’t. Show of hands who will? ✋✋✋</p><p><strong><em>Note</em></strong>: You will still hit CORS errors if your lambda function crashes. If your code does not have proper error handling and fails to return the cors_headers your application will by default throw a CORS error (because as far as it knows that&#39;s what the problem is).</p><p>The steps above should provide a decent baseline from which to build out a small but functional application utilising API Gateway. I plan on writing some detailed guides on more advanced API + Lambda design so if that’s something you’re interested in do stick around.</p><p>Cheers,</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5294a70ba945" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Invoking Lambda Docker Images with AWS CDK (Python)]]></title>
            <link>https://towardsdev.com/invoking-lambda-docker-images-with-aws-cdk-python-adc74a2e9d1c?source=rss-c2f9a8700fb5------2</link>
            <guid isPermaLink="false">https://medium.com/p/adc74a2e9d1c</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[aws-cdk]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[aws-lambda]]></category>
            <category><![CDATA[serverless]]></category>
            <dc:creator><![CDATA[Jackson Bowe]]></dc:creator>
            <pubDate>Wed, 06 Apr 2022 05:34:39 GMT</pubDate>
            <atom:updated>2022-04-06T05:34:39.043Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/705/1*Ep7ub9pIzwm-QvVgenhaUA.png" /></figure><p>This is Part 2 of a two part post. In <a href="https://medium.com/p/a10bffd20613#56d7-202c55c477fa">Part 1</a> I covered provisioning the lambda docker image, and in this part I will cover interacting with it by <em>invoking </em>it from a standard lambda.</p><p>Covered:</p><ul><li>Provisioning a normal lambda function</li><li>Granting ‘invoke’ permissions for Docker Lambda</li><li>Docker Lambda input and output handling</li></ul><h4>Prerequisites</h4><ul><li>Part 1 complete:<br>- <a href="https://docs.docker.com/get-docker/">Docker</a> installed on local machine<br>- AWS CDK installed and set up correctly</li></ul><p>Note: If you’re not using AWS CDK and you just want to know how to invoke a docker you’ve deployed separately you will need to manually grant invoke permissions to your invoking lambda.</p><h4>Directory Structure</h4><pre>cdk-project<br>|-- lambdas/<br>    |-- docker_func/ # From Part 1<br>    |-- new_func/<br>        |-- main.py<br>|-- project/<br>    |-- project_stack.py</pre><h3>Process</h3><p>Note: Since this is an extension of Part 1, I will be directly referencing files/functions created in it. I will make it clear when I do this.</p><h4>Invoke from a standard lambda</h4><p>This section will layout how to invoke a Lambda docker image from a standard python Lambda.</p><ol><li>Provision the standard Lambda (if needed)</li></ol><pre># docker_lambda = _lambda.DockerImageFunction(...) ## From Part 1</pre><pre>new_lambda = _lambda.Function(<br>    self, &#39;NewLambda&#39;,<br>    runtime=_lambda.Runtime.PYTHON_3_8,<br>    code=_lambda.Code.from_asset(&#39;lambdas/new_func&#39;),<br>    handler=&#39;main.handler&#39;<br>    environment={<br>        &quot;DOCKER_LAMBDA_NAME&quot;: docker_lambda.function_name<br>)</pre><p>Note the environment variable “DOCKER_LAMBDA NAME”. When you generate infrastructure using CDK it gives all your resources fair verbose names.</p><p>eg: MyCoolStack-APINewLambdaXXXX-XXXXXXXXXXXX</p><p>You don’t want to remember this. Yuck. Instead we can tell CDK that once it’s generated a name for our lambda, we want to grab it and use it in another resource (<strong>new_lambda</strong> in this instance)</p><p>2. Grant <em>invoke</em> permissions</p><pre># docker_lambda = _lambda.DockerImageFunction(...) ## From Part 1<br># new_lambda = _lambda.Function(...)</pre><pre>docker_lambda.grant_invoke(new_lambda)</pre><p>3. Invoke the docker Lambda</p><p>In lambdas/new_func/main.py add the following imports to the top of the file</p><pre>import boto3<br>import os<br>import json</pre><p>Now in the handler function add:</p><pre>client = boto3.client(&#39;lambda&#39;)<br>payload = {...some data object...}<br>response = client.invoke(<br>    FunctionName=os.environ[&#39;DOCKER_LAMBDA_NAME&#39;]<br>    Payload=bytes(json.dumps(payload), &quot;utf-8&quot;)<br>)</pre><p>4. Your docker image should receive the payload as a JSON object. If you’ve followed on from Part 1 then it will be in the payload argument. See below for a simple example:</p><pre># This is in DockerImage &gt; main.py <br># See Part 1 for setup process</pre><pre>def handler(payload):<br>    ...do some really cool code...</pre><pre>    return { &quot;success&quot;: payload }</pre><h4>Handling the response</h4><p>Docker Images don’t respond in a very nice format. It can be super painful to get the response correctly and there’s a few pitfalls that can eat your time.</p><p>The code below is a barebones example of how to read the response from your docker images into JSON format.</p><pre># response = client.invoke(...)</pre><pre>r_payload = response[&#39;Payload&#39;]<br>read_payload = r_payload.read() #! Important, see [1] below<br>decoded = str(read_payload, &#39;utf-8&#39;)<br>result = json.loads(decoded)<br>print(result)</pre><p>[1]: I sunk hours into this single line of code. Here’s why:</p><p>The response payload of a docker image (r_payload ) is of type &lt;StreamingBody&gt; . I don’t know everything about it, but what I do know is that when you .read() this value it acts similar to a file read. This means subsequent “reads” just pick up from where the previous ended.</p><p>Here’s a demonstration:</p><pre>one = r_payload.read() # Reads ALL of the encoded payload</pre><pre>two = r_payload.read() # Picks up where previous read finished, oh<br>                         wait there&#39;s no more to read :(</pre><pre>print(one) # Output = the encoded payload<br>print(two) # Output = &#39;None&#39;</pre><p>The takeaway? Only read() the encoded payload <strong>once</strong> and save it to a variable.</p><h3>Conclusion</h3><p>If you have followed both Part 1 and Part 2 (you’re here now) then you should have all the foundation blocks you need.</p><p>All the code, directory structure, lambda settings etc. come directly from my working deployments. If there are sections that you can’t get working please leave a reply and I’ll do my best to assist, especially if it’s because of a typo in these instructions.</p><p>Thanks for readin’</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=adc74a2e9d1c" width="1" height="1" alt=""><hr><p><a href="https://towardsdev.com/invoking-lambda-docker-images-with-aws-cdk-python-adc74a2e9d1c">Invoking Lambda Docker Images with AWS CDK (Python)</a> was originally published in <a href="https://towardsdev.com/">Towards Dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Provisioning Lambda Docker Images with AWS CDK (Python)]]></title>
            <link>https://levelup.gitconnected.com/provisioning-lambda-docker-images-with-aws-cdk-python-a10bffd20613?source=rss-c2f9a8700fb5------2</link>
            <guid isPermaLink="false">https://medium.com/p/a10bffd20613</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[aws-cdk]]></category>
            <category><![CDATA[serverless]]></category>
            <category><![CDATA[aws-lambda]]></category>
            <dc:creator><![CDATA[Jackson Bowe]]></dc:creator>
            <pubDate>Mon, 04 Apr 2022 04:51:54 GMT</pubDate>
            <atom:updated>2022-04-19T13:29:36.521Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/382/1*mNFm7LvWyTSlKf2j0FQNqw.png" /><figcaption>Dockerized Lambda Functions</figcaption></figure><p>This is Part 1 of a two-part post. In this part, I will cover provisioning the lambda docker image, and in the next part, I will cover interacting with it.</p><p>Covered:</p><ul><li>Declare Lambda Docker Image in CDK</li><li>Importing local modules to main docker script</li><li>Writing the Dockerfile</li><li>Reading/Writing to Docker Image filesystem</li><li>Testing locally</li></ul><h3>Prerequisites</h3><ul><li><a href="https://docs.docker.com/get-docker/">Docker</a> installed on local machine</li><li>AWS CDK installed and set up correctly</li></ul><p>Prior experience with Docker would be helpful, although I managed to figure this out and it was my first time dealing with Docker so you should be fine.</p><h4>Directory Structure</h4><pre>cdk-project<br>|-- lambdas/<br>    |-- docker_func/<br>        |-- app/<br>            |-- __init__.py<br>            |-- components/<br>                |-- __init__.py<br>                |-- com1.py<br>                |-- com2.py<br>            |-- utils/<br>                |-- __init__.py<br>                |-- ut1.py<br>            |-- main.py<br>            |-- output.json # Optional<br>        |-- Dockerfile<br>        |-- README.md<br>        |-- requirements.txt<br>|-- project/<br>   |-- project_stack.py</pre><h3>Process</h3><p>Step by step process based on the above project structure. The file names I’ll be using in these steps directly relate to the files in the above Directory Structure.</p><p>Note: Starting in the root directory of your CDK project ../#/cdk-project&gt;</p><ol><li>Declare the docker using CDK</li></ol><pre># ../project/project_stack.py</pre><pre>docker_lambda = _lambda.DockerImageFunction(self, &#39;DockerLambda&#39;,<br>code=_lambda.DockerImageCode.from_image_asset(&#39;lambdas/docker_func&#39;),<br>    timeout=Duration.seconds(30), # Default is only 3 seconds<br>    memory_size=1000, # If your docker code is pretty complex<br>    environment={<br>        &quot;BUCKET_NAME&quot;: bucket.bucket_name # Optional<br>    }<br>)</pre><p>2. In a new terminal, navigate to top-level of docker function:</p><pre>cd lambdas/docker_func</pre><p>3. Provision some basic components/utils</p><pre># app/components/com1.py</pre><pre>class Com1():<br> def __init__(self):<br>  pass</pre><pre>~~~</pre><pre># app/components/com2.py</pre><pre>class Com2():<br> def __init__(self):<br>  pass</pre><pre>~~~</pre><pre># app/utils/ut1.py</pre><pre>class Ut1():<br> def __init__(self):<br>  pass</pre><p>4. Set components and utils to be treated as modules by adding __init__.py to each folder and importing the classes specified in #3.</p><pre># app/components/__init__.py<br>from components.com1 import *<br>from componented.com2 import *</pre><pre>~~~</pre><pre># app/utils/__init__.py<br>from utils.ut1 import *</pre><p>Warning: If you skip this step you will not be able to import these modules in the way that you think. When docker packages up your files it moves them all around which breaks relative imports (even though it may work locally)</p><p>5. Write the Dockerfile .</p><pre>FROM public.ecr.aws/lambda/python:3.8</pre><pre># Copy function code<br>COPY app/main.py ${LAMBDA_TASK_ROOT}</pre><pre># Add local dependencies<br>ADD app/components components<br>ADD app/utils utils<br>ADD app/template.docx template.docx<br># Install the function&#39;s dependencies using file requirements.txt<br># from your project folder.</pre><pre>COPY requirements.txt  .<br>RUN  pip3 install -r requirements.txt --target &quot;${LAMBDA_TASK_ROOT}&quot;</pre><pre># Set the CMD to your handler (could also be done as a parameter override outside of the Dockerfile)<br>CMD [ &quot;main.handler&quot; ]</pre><p>In the <em>Add local dependencies</em> section of the Dockerfile there’s some important details.<br>These ADD commands tell docker that when it is packaging up your files it needs to grab the contents of source and place it in target when done.</p><p>eg. ADD source target &gt; ADD app/components components</p><p>This means that once our app is built, we can access the files inside components via</p><pre>from components.com1 import Com1</pre><p>The last line CMD [&quot;main.handler&quot;] sets the docker entry point to the function handler in main.py:</p><pre># main.py</pre><pre>def handler(event, context):<br> pass</pre><p>If you don’t want to call your file main.py then just change all instances where I use it to your preferred name.</p><p>6. Deploy your changes. It should take a while to upload initially. I mean a long while. Like 7–10 minutes.</p><h3>Writing to the Docker filesystem</h3><p>If you try to write a file you will get:</p><pre>[ERROR] OSError: [Errno 30] Read-only file ststel: &#39;/path&#39;</pre><p>This is because the only writable directory with any AWS Lambda function is the /tmp folder.</p><p>If you need to write a document, do it like below:</p><pre>document.save(&#39;/tmp/report.docx&#39;) # example using python-docx</pre><h3>Testing locally</h3><p>Uploading the docker image every time you make a change is possibly the fastest way to transform your brain from goo to soup. Don’t do that. Do this instead.</p><p>Say you’ve got a Docker Image that uses the python-docx library (not important, it’s just a good example). Your script loads a template.docx file and saves the resulting output.docx file.</p><p>To test locally we use python’s if __name__ == &quot;__main__&quot;: magic to provide dummy data to our handler function. This method will <strong><em>ONLY </em></strong>run when we manually run the script.</p><pre># main.py</pre><pre>def handler(payload, context, prefix=&#39;/tmp/&#39;):<br>   # ... code<br>   document.save(prefix+&quot;output.json&quot;)<br>   # ... more code<br> <br>   return<br> <br>if __name__ == &quot;__main__&quot;:<br>    with open(&quot;input.json&quot;) as f: # input.json sample event input<br>        handler(json.load(f), None, prefix=&#39;&#39;)</pre><p>Note in the above code I’m using a prefix argument to my handler() function. This is to control where the output file is written. For my local testing, I don’t want the file to be written to the /tmp directory because that will be a reserved folder once I deploy.</p><p>To run the file locally you will need to be in the app folder (referencing the directory structure from the start).</p><pre>C:\&lt;path&gt;\cdk-project\lambdas\docker_func\app&gt; python main.py</pre><p>That should pretty much cover it. The above steps are all I needed to do to get my lambda working. For reference what it does is:</p><ol><li>One lambda function preps a json object and sends it to the Docker Image.</li><li>Docker Image parses the json data, imports 3rd party libraries, reads and populates template documents, saves the output to docker filesystem, uploads the result to S3, and finally returns the S3 object URI to the Lambda that invoked it.</li></ol><p>Hopefully this is helpful to anyone who reads. Thanks.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a10bffd20613" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/provisioning-lambda-docker-images-with-aws-cdk-python-a10bffd20613">Provisioning Lambda Docker Images with AWS CDK (Python)</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>