<?xml version="1.0" encoding="utf-8"?><feed xmlns="http://www.w3.org/2005/Atom" ><generator uri="https://jekyllrb.com/" version="3.9.5">Jekyll</generator><link href="https://io.twigfarm.net/feed.xml" rel="self" type="application/atom+xml" /><link href="https://io.twigfarm.net/" rel="alternate" type="text/html" /><updated>2024-04-09T04:48:07+00:00</updated><id>https://io.twigfarm.net/feed.xml</id><title type="html">Twigfarm Tech Blog</title><subtitle>In this blog, we share our technical findings about web development such as AWS, backend, frontend, devOps, etc.</subtitle><entry><title type="html">How to Connect AWS Lambdas within VPC to Datadog</title><link href="https://io.twigfarm.net/aws/vpc-lambda-for-datadog/" rel="alternate" type="text/html" title="How to Connect AWS Lambdas within VPC to Datadog" /><published>2024-04-08T00:00:00+00:00</published><updated>2024-04-08T00:00:00+00:00</updated><id>https://io.twigfarm.net/aws/vpc-lambda-for-datadog</id><content type="html" xml:base="https://io.twigfarm.net/aws/vpc-lambda-for-datadog/"><![CDATA[<p>Published on April 8, 2024</p>

<p><strong>By Hyuntaek Park</strong></p>

<p><em>Senior software engineer at Twigfarm</em></p>

<p>Recently, as part of a Proof of Concept (PoC) at Twigfarm, we have been adapting Datadog to efficiently identify bugs and issues. Our backend is primarily serverless, incorporating elements such as API Gateway, S3, MongoDB Atlas, and numerous Lambda functions spread across different AWS accounts.</p>

<p>While integrating these serverless components with Datadog proved feasible, we encountered difficulties in tracking logs for certain Lambda functions on the Datadog console. Upon investigation, we discovered that the Lambda functions within the VPC were not connecting.</p>

<p>As you might know already, lambda functions inside VPC cannot connect to the internet without additional settings such as NAT gateway or NAT instance.</p>

<p>We addressed this problem using VPC Peering.</p>

<p>Since we had to deal with several Datadog private links, we had some repetitive jobs and they were easy to make mistakes. Be careful.</p>

<h2 id="prerequisites">Prerequisites</h2>

<p>For simplicity, consider the setup as follows:</p>

<ul>
  <li>A Lambda function resides in the ap-northeast-2 region, within a VPC.</li>
  <li>Datadog has been configured on datadoghq.com.</li>
  <li>Another VPC is established in the us-east-1 region, ensuring its IP range does not overlap with the VPC in the ap-northeast-2 region.</li>
  <li>VPC IP CIDR for ap-northeast-2 is 172.28.0.0/16</li>
  <li>VPC IP CIDR for us-east-1 is 172.10.0.0/16</li>
</ul>

<h2 id="security-group">Security Group</h2>

<p>Create a security group within the us-east-1 VPC that permits traffic from the 172.28.0.0/16, (IP range of ap-northeast-2 VPC) network on port 443.</p>

<p><img src="https://s3.ap-northeast-2.amazonaws.com/io.twigfarm.net/image-4.png" alt="alt text" /></p>

<h2 id="vpc-endpoints">VPC Endpoints</h2>

<p>The table below lists the PrivateLink service names. Not all endpoints need to be created; I have selected 7 that I intend to use.</p>

<p><img src="https://s3.ap-northeast-2.amazonaws.com/io.twigfarm.net/image-1.png" alt="Datadog PrivateLink service name and DNS name" /></p>

<ul>
  <li>Select N.Virginia (us-east-1) region in AWS console</li>
  <li>Go to <strong><em>VPC</em></strong></li>
  <li>Select <strong><em>Endpoints</em></strong></li>
  <li>Click <strong><em>Create endpoint</em></strong></li>
  <li>Input as the following. Make sure input name tag. I used private DN name for the name.</li>
</ul>

<p><img src="https://s3.ap-northeast-2.amazonaws.com/io.twigfarm.net/image-3.png" alt="alt text" /></p>

<ul>
  <li>After you click <strong><em>Verify service</em></strong> button, you get to choose VPC, Subnets, and Security groups.</li>
  <li>Click <strong><em>Create endpoint</em></strong></li>
</ul>

<p><img src="https://s3.ap-northeast-2.amazonaws.com/io.twigfarm.net/image-5.png" alt="al text" /></p>

<p>Repeat the same process for all the private link services that you want to connect. Here are the results:</p>

<p><img src="https://s3.ap-northeast-2.amazonaws.com/io.twigfarm.net/image-2.png" alt="Results after creation of EndPoints" /></p>

<h2 id="amazon-route-53-hosted-zones">Amazon Route 53 Hosted Zones</h2>

<ul>
  <li>Go to Route 53</li>
  <li>Click <strong><em>Create hosted zone</em></strong></li>
  <li>Fill in Domain name</li>
  <li>Choose Private h osted zone</li>
  <li>Choose Region as US East (N. Virginia)</li>
  <li>Choose your VPC that you created for Datadog integration</li>
  <li>Press Create hosted zone</li>
</ul>

<p><img src="https://s3.ap-northeast-2.amazonaws.com/io.twigfarm.net/image-6.png" alt="create route 53 hosted zone" /></p>

<p>Repeat the same process for all of the private link services that you want to connect. Here are the results:</p>

<p><img src="https://s3.ap-northeast-2.amazonaws.com/io.twigfarm.net/image-7.png" alt="hosted zones" /></p>

<h2 id="amazon-route-53-a-record">Amazon Route 53 A Record</h2>

<p>Now we need create an <strong><em>A record</em></strong> for each of the private hosted zones we just created.</p>

<ul>
  <li>Choose one of the hosted zones. e.g.) agent-http-intake.logs.datadoghq.com</li>
  <li>Press Create record</li>
  <li>Leave the record name part empty</li>
  <li>Choose A - Routes traffic to an IPv4 address and some AWS resources for Record type</li>
  <li>Turn on Alias</li>
  <li>Route traffic to Alias to VPC endpoint and US East (N. Virginia)</li>
  <li>Carefully choose the VPC endpoint name for the record</li>
  <li>Press Create records</li>
</ul>

<p><img src="https://s3.ap-northeast-2.amazonaws.com/io.twigfarm.net/image-8.png" alt="a record" /></p>

<p>Again, repeat this for all of the private link services</p>

<h2 id="edit-amazon-route-53-hosted-zone">Edit Amazon Route 53 Hosted Zone</h2>

<p>We need to associate VPCs which reside in both us-east-1 and ap-northeast-2.</p>

<ul>
  <li>Choose one of the hosted zones. e.g.) agent-http-intake.logs.datadoghq.com</li>
  <li>Press Edit hosted zone</li>
  <li>Make sure add regions and the appropriate VPC IDs</li>
  <li>Press Save changes button</li>
</ul>

<p><img src="https://s3.ap-northeast-2.amazonaws.com/io.twigfarm.net/image-9.png" alt="alt text" /></p>

<p>Again, repeat this for all of the hosted zones. Then we are done with the Route 53 setup.</p>

<h2 id="create-peering-connection">Create Peering Connection</h2>

<p>A VPC peering connection consists of <strong><em>requester</em></strong> and <strong><em>acceptor</em></strong>. In our case we create a requester first in ap-northeast-2 region and acceptor in us-east-1.</p>

<ul>
  <li>Go to VPC in us-east-1 region</li>
  <li>Select and copy VPC ID</li>
  <li>Change the region to ap-northeast-2</li>
  <li>Go to Peering connections</li>
  <li>Press Create peering connection button</li>
  <li>Fill in two VPC information in ap-northeast-2 and us-east-1</li>
</ul>

<p><img src="https://s3.ap-northeast-2.amazonaws.com/io.twigfarm.net/image-10.png" alt="alt text" /></p>

<p>Now the request has been made. Time to accept the request.</p>

<ul>
  <li>Change the region back to us-east-1</li>
  <li>Make sure you are in VPC -&gt; Peering connections</li>
  <li>Choose the peering connection that you just created in ap-northeast-2 region</li>
  <li>Press Action button and choose Accept request</li>
  <li>Soon the status will be changed to <strong><em>Active</em></strong>.</li>
</ul>

<p><img src="https://s3.ap-northeast-2.amazonaws.com/io.twigfarm.net/image-11.png" alt="Status is Active now" /></p>

<h2 id="update-route-tables">Update Route Tables</h2>

<p>We need to update Route tables for VPCs in both regions. Since we are in us-east-1 region, let’s do this region first.</p>

<ul>
  <li>Go to VPC -&gt; Route tables</li>
  <li>Choose the route table for the Datadog VPC</li>
  <li>Press Edit routes and press Add route button</li>
  <li>Add IP address of ap-northeast-2 region as the destination. In our case, it is 172.28.0.0/16</li>
  <li>Choose Peering Connection for the target and select the peering connection ID</li>
  <li>Then press Save changes button</li>
</ul>

<p><img src="https://s3.ap-northeast-2.amazonaws.com/io.twigfarm.net/image-12.png" alt="Route tables for acceptor" /></p>

<p>Updating route table in ap-northeast-2 region is the last step. Repeat the same but choose the destination appropriately.</p>

<ul>
  <li>Switch back the the ap-northeast-2 region</li>
  <li>Go to VPC -&gt; Route tables</li>
  <li>Choose the route table for the Datadog VPC</li>
  <li>Press Edit routes and press Add route button</li>
  <li>Add IP address of ap-northeast-2 region as the destination. In our case, it is 172.10.0.0/16</li>
  <li>Choose Peering Connection for the target and select the peering connection ID</li>
  <li>Then press Save changes button</li>
</ul>

<h2 id="testing">Testing</h2>

<p>If you’ve completed the steps so far, the peering connection should now be established. Next, navigate to the Datadog console to verify whether the logs from the Lambda function are visible in a few minutes. However, if your peering connection is not established correctly, you need to check the connection.</p>

<p>The following commands would be useful for you to test the peering connection. Run the commands from EC2 instances in both us-east-1 and ap-northeast-2 regions.</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>dig +short http-intake.logs.datadoghq.com
nc w1 -vz http-intake.logs.datadoghq.com 443
</code></pre></div></div>

<h2 id="references">References</h2>

<ul>
  <li><a href="[https://docs.datadoghq.com/agent/guide/private-link/?tab=connectfromanotherregionusingvpcpeering&amp;site=us]">https://docs.datadoghq.com/agent/guide/private-link/?tab=connectfromanotherregionusingvpcpeering&amp;site=us</a></li>
  <li><a href="https://docs.aws.amazon.com/vpc/latest/peering/what-is-vpc-peering.html">https://docs.aws.amazon.com/vpc/latest/peering/what-is-vpc-peering.html</a></li>
  <li><a href="https://docs.aws.amazon.com/vpc/latest/peering/create-vpc-peering-connection.html#same-account-different-region">https://docs.aws.amazon.com/vpc/latest/peering/create-vpc-peering-connection.html#same-account-different-region</a></li>
</ul>]]></content><author><name></name></author><category term="[&quot;AWS&quot;]" /><category term="AWS" /><category term="Datadog" /><category term="VPC" /><category term="Peer Connection" /><summary type="html"><![CDATA[This article explains how we addressed the issue of AWS Lambda functions within a VPC not connecting to Datadog.]]></summary></entry><entry><title type="html">Integrating Label Studio Data: A Step-by-Step Guide Using Jet Admin</title><link href="https://io.twigfarm.net/aws/labelstudio-jetadmin/" rel="alternate" type="text/html" title="Integrating Label Studio Data: A Step-by-Step Guide Using Jet Admin" /><published>2023-03-13T00:00:00+00:00</published><updated>2023-03-13T00:00:00+00:00</updated><id>https://io.twigfarm.net/aws/labelstudio-jetadmin</id><content type="html" xml:base="https://io.twigfarm.net/aws/labelstudio-jetadmin/"><![CDATA[<p>Published on March 13, 2023</p>

<p><strong>By Hyuntaek Park</strong></p>

<p><em>Senior full-stack engineer at Twigfarm</em></p>

<p>At Twigfarm, we use Label Studio extensively for data labeling, such as image classifications, object detection, and text labeling from images. One of the pain points we faced was that there were many tedious tasks just to view who did which tasks in projects.</p>

<p>Label Studio uses Postgres as its database, and integrating it into Jet Admin is quite simple.</p>

<h2 id="requirements">Requirements</h2>

<p>We needed an admin tool to achieve the above goals, but all of our developers are busy building other products. We wanted to minimize our efforts to build a tool that could show the list with the following columns:</p>

<ul>
  <li>Project ID</li>
  <li>Title</li>
  <li>Description</li>
  <li>Done tasks</li>
  <li>Total tasks</li>
  <li>Names of contributors</li>
</ul>

<p>Pagination of the list and filtering features is also essesntial requirements.</p>

<h2 id="create-project">Create Project</h2>

<p>Assume that you have an account at jetadmin.io. Go to <a href="https://app.jetadmin.io">https://app.jetadmin.io</a> and choose <strong><em>New App</em></strong>.</p>

<p><img width="934" alt="image" src="https://user-images.githubusercontent.com/69557497/224837403-e32274a0-30b8-411c-ac0f-5861b926aa44.png" /></p>

<p>Choose whatever you want for “WHAT ARE YOU LOOKING TO BUILD” and there might be another questions. You can fill them out or choose <strong><em>Skip</em></strong>.</p>

<h2 id="choose-resource">Choose Resource</h2>

<p>The next part is important. Since Label Studio uses PostgreSQL, choose “PostgreSQL,” as shown in the following screenshot.</p>

<p><img width="1101" alt="image" src="https://user-images.githubusercontent.com/69557497/224838714-e88a10c8-1dea-410e-9a90-36d51089f84e.png" /></p>

<h2 id="establish-database-connection">Establish database connection</h2>

<p>Enter your database connection information then click on the <strong><em>Test Connection</em></strong> to check if the connection is successfully established. Make sure your PostgreSQL is accessible from the Jet Admin IP shown on the screen. If the connection is successful, click <strong><em>Add resource</em></strong> button.</p>

<p><img width="700" alt="image" src="https://user-images.githubusercontent.com/69557497/224839573-6822ba8b-0e5e-47c0-8363-6fda89c95aaa.png" /></p>

<h2 id="prepare-your-data-using-sql">Prepare your data using SQL</h2>

<p>Choose <strong><em>Blank</em></strong> layout. Then, hover over the database icon and choose <strong><em>PostgreSQL</em></strong></p>

<p><img width="1275" alt="image" src="https://user-images.githubusercontent.com/69557497/224841126-e0025c0f-b44e-4a31-8cae-5178371fa6c8.png" /></p>

<p>Choose <strong><em>Create with SQL query</em></strong> and name it whatever you want. I will just name it “Projects with number of done tasks”. Click <strong><em>Create</em></strong> button.</p>

<p>I have the following SQL query. Some optimizations can be done, but itfulfills the requirements for now.</p>

<div class="language-sql highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">SELECT</span> <span class="n">project</span><span class="p">.</span><span class="n">id</span><span class="p">,</span> <span class="n">project</span><span class="p">.</span><span class="n">title</span> <span class="k">AS</span> <span class="n">title</span><span class="p">,</span> <span class="n">project</span><span class="p">.</span><span class="n">description</span><span class="p">,</span> <span class="k">SUM</span><span class="p">(</span><span class="k">CASE</span> <span class="k">WHEN</span> <span class="n">task</span><span class="p">.</span><span class="n">is_labeled</span> <span class="k">THEN</span> <span class="mi">1</span> <span class="k">ELSE</span> <span class="mi">0</span> <span class="k">END</span><span class="p">)</span> <span class="k">AS</span> <span class="n">done_tasks</span><span class="p">,</span> <span class="k">COUNT</span><span class="p">(</span><span class="n">task</span><span class="p">.</span><span class="n">id</span><span class="p">)</span> <span class="k">AS</span> <span class="n">total_tasks</span><span class="p">,</span>
    <span class="n">string_agg</span><span class="p">(</span><span class="k">DISTINCT</span> <span class="k">CASE</span> <span class="k">WHEN</span> <span class="n">htx_user</span><span class="p">.</span><span class="n">id</span> <span class="o">&gt;</span> <span class="mi">0</span> <span class="k">THEN</span> <span class="n">CONCAT</span><span class="p">(</span><span class="n">htx_user</span><span class="p">.</span><span class="n">first_name</span><span class="p">,</span> <span class="s1">'('</span><span class="p">,</span>  <span class="n">user_task_counter</span><span class="p">.</span><span class="n">total_completed</span><span class="p">,</span> <span class="s1">')'</span><span class="p">)</span> <span class="k">ELSE</span> <span class="k">NULL</span> <span class="k">END</span><span class="p">,</span> <span class="s1">', '</span><span class="p">)</span> <span class="k">AS</span> <span class="n">completed_by_list</span>
<span class="k">FROM</span> <span class="n">project</span>
<span class="k">INNER</span> <span class="k">JOIN</span> <span class="n">task</span> <span class="k">ON</span> <span class="n">task</span><span class="p">.</span><span class="n">project_id</span> <span class="o">=</span> <span class="n">project</span><span class="p">.</span><span class="n">id</span>
<span class="k">LEFT</span> <span class="k">JOIN</span> <span class="n">task_completion</span> <span class="k">ON</span> <span class="n">task_completion</span><span class="p">.</span><span class="n">task_id</span> <span class="o">=</span> <span class="n">task</span><span class="p">.</span><span class="n">id</span>
<span class="k">LEFT</span> <span class="k">JOIN</span> <span class="n">htx_user</span> <span class="k">ON</span> <span class="n">htx_user</span><span class="p">.</span><span class="n">id</span> <span class="o">=</span> <span class="n">task_completion</span><span class="p">.</span><span class="n">completed_by_id</span>
<span class="k">LEFT</span> <span class="k">JOIN</span> <span class="p">(</span>
    <span class="k">SELECT</span> <span class="k">DISTINCT</span><span class="p">(</span><span class="n">completed_by_id</span><span class="p">),</span> <span class="k">COUNT</span><span class="p">(</span><span class="n">task</span><span class="p">.</span><span class="n">id</span><span class="p">)</span> <span class="k">as</span> <span class="n">total_completed</span><span class="p">,</span> <span class="n">task</span><span class="p">.</span><span class="n">project_id</span>
    <span class="k">FROM</span> <span class="n">task</span><span class="p">,</span> <span class="n">task_completion</span>
    <span class="k">WHERE</span> <span class="n">task_completion</span><span class="p">.</span><span class="n">task_id</span> <span class="o">=</span> <span class="n">task</span><span class="p">.</span><span class="n">id</span>
    <span class="k">GROUP</span> <span class="k">BY</span> <span class="n">completed_by_id</span><span class="p">,</span> <span class="n">project_id</span>
<span class="p">)</span> <span class="n">user_task_counter</span> <span class="k">ON</span> <span class="p">(</span><span class="n">task</span><span class="p">.</span><span class="n">project_id</span> <span class="o">=</span> <span class="n">user_task_counter</span><span class="p">.</span><span class="n">project_id</span> <span class="k">AND</span> <span class="n">htx_user</span><span class="p">.</span><span class="n">id</span> <span class="o">=</span> <span class="n">user_task_counter</span><span class="p">.</span><span class="n">completed_by_id</span><span class="p">)</span>
<span class="k">GROUP</span> <span class="k">BY</span> <span class="n">project</span><span class="p">.</span><span class="n">id</span>
<span class="k">ORDER</span> <span class="k">BY</span> <span class="n">id</span> <span class="k">DESC</span>
</code></pre></div></div>

<p>Press the <strong><em>Play symbol</em></strong> to run the query. Validate if this is the data you would like to see.</p>

<p>I get results like the following. Note that I hid columns with sensitive information.</p>

<p><img width="878" alt="image" src="https://user-images.githubusercontent.com/69557497/224848662-4638cd36-a4ce-4962-8d1c-ad920b60eed5.png" /></p>

<p>If you are satisfied with the result, then press <strong><em>Save</em></strong> button, or play more with the SQL query until you get the result that you desire.</p>

<h2 id="page-layouts">Page layouts</h2>

<p>Now the recipe is prepared. It is time to configure the list screen with a search feature.</p>

<h3 id="list">List</h3>

<p><img width="1064" alt="image" src="https://user-images.githubusercontent.com/69557497/224849594-c7ad0763-b740-4062-b959-ade8a342dcca.png" /></p>

<p>Choose <strong><em>Blank</em></strong> and click <strong><em>Continue</em></strong> button.</p>

<p>Drag and drop <strong><em>Container</em></strong> and then a <strong><em>Table</em></strong> component from the right-hand side of the screen to the center of the screen. Choose data sources as the following:</p>

<p><img width="1293" alt="image" src="https://user-images.githubusercontent.com/69557497/224850161-595f3d8e-f779-4286-a4f9-0000827a10a2.png" /></p>

<p>Now the list is ready.</p>

<h3 id="search-box">Search Box</h3>

<p>Let’s add a search box. Drag and drop <strong><em>Filter</em></strong> from the Lists section on the right-hand side of the screen.</p>

<p><img width="415" alt="image" src="https://user-images.githubusercontent.com/69557497/224856712-d6af5916-85d6-4f88-9197-cde2272a86eb.png" /></p>

<p>Click <strong><em>Bind to Component</em></strong> button, then select <strong><em>Projects with number of done tasks</em></strong> or whatever you named the data source.</p>

<p><img width="1231" alt="image" src="https://user-images.githubusercontent.com/69557497/224856879-61048f15-50f3-4eb1-9f2d-98700621a352.png" /></p>

<p>Choose <strong><em>+ Add a Filter</em></strong>. I want my filter to be used to display a list containing the substring of the title that the user entered. So it looks like the following screenshot.</p>

<p><img width="1229" alt="image" src="https://user-images.githubusercontent.com/69557497/224857238-fc7f62ca-fd9a-4f29-8a03-35c67ceecdb0.png" /></p>

<h2 id="preview-and-publish">Preview and publish</h2>

<p>Let us press the <strong><em>Preview</em></strong> button on the header. If you like it, click the <strong><em>Publish</em></strong> button.</p>

<p>There might be a few things that you might want to change to make it more intuitive and fancy. It is your time to navigate the rest of Jet Admin and refine as much as you want. Then publish your work.</p>

<p>You might also want to modify the SQL query to fulfill your own requirements. I hope this tutorial about Jet Admin saves your time building the admin page.</p>]]></content><author><name></name></author><category term="[&quot;AWS&quot;]" /><category term="AWS" /><category term="Jet Admin" /><category term="Postgres" /><category term="Label Studio" /><summary type="html"><![CDATA[The article provides a step-by-step guide for integrating Label Studio data using Jet Admin, a PostgreSQL-based admin tool.]]></summary></entry><entry><title type="html">Securely Connecting Lambda to MongoDB Atlas through VPC Peering</title><link href="https://io.twigfarm.net/aws/vpc-peerconnection/" rel="alternate" type="text/html" title="Securely Connecting Lambda to MongoDB Atlas through VPC Peering" /><published>2022-12-10T00:00:00+00:00</published><updated>2022-12-10T00:00:00+00:00</updated><id>https://io.twigfarm.net/aws/vpc-peerconnection</id><content type="html" xml:base="https://io.twigfarm.net/aws/vpc-peerconnection/"><![CDATA[<p>Published on December 10, 2022</p>

<p><strong>By Hyuntaek Park</strong></p>

<p><em>Senior full-stack engineer at Twigfarm</em></p>

<p>MongoDB Atlas has several network security options. One of them is traditional IP whitelisting, which is very convenient when your business logic, which needs access to the MongoDB Atlas, has a static IP address. Or you can set 0.0.0.0/0 to access to the database, which opens your database to the public. It is very dangerous and you should avoid it.</p>

<p>At Twigfarm, we use AWS lambda very often. We had cases where our lambdas needs access to the MongoDB Atlas database. As you might already know, unlike AWS EC2, you cannot set a static IP address for AWS lambda easily. It is possible using an AWS NAT Gateway but requires a bit of work, which is out of scope in this article. I will cover that topic later if I have a chance.</p>

<h2 id="prerequisites">Prerequisites</h2>

<ul>
  <li>A database is setup on MongoDB Atlas</li>
  <li>Have your MongoDB Atlas connection string ready</li>
</ul>

<h2 id="create-a-lambda-function">Create a lambda function</h2>

<p>Let’s create a lambda function that is trying to access to the MongoDB Atlas database. Obviously, it is not going to work and gets timeout because the MongoDB Atlas database does not allow this connection yet.</p>

<p>Lambda code is as the following; the code snippet is copied from <a href="https://www.mongodb.com/docs/drivers/node/current/fundamentals/connection/connect/#std-label-node-connect-to-mongodb">here</a> and modified.</p>

<p>You need MongoDB Nods.js Driver to run the following code. Please refer to the following link: <a href="https://www.npmjs.com/package/mongodb">https://www.npmjs.com/package/mongodb</a></p>

<p>To use the third-party library in a lambda, I prefer to have the libraries in a layer. You can refer to the following link for layers in lambda functions. <a href="https://docs.aws.amazon.com/lambda/latest/dg/configuration-layers.html">https://docs.aws.amazon.com/lambda/latest/dg/configuration-layers.html</a></p>

<div class="language-js highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">const</span> <span class="p">{</span> <span class="nx">MongoClient</span> <span class="p">}</span> <span class="o">=</span> <span class="nx">require</span><span class="p">(</span><span class="dl">"</span><span class="s2">mongodb</span><span class="dl">"</span><span class="p">);</span>

<span class="c1">// Connection URI</span>
<span class="kd">const</span> <span class="nx">uri</span> <span class="o">=</span> <span class="nx">process</span><span class="p">.</span><span class="nx">env</span><span class="p">.</span><span class="nx">MONGODB_URI</span><span class="p">;</span>

<span class="c1">// Create a new MongoClient</span>
<span class="kd">const</span> <span class="nx">client</span> <span class="o">=</span> <span class="k">new</span> <span class="nx">MongoClient</span><span class="p">(</span><span class="nx">uri</span><span class="p">,</span> <span class="p">{</span>
  <span class="na">useUnifiedTopology</span><span class="p">:</span> <span class="kc">true</span><span class="p">,</span>
<span class="p">});</span>

<span class="nx">exports</span><span class="p">.</span><span class="nx">handler</span> <span class="o">=</span> <span class="k">async</span> <span class="p">(</span><span class="nx">event</span><span class="p">)</span> <span class="o">=&gt;</span> <span class="p">{</span>
  <span class="k">try</span> <span class="p">{</span>
    <span class="c1">// Connect the client to the server (optional starting in v4.7)</span>
    <span class="k">await</span> <span class="nx">client</span><span class="p">.</span><span class="nx">connect</span><span class="p">();</span>
    <span class="c1">// Establish and verify connection</span>
    <span class="k">await</span> <span class="nx">client</span><span class="p">.</span><span class="nx">db</span><span class="p">(</span><span class="nx">YOUR_DB_NAME</span><span class="p">).</span><span class="nx">command</span><span class="p">({</span> <span class="na">ping</span><span class="p">:</span> <span class="mi">1</span> <span class="p">});</span>
    <span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="dl">"</span><span class="s2">Connected successfully to server</span><span class="dl">"</span><span class="p">);</span>
  <span class="p">}</span> <span class="k">finally</span> <span class="p">{</span>
    <span class="c1">// Ensures that the client will close when you finish/error</span>
    <span class="k">await</span> <span class="nx">client</span><span class="p">.</span><span class="nx">close</span><span class="p">();</span>
  <span class="p">}</span>
<span class="p">};</span>
</code></pre></div></div>

<p>Then we set the MONGODB_URI to your MongoDB Atlas connection string.
<img width="873" alt="image" src="https://user-images.githubusercontent.com/69557497/206849397-41c55fed-3ca4-4c96-a813-d627a213ece6.png" /></p>

<p>Then you click the <strong><em>Test</em></strong> button to run the lambda function. If you haven’t created a test case before, just leave everything as it is and name the test case and save it. Then click the <strong><em>Test</em></strong> button again.</p>

<p>You should get a timeout response such as the following because your lambda is not whitelisted in the MongoDB Atlas database.</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>Response
{
  "errorMessage": "2022-12-10T10:16:28.767Z 8bd39e1c-f688-409c-93f1-eaa13c6b46a6 Task timed out after 3.01 seconds"
}

</code></pre></div></div>

<h2 id="create-a-vpc">Create a VPC</h2>

<p>Go to <strong><em>AWS VPC</em></strong>. Then click <strong><em>Create VPC</em></strong> button.
<img width="2020" alt="image" src="https://user-images.githubusercontent.com/69557497/206832451-519e7102-83b5-4781-957b-f766e7e10260.png" /></p>

<p>Here I have a couple of public subnets and no private subnets for simplicity.</p>

<p><img width="1004" alt="image" src="https://user-images.githubusercontent.com/69557497/206850543-5aac6daa-53b3-4f36-8f62-3597ca8a6c4d.png" /></p>

<p>These are the result of the VPC creation and highlighted are strings to be used at the MongoDB Atlas</p>

<h2 id="create-a-vpc-peering-at-mongodb-atlas">Create a VPC peering at MongoDB Atlas</h2>

<p>Log in to MongoDB Atlas and choose your project to connect to the lambda function. Click <strong><em>Network Access</em></strong> and select <strong><em>Peering</em></strong> tab. I have a few VPC peering connections already but, likely, that you don’t have any. Click <strong><em>ADD PEERING CONNECTION</em></strong> button to create a new connection.</p>

<p><img width="1261" alt="image" src="https://user-images.githubusercontent.com/69557497/206850841-71cd0350-89e1-49b3-bdc7-66f2e936b962.png" /></p>

<p>Choose <strong><em>AWS</em></strong>. Click <strong><em>Next</em></strong>.</p>

<p>Fill in the Account ID, VPC ID, and VPC CIDR with the above VPC information. Then click <strong><em>Initiate Peering</em></strong>.
<img width="1287" alt="image" src="https://user-images.githubusercontent.com/69557497/206855634-7c981265-7ace-48cd-9dac-437506de680e.png" /></p>

<h2 id="accept-peering-connection-requests-in-aws">Accept peering connection requests in AWS</h2>

<p>Now go back to the <strong><em>AWS VPC</em></strong> and choose Peering connections. Choose the peering connection and then <strong><em>Actions</em></strong> and choose <strong><em>Accept request</em></strong>.</p>

<p><img width="1400" alt="image" src="https://user-images.githubusercontent.com/69557497/206855905-580bcec5-0370-4fff-8954-f77c23b90e2f.png" /></p>

<p>You’ll see the Status is changed to <strong><em>Active</em></strong>.</p>

<h2 id="setting-up-the-route-table">Setting up the route table</h2>

<p>This is is the last step of the VPC Peering. Go to the <strong><em>AWS VPC</em></strong> then choose the <strong><em>Route tables</em></strong>. Choose the route table for the VPC and click <strong><em>Edit routes</em></strong> then <strong><em>Add route</em></strong>.</p>

<p>Add the VPC CIDR value we obtained from the MongoDB Atlas Peering Connection. In my case, it is <strong><em>192.168.248.0/21</em></strong> for the <strong><em>Destination</em></strong> field. Choose the <strong><em>Peering Connection</em></strong> and the Peering connection ID for the <strong><em>Target</em></strong> field.</p>

<p><img width="1242" alt="image" src="https://user-images.githubusercontent.com/69557497/206856399-05261b54-9f5b-4860-b55a-980f68850cfb.png" /></p>

<h2 id="configure-lambdas-vpc">Configure lambda’s VPC</h2>

<p>Now the connection is made. Let’s go back to the lambda and do the VPC configurations.</p>

<p>Go back to the lambda we created and choose <strong><em>Configuration</em></strong> and <strong><em>VPC</em></strong>. Then click <strong><em>Edit</em></strong> button.</p>

<p><img width="1196" alt="image" src="https://user-images.githubusercontent.com/69557497/206856623-c781599a-24a7-412b-ae7e-39942ae9a5d7.png" /></p>

<p>Then fill in the VPC information and click <strong><em>Save</em></strong> button.
<img width="849" alt="image" src="https://user-images.githubusercontent.com/69557497/206856850-444dc813-b191-499f-952a-aeea427766ed.png" /></p>

<h2 id="final-testing">Final testing</h2>

<p>Now the lambda and the MongoDB Atlas database are connected securely. Let’s do the same testing that we did at the beginning of this article. Now you will be able to see the “Connected successfully to server” in your log.</p>

<p>For more information about the VPC Peering Connection, you can refer to the MongoDB Atlas tutorial as well <a href="https://www.mongodb.com/docs/atlas/security-vpc-peering">https://www.mongodb.com/docs/atlas/security-vpc-peering</a>.</p>]]></content><author><name></name></author><category term="[&quot;AWS&quot;]" /><category term="AWS" /><category term="Lambda" /><category term="MongoDB Atlas" /><category term="VPC peer connection" /><summary type="html"><![CDATA[This blog post explains how to connect your MongoDB Atlas database to AWS Lambda using VPC peering]]></summary></entry><entry><title type="html">How To Mount the EFS file system on the EC2 instance</title><link href="https://io.twigfarm.net/aws/mounting-efs-on-ec2/" rel="alternate" type="text/html" title="How To Mount the EFS file system on the EC2 instance" /><published>2022-11-22T00:00:00+00:00</published><updated>2022-11-22T00:00:00+00:00</updated><id>https://io.twigfarm.net/aws/mounting-efs-on-ec2</id><content type="html" xml:base="https://io.twigfarm.net/aws/mounting-efs-on-ec2/"><![CDATA[<p>Published on November 22, 2022</p>

<p><strong>By Hyuntaek Park</strong></p>

<p><em>Senior full-stack engineer at Twigfarm</em></p>

<p>Amazon EFS (Elastic File System) is very useful when we need a limitless storage and / or to share the storage with different AWS services such as lambdas, another EC2 instances, ECSs, etc. In order to start using the EFS on our EC2, we need a little bit of a mounting process.</p>

<p>Although the process is already explained very well <a href="https://docs.aws.amazon.com/efs/latest/ug/wt1-test.html">https://docs.aws.amazon.com/efs/latest/ug/wt1-test.html</a>, let me explain in my words with a few screenshots for a better understanding.</p>

<h2 id="prerequisites">Prerequisites</h2>

<ul>
  <li>An EFS is created</li>
  <li>An EC2 instance is created</li>
</ul>

<h2 id="ssh-into-the-ec2-instance-and-run-the-mount-command">SSH into the EC2 instance and run the mount command</h2>

<p>First, ssh into the EC2 instance to run the following commands.</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$ mkdir ~/efs-mount-point
$ sudo mount -t nfs -o nfsvers=4.1,rsize=1048576,wsize=1048576,hard,timeo=600,retrans=2,noresvport EFS_DNS_NAME:/ ~/efs-mount-point
</code></pre></div></div>

<p>You can obtain the EFS_DNS_NAME here and replace it with your EFS DNS name.
<img width="1016" alt="image" src="https://user-images.githubusercontent.com/69557497/203199305-5636e293-d560-4417-9718-e052402b1709.png" /></p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$ cd ~/efs-mount-point
</code></pre></div></div>

<p>Now you can confirm the EFS is mounted. One thing that you need to keep in mind is that if you restart the EC2 instance, you will have to run the mounting command again.</p>

<p>If you need to setup your EC2 instance to automatically mount the EFS on restarts, then refer to the following link. <a href="https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/user-data.html">https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/user-data.html</a></p>

<p>Enjoy the flexible and easy to use storage, EFS.</p>

<p>Thanks!</p>]]></content><author><name></name></author><category term="[&quot;AWS&quot;]" /><category term="AWS" /><category term="EFS" /><category term="EC2" /><category term="Mount" /><summary type="html"><![CDATA[This blog post explains how to mount an EFS file system on an EC2 instance in order to utilize the limitless storage seamlessly.]]></summary></entry><entry><title type="html">How To Copy an Encrypted RDS Using Default KMS Key to Another AWS Account</title><link href="https://io.twigfarm.net/aws/copy-rds-across-accounts/" rel="alternate" type="text/html" title="How To Copy an Encrypted RDS Using Default KMS Key to Another AWS Account" /><published>2022-10-03T00:00:00+00:00</published><updated>2022-10-03T00:00:00+00:00</updated><id>https://io.twigfarm.net/aws/copy-rds-across-accounts</id><content type="html" xml:base="https://io.twigfarm.net/aws/copy-rds-across-accounts/"><![CDATA[<p>Published on October 01, 2022</p>

<p><strong>By Hyuntaek Park</strong></p>

<p><em>Senior full-stack engineer at Twigfarm</em></p>

<p>Usually, cloning a database is very easy through <strong><em>dump</em></strong> and <strong><em>restore</em></strong>. However, if you have your database in AWS RDS and if that RDS is encrypted with a default provided AWS KMS key, it is not that simple. AWS does not allow you to share the snapshot to a different account.</p>

<p>In order to overcome this problem, we need to make a few extra steps. In this article, I will demonstrate how to copy a snapshot; and finally, restore an RDS using the snapshot that is shared.</p>

<h2 id="source-database">Source Database</h2>

<p>I created a simple Postgres database in my source account as the following:</p>

<p><img width="957" alt="image" src="https://user-images.githubusercontent.com/69557497/192242368-68c2e6b6-ad55-4926-920e-8a6fda18b8c0.png" /></p>

<p>As I mentioned earlier this RDS instance is encrypted using the default AWS KMS key.</p>

<h2 id="create-a-snapshot">Create a snapshot</h2>

<p>Go to <code class="language-plaintext highlighter-rouge">RDS</code> &gt; <code class="language-plaintext highlighter-rouge">Snapshots</code>. Click the <code class="language-plaintext highlighter-rouge">Take snapshot</code> button. Choose the DB Instance and name the snapshot as you like. Then click the <code class="language-plaintext highlighter-rouge">Take snapshot</code> button</p>

<p><img width="844" alt="image" src="https://user-images.githubusercontent.com/69557497/192243087-69d8caa4-96e8-423d-93f2-1c6d4bf50635.png" /></p>

<p>You need to wait a few minutes until the creation process is finished.</p>

<h2 id="share-the-snapshot-first-try">Share the snapshot (first try)</h2>

<p>Once the snapshot creation is finished, choose the snapshot. Click the <code class="language-plaintext highlighter-rouge">Actions</code> dropdown and click <code class="language-plaintext highlighter-rouge">Share snapshot</code>.</p>

<p>This is where you specify the AWS destination account that the snapshot is to be shared.</p>

<p><img width="804" alt="image" src="https://user-images.githubusercontent.com/69557497/192245849-2a647230-55ab-41e7-a01c-3cb3ba3a7110.png" /></p>

<p>Although I entered the correct AWS account number the <code class="language-plaintext highlighter-rouge">Save</code> button is kept disabled.</p>

<p>And the error message is saying,</p>

<blockquote>
  <p>“Sharing snapshots encrypted with the default service key for RDS is currently not supported.”</p>
</blockquote>

<p>We need a different way to share the snapshot.</p>

<h2 id="create-a-kms-key-in-the-source-account">Create a KMS key in the source account</h2>

<p>Go to <code class="language-plaintext highlighter-rouge">Key Management Service (KMS)</code> in the AWS console. Then click the <code class="language-plaintext highlighter-rouge">Create a key</code> button.</p>

<p>Leave the options as they were unless you need to make a change.</p>

<p><img width="812" alt="image" src="https://user-images.githubusercontent.com/69557497/192248160-0cadc226-61ea-40a2-901f-522b3c832761.png" /></p>

<p>Click the <code class="language-plaintext highlighter-rouge">Next</code> button. Then enter <code class="language-plaintext highlighter-rouge">alias</code>. Then click <code class="language-plaintext highlighter-rouge">Next</code> again.</p>

<p><img width="815" alt="image" src="https://user-images.githubusercontent.com/69557497/192248651-e52e7391-86ca-4bc1-8bb8-db31f0a57601.png" /></p>

<p>Then choose your user name or a role if you want it that way. I chose my user name here. Click <code class="language-plaintext highlighter-rouge">Next</code>.</p>

<p><img width="779" alt="image" src="https://user-images.githubusercontent.com/69557497/192248956-2f114c4a-9567-4124-a2ee-cac90d8ffb93.png" /></p>

<p>Here, choose your user name again, then enter the destination account number. Then click <code class="language-plaintext highlighter-rouge">Next</code>.</p>

<p><img width="686" alt="image" src="https://user-images.githubusercontent.com/69557497/192249727-80d0e96d-59d3-4e4a-b421-2141734d7441.png" /></p>

<p>Check the key policy then click the <code class="language-plaintext highlighter-rouge">Finish</code> button. Now that you have your first KMS key for the snapshot in the source account.</p>

<h2 id="copy-the-snapshot">Copy the snapshot</h2>

<p>Go to <code class="language-plaintext highlighter-rouge">RDS</code> &gt; <code class="language-plaintext highlighter-rouge">Snapshots</code> &gt; choose the snapshot you created. Then click the <code class="language-plaintext highlighter-rouge">Actions</code> dropdown then choose <code class="language-plaintext highlighter-rouge">Copy snapshot</code> this time.</p>

<p><img width="944" alt="image" src="https://user-images.githubusercontent.com/69557497/192250630-8f960458-6fe0-4f45-9e4d-b7caa6928e45.png" /></p>

<p>Enter <code class="language-plaintext highlighter-rouge">New DB Snapshot Identifier</code> and ensure to choose the KMS key that you just created for the <code class="language-plaintext highlighter-rouge">AWS KMS key</code>. Then click the <code class="language-plaintext highlighter-rouge">Copy snapshot</code> button.</p>

<p><img width="672" alt="image" src="https://user-images.githubusercontent.com/69557497/192251332-b27cf389-2d8a-4ae5-be05-d2ce7eba5e25.png" /></p>

<p>Wait a few minutes again while the snapshot copy is in progress.</p>

<h2 id="share-the-snapshot-second-try">Share the snapshot (second try)</h2>

<p>When the copy of the snapshot is ready, choose the snapshot copy. Click the <code class="language-plaintext highlighter-rouge">Actions</code> dropdown button then select the <code class="language-plaintext highlighter-rouge">Share snapshot</code> button. Then add the destination AWS account ID. Basically, repeat the steps you did in <strong><em>Share the snapshot (first try)</em></strong> section.</p>

<p><img width="810" alt="image" src="https://user-images.githubusercontent.com/69557497/192253506-4b019c2f-f968-4e39-9e10-fb5da31a17b5.png" /></p>

<p>This time, the save button is enabled. Click it!</p>

<h2 id="restore-from-the-snapshot-first-try">Restore from the snapshot (first try)</h2>

<p>Log in to the destination AWS account.
Go to <code class="language-plaintext highlighter-rouge">RDS</code> &gt; <code class="language-plaintext highlighter-rouge">Snapshots</code> &gt; <code class="language-plaintext highlighter-rouge">Shared with me</code>. You should see a snapshot that we shared from the source account.</p>

<p>Our goal is to restore from this snapshot. Choose the snapshot. Click the <code class="language-plaintext highlighter-rouge">Actions</code> dropdown button.</p>

<p><img width="1284" alt="image" src="https://user-images.githubusercontent.com/69557497/192423828-2312286f-20e9-416b-86d4-47b8cf76a5ca.png" /></p>

<p>Unfortunately <code class="language-plaintext highlighter-rouge">Restore snapshot</code> button is disabled. We need to make another copy with a new destination KMS key.</p>

<h2 id="create-a-kms-key-in-the-destination-account">Create a KMS key in the destination account</h2>

<p>Go to <code class="language-plaintext highlighter-rouge">KMS</code> then click <code class="language-plaintext highlighter-rouge">Create a key</code>. Do the same as what we did in <strong><em>Create a KMS key in source account</em></strong> section except for <code class="language-plaintext highlighter-rouge">Alias</code>.</p>

<h2 id="copy-the-snapshot-again-but-in-the-destination-account">Copy the snapshot (Again but in the destination account)</h2>

<p>Now we need to make a copy of the snapshot that is shared using the key that we have just created.</p>

<p>Go to <code class="language-plaintext highlighter-rouge">RDS</code> &gt; <code class="language-plaintext highlighter-rouge">Snapshots</code> &gt; <code class="language-plaintext highlighter-rouge">Shared with me</code>. Choose the shared snapshot. Click <code class="language-plaintext highlighter-rouge">Actions</code> &gt; <code class="language-plaintext highlighter-rouge">Copy snapshot</code></p>

<p><img width="672" alt="image" src="https://user-images.githubusercontent.com/69557497/192425459-1aa68f00-796d-4c03-9575-00c38839808e.png" /></p>

<p>Be sure to Choose the newly made AWS KMS key.</p>

<h2 id="restore-from-the-snapshot-second-try">Restore from the snapshot (second try)</h2>

<p>Now choose the copied snapshot. Click <code class="language-plaintext highlighter-rouge">Actions</code> dropdown button. Now you see the <code class="language-plaintext highlighter-rouge">Restore snapshot</code> is enabled. Select <code class="language-plaintext highlighter-rouge">Restore snapshot</code>.</p>

<p>Fill in the database information. You will see your new database instance is created with the snapshot.</p>

<p>What a long way to copy(backup) and restore in a new AWS account. I hope AWS provides us with a better way to achieve this goal.</p>

<p>Thanks!</p>]]></content><author><name></name></author><category term="[&quot;AWS&quot;]" /><category term="AWS" /><category term="RDS" /><category term="Snapshot" /><category term="KMS" /><summary type="html"><![CDATA[This blog post demonstrates how to create a backup(snapshot) and restore an RDS using a snapshot created in one account to another]]></summary></entry><entry><title type="html">Cloning (Save and Restore) DynamoDB Table to Another AWS Account</title><link href="https://io.twigfarm.net/aws/clone-dynamoDB-across-accounts/" rel="alternate" type="text/html" title="Cloning (Save and Restore) DynamoDB Table to Another AWS Account" /><published>2022-09-09T00:00:00+00:00</published><updated>2022-09-09T00:00:00+00:00</updated><id>https://io.twigfarm.net/aws/clone-dynamoDB-across-accounts</id><content type="html" xml:base="https://io.twigfarm.net/aws/clone-dynamoDB-across-accounts/"><![CDATA[<p>Published on September 12, 2022</p>

<p><strong>By Hyuntaek Park</strong></p>

<p><em>Senior full-stack engineer at Twigfarm</em></p>

<p>At Twigfarm, we created a new AWS account and some of the DynamoDB tables should be copied from the old account to the new account. I thought it would be a very simple process like other database systems have a dump and restore feature. But it wasn’t that simple.</p>

<p>I tried a few different ways to achieve our goal but nothing really was simple enough. Luckily, one of the AWS Solutions Architects introduced me to a new solution that AWS just released: <a href="https://aws.amazon.com/blogs/database/amazon-dynamodb-can-now-import-amazon-s3-data-into-a-new-table/">https://aws.amazon.com/blogs/database/amazon-dynamodb-can-now-import-amazon-s3-data-into-a-new-table</a>. You should read the above article first to get a sense of how it is done.</p>

<p>In this article I will demonstrate how I save the DynamoDB table into the S3 which is in a different AWS account, then create the DynamoDB table from what is saved in S3.</p>

<h2 id="architecture">Architecture</h2>

<p>Architecture is fairly simple. In this article, I will explain how to save and restore. Some are done using console and some are done through the AWS CLI.</p>

<p><img width="812" alt="image" src="https://user-images.githubusercontent.com/69557497/189641258-a1e9b0a8-2794-4457-810e-4200d5960692.png" /></p>

<h2 id="prerequisites">Prerequisites</h2>

<p>You need to have your AWS CLI profiles for both source and destination accounts. In this article, I use <code class="language-plaintext highlighter-rouge">source-user</code> and <code class="language-plaintext highlighter-rouge">destination-user</code> for profile names. Please refer to <a href="https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-profiles.html">https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-profiles.html</a>.</p>

<h2 id="dynamodb-table">DynamoDB Table</h2>

<p>I have a simple DynamoDB table in the source account. Our final goal is to have a table with those two items in the destination account.</p>

<p><img width="835" alt="image" src="https://user-images.githubusercontent.com/69557497/189460103-96bf901a-2bd5-4c32-a5be-f5f78eef7afe.png" /></p>

<h3 id="enable-point-in-time-recovoer-pitr">Enable Point-in-time recovoer (PITR)</h3>

<p>Choose the source DynamoDB table &gt; Bakcups &gt; Edit button under Point-in-time recovery (PITR). Then enable the point-in-time-recovery feature.</p>

<h2 id="destination-s3-bucket">Destination S3 Bucket</h2>

<p>Log into the destination AWS account. It is convenient if you use a different web browser or open a new window with incognito mode.</p>

<p>Create a bucket as the following:</p>

<p>Bucket name: <code class="language-plaintext highlighter-rouge">&lt;YOUR_UNIQUE_BUCKET_NAME&gt;</code></p>

<p>Choose <code class="language-plaintext highlighter-rouge">ACL enabled</code> and <code class="language-plaintext highlighter-rouge">Object writer</code> for Object Ownership.</p>

<p><img width="840" alt="image" src="https://user-images.githubusercontent.com/69557497/189559695-f87cd0a5-fb5c-4763-8996-19ebc825206c.png" /></p>

<h3 id="s3-bucket-policy">S3 Bucket Policy</h3>

<p>Copy and paste the following JSON for your destination bucket. Ensure to replace <code class="language-plaintext highlighter-rouge">SOURCE_ACCOUNT_NO</code>, <code class="language-plaintext highlighter-rouge">SOURCE_USER_NAME</code>, and <code class="language-plaintext highlighter-rouge">DESTINATION_BUCKET_NAME</code> with your own.</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>{
    "Version": "2012-10-17",
    "Id": "",
    "Statement": [
        {
            "Sid": "",
            "Effect": "Allow",
            "Principal": {
                "AWS": "arn:aws:iam::&lt;SOURCE_ACCOUNT_NO&gt;:user/&lt;SOURCE_USER_NAME&gt;"
            },
            "Action": "s3:*",
            "Resource": [
                "arn:aws:s3:::&lt;DESTINATION_BUCKET_NAME&gt;",
                "arn:aws:s3:::&lt;DESTINATION_BUCKET_NAME&gt;/*"
            ]
        }
    ]
}
</code></pre></div></div>

<h2 id="export-table-to-amazon-s3-using-command-line-interface-cli">Export table to Amazon S3 using Command Line Interface (CLI)</h2>

<p>Enter the following command in your terminal.</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>aws dynamodb export-table-to-point-in-time \
  --profile source-user \
  --region &lt;YOUR_AWS_REGION&gt;
  --table-arn &lt;SOURCE_DYNAMODB_TABLE_ARN&gt; \
  --s3-bucket &lt;DESTINATION_BUCKET_NAME&gt; \
  --s3-bucket-owner 304884871948 \
  --s3-prefix backup-folder
</code></pre></div></div>

<p><img width="1350" alt="image" src="https://user-images.githubusercontent.com/69557497/189619032-6da71c63-5217-412a-82d1-5132d71ad287.png" /></p>

<p>If there is no error after entering the command, you would see one line under <code class="language-plaintext highlighter-rouge">Exports to S3</code>. Wait a few minutes. The status will change from <code class="language-plaintext highlighter-rouge">Exporting</code> to <code class="language-plaintext highlighter-rouge">Completed</code>. Now the exporting part is done.</p>

<h2 id="restore-from-the-s3">Restore from the S3</h2>

<p>Now you go to <code class="language-plaintext highlighter-rouge">DynamoDB</code> &gt; <code class="language-plaintext highlighter-rouge">Imports from S3</code>. Then click <code class="language-plaintext highlighter-rouge">Import from S3</code> button.</p>

<p>Click <code class="language-plaintext highlighter-rouge">Browse S3</code> button and drill down folders until you see the <code class="language-plaintext highlighter-rouge">data</code> folder and choose the file with json.gz extension.</p>

<p><img width="842" alt="image" src="https://user-images.githubusercontent.com/69557497/189636421-7e4a311f-6b1d-4264-bcdb-4ba8257f25ae.png" /></p>

<p><img width="1273" alt="image" src="https://user-images.githubusercontent.com/69557497/189636221-82f54c49-a807-4098-8377-caeb66c8023c.png" /></p>

<p>Then You fill out the form to create a new DynamoDB table.</p>

<h2 id="verification">Verification</h2>

<p>Go to DynamoDB. Check the if table items are successfully imported such as the following.</p>

<p><img width="595" alt="image" src="https://user-images.githubusercontent.com/69557497/189636732-2fd14bfb-d68b-451f-9939-a2a38d7afcfa.png" /></p>

<p>If you see the identical table contents, congratulations! <code class="language-plaintext highlighter-rouge">Imports from S3</code> feature is a new feature. Without the feature, you would have struggled with many complicated AWS services and permissions. Here with the <code class="language-plaintext highlighter-rouge">Imports from S3</code> feature, only S3 and DynamoDB are the services that we need to consider.</p>

<p>Thanks!</p>]]></content><author><name></name></author><category term="[&quot;AWS&quot;]" /><category term="AWS" /><category term="DynamoDB" /><category term="S3" /><summary type="html"><![CDATA[This blog post demonstrates how to clone that is saving and restoring DynamoDB table from one account to another]]></summary></entry><entry><title type="html">How to Host Label Studio on AWS Elastic Beanstalk with Persistent Storage and RDS PostgreSQL</title><link href="https://io.twigfarm.net/aws/labelstudio-elasticbeanstalk/" rel="alternate" type="text/html" title="How to Host Label Studio on AWS Elastic Beanstalk with Persistent Storage and RDS PostgreSQL" /><published>2022-07-06T00:00:00+00:00</published><updated>2022-07-06T00:00:00+00:00</updated><id>https://io.twigfarm.net/aws/labelstudio-elasticbeanstalk</id><content type="html" xml:base="https://io.twigfarm.net/aws/labelstudio-elasticbeanstalk/"><![CDATA[<p>Published on July 06, 2022</p>

<p><strong>By Hyuntaek Park</strong></p>

<p><em>Senior full-stack engineer at Twigfarm</em></p>

<p>At Twigfarm, we wanted to host the Label Studio on the AWS Elastic Beanstalk. I googled it for how and found only one article: <a href="https://medium.com/@KerleIndia/how-to-host-label-studio-on-aws-elastic-beanstalk-41abcbcced4">https://medium.com/@KerleIndia/how-to-host-label-studio-on-aws-elastic-beanstalk-41abcbcced4</a></p>

<p>It provides a simple method to host the Label Studio on the AWS Elastic Beanstalk but with data persistence problems. The storage is only temporary; login status and files are gone within a few hours.</p>

<p>An alternative solution is to use Heroku. With just a few clicks you can easily deploy the Label Studio application on Heroku. However, we want to control the database and files directly. Thus, we could not give AWS Elastic Beanstalk option.</p>

<p>In this tutorial, I go over how to deploy the Label Studio application on AWS Elastic Beanstalk while keeping persistent storage and separating the database. Custom domains and HTTPs settings are beyond the scope of this tutorial. You can refer to this link for some hints: <a href="https://io.twigfarm.net/aws/https-ec2/">https://io.twigfarm.net/aws/https-ec2/</a></p>

<h2 id="architecture">Architecture</h2>

<p>Here is a simple diagram of how we host the Label Studio is deployed on AWS Elastic Beanstalk setup.</p>

<p><img width="883" alt="image" src="https://user-images.githubusercontent.com/69557497/177544428-7b12e397-dd55-4bd7-8c50-1f33a4cb7634.png" /></p>

<p>One thing to note is that here I am using the instances that are as small as possible for the demo purpose. You might need to set up with larger instances and load balancers correctly if you are trying to do the production deployment.</p>

<p>Let us start by setting up the RDS Postgres first.</p>

<h2 id="aws-rds-postgres-setup">AWS RDS Postgres Setup</h2>

<p><img width="787" alt="image" src="https://user-images.githubusercontent.com/69557497/177545555-52fc6d6e-64d9-4b8e-b1a3-0ad18cbaed00.png" /></p>

<p>Go to RDS and create a PostgreSQL database. Leave the settings as default except for the followings:</p>

<ul>
  <li>Choose PostgreSQL</li>
  <li>Set username</li>
  <li>Set the master password</li>
  <li>Confirm password</li>
  <li>Initial database name in Additional configuration (Important!): I used “labelstudio_db”</li>
</ul>

<p><img width="808" alt="image" src="https://user-images.githubusercontent.com/69557497/177546662-83d514cc-3978-460a-9c97-423eed864431.png" /></p>

<p>Then wait for a while until the database creation gets finished.</p>

<h2 id="docker-build">Docker Build</h2>

<p>Go ahead and clone the Label Studio GitHub Repository.</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>git clone https://github.com/heartexlabs/label-studio.git label-studio-eb

</code></pre></div></div>

<h2 id="ecr-setup">ECR Setup</h2>

<p>Now that your docker image is ready. Now it is time for the repository setup for the docker image.</p>

<p>Go to “Amazon Elastic Container Services (ECS)”, then choose Repositories under Amazon ECR on your left panel in the AWS console.</p>

<p>Click “Create repository”.</p>

<ul>
  <li>Repository name: labelstudio</li>
</ul>

<p><img width="1014" alt="image" src="https://user-images.githubusercontent.com/69557497/177555689-8f11d3cf-b8ce-4ada-a9ef-b8a2dd66c98d.png" /></p>

<p>Click “Create repository”.</p>

<p>Once the repository is created, click on “View push commands” and type in the commands as the following:</p>

<p><img width="797" alt="image" src="https://user-images.githubusercontent.com/69557497/177557351-3ee5e7bb-4ca2-4807-84d1-2b09d4daffac.png" /></p>

<p>The following are done sequentially.</p>

<ol>
  <li>Login</li>
  <li>Docker build</li>
  <li>Tag</li>
  <li>Push</li>
</ol>

<p>After the successful push, you should be able to see the image that was just pushed.</p>

<p><img width="1238" alt="image" src="https://user-images.githubusercontent.com/69557497/177560638-8bb44420-d774-4dbb-9810-44d7aa31a621.png" /></p>

<h2 id="iam-role-to-connect-to-ecr-from-the-elastic-beanstalk">IAM role to connect to ECR from the Elastic Beanstalk</h2>

<p>Go to “IAM” in AWS console. Choose “aws-elasticbeanstalk-ec2-role” under Access mangement &gt; Roles. Add “AWSAppRunnerServicePolicyForECRAccess” policy.</p>

<p><img width="1263" alt="image" src="https://user-images.githubusercontent.com/69557497/177656085-ef6b7c4c-98c7-470e-8394-caa88280f51b.png" /></p>

<h2 id="efs">EFS</h2>

<p>Go to EFS (Elastic File System) in the AWS console. Create a file system by clicking the “Create file system” button. Leave all the settings as they were. We create one with the “Standard” storage class.</p>

<p><img width="625" alt="image" src="https://user-images.githubusercontent.com/69557497/177643558-7b051158-9bbf-4ce1-8df8-cba0314298bd.png" /></p>

<p>Make a note of the “File system ID”, which we will need in the next section.</p>

<h2 id="elastic-beanstalk-deployment-files">Elastic Beanstalk Deployment Files</h2>

<p>We need to create four files:</p>

<ol>
  <li>.ebextensions/01_mount.config # For EFS mount</li>
  <li>.platform/00_nginx.config # For nginx settings</li>
  <li>.platform/nginx/conf.d/proxy.conf # For unlimited file size upload</li>
</ol>

<h3 id="efs-mount">EFS mount</h3>

<p>Persistent storage is very important since we upload source files and create output files that they should be retained over time and across the users. I chose EFS is pretty consistent and automatically scales.</p>

<p>First of all, create the following directory and a file.</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code># .ebextensions/01_mount.config

option_settings:
  aws:elasticbeanstalk:application:environment:
    FILE_SYSTEM_ID: '&lt;YOUR_FILE_SYSTEM_ID&gt;'
    MOUNT_DIRECTORY: '/efs'

##############################################
#### Do not modify values below this line ####
##############################################

packages:
  yum:
    amazon-efs-utils: []

commands:
  01_mount:
    command: '/tmp/mount-efs.sh'

files:
  '/tmp/mount-efs.sh':
    mode: '000755'
    content: |
      #!/bin/bash

      EFS_MOUNT_DIR=$(/opt/elasticbeanstalk/bin/get-config environment -k MOUNT_DIRECTORY)
      EFS_FILE_SYSTEM_ID=$(/opt/elasticbeanstalk/bin/get-config environment -k FILE_SYSTEM_ID)

      echo "Mounting EFS filesystem ${EFS_FILE_SYSTEM_ID} to directory ${EFS_MOUNT_DIR} ..."

      echo 'Stopping NFS ID Mapper...'
      service rpcidmapd status &amp;&gt; /dev/null
      if [ $? -ne 0 ] ; then
          echo 'rpc.idmapd is already stopped!'
      else
          service rpcidmapd stop
          if [ $? -ne 0 ] ; then
              echo 'ERROR: Failed to stop NFS ID Mapper!'
              exit 1
          fi
      fi

      echo 'Checking if EFS mount directory exists...'
      if [ ! -d ${EFS_MOUNT_DIR} ]; then
          echo "Creating directory ${EFS_MOUNT_DIR} ..."
          mkdir -p ${EFS_MOUNT_DIR}
          if [ $? -ne 0 ]; then
              echo 'ERROR: Directory creation failed!'
              exit 1
          fi
      else
          echo "Directory ${EFS_MOUNT_DIR} already exists!"
      fi

      mountpoint -q ${EFS_MOUNT_DIR}
      if [ $? -ne 0 ]; then
          echo "mount -t efs -o tls ${EFS_FILE_SYSTEM_ID}:/ ${EFS_MOUNT_DIR}"
          mount -t efs -o tls ${EFS_FILE_SYSTEM_ID}:/ ${EFS_MOUNT_DIR}
          if [ $? -ne 0 ] ; then
              echo 'ERROR: Mount command failed!'
              exit 1
          fi
          chmod 777 ${EFS_MOUNT_DIR}
          runuser -l  ec2-user -c "touch ${EFS_MOUNT_DIR}/it_works"
          if [[ $? -ne 0 ]]; then
              echo 'ERROR: Permission Error!'
              exit 1
          else
              runuser -l  ec2-user -c "rm -f ${EFS_MOUNT_DIR}/it_works"
          fi
      else
          echo "Directory ${EFS_MOUNT_DIR} is already a valid mountpoint!"
      fi

      echo 'EFS mount complete.'

</code></pre></div></div>

<h3 id="nginx-configuration">nginx configuration</h3>

<p>We often deal with large files with more than 10 mb in the Label Studio. We manually need to override default nginx settings so that we can upload large-size files. We need two files to achieve the goal.</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code># .platform/00_nginx.config
files:
  “/etc/nginx/conf.d/proxy.conf”:
     mode: “000644”
     owner: root
     group: root
     content: |
       keepalive_timeout 120s;
       proxy_connect_timeout 120s;
       proxy_send_timeout 120s;
       proxy_read_timeout 120s;
       fastcgi_send_timeout 120s;
       fastcgi_read_timeout 120s;
container_commands:
  nginx_reload:
     command: “sudo service nginx reload”

</code></pre></div></div>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
# .platform/nginx/conf.d/proxy.conf
client_max_body_size 0;

</code></pre></div></div>

<p>You can consult more details about Elastic Beanstalk platform extensions in this link: <a href="https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/platforms-linux-extend.html">https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/platforms-linux-extend.html</a></p>

<h3 id="dockerrunawsjson-file">Dockerrun.aws.json File</h3>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>{
  "AWSEBDockerrunVersion": "1",
  "Image": {
    "Name": "&lt;YOUR_ECR_REPOSITORY_URI&gt;:latest",
    "Update": "true"
  },
  "Ports": [
    {
      "ContainerPort": "8080"
    }
  ],
  "Volumes": [
    {
      "HostDirectory": "/efs/data/",
      "ContainerDirectory": "/label-studio/data/"
    }
  ]
}
</code></pre></div></div>

<h3 id="upload">Upload</h3>

<p>Now that our Elastic Beanstalk configuration files are ready. Let zip them into one file: deploy.zip</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>zip -r deploy.zip Dockerrun.aws.json .platform .ebextensions
</code></pre></div></div>

<p>Almost done. Let us create an Elastic Beanstalk application to deploy the system.</p>

<h2 id="elastic-beanstalk-creation">Elastic Beanstalk Creation</h2>

<p>Go to Amazon Elastic Beanstalk Environments in the AWS console. Start by clicking “Create a new environment”.</p>

<ul>
  <li>environment tier: Web server environment</li>
  <li>Application name: labelstudio-eb</li>
  <li>Platform: Docker</li>
  <li>Platform branch: Docker running on 64bit Amazon Linux 2</li>
  <li>Platform version: 3.4.17 (Recommended)</li>
  <li>Application code: Upload your code</li>
  <li>Source code origin: Local file</li>
  <li>Choose file: deploy.zip</li>
</ul>

<p>It is not over yet. Click the “Configure more options” button to set environment variables for the database. Find the “Software” section and click the “Edit” button. Then scroll down to input environment variables under “Environment properties”</p>

<h3 id="networking-setup">Networking Setup</h3>

<p>Choose the same VPC as the one That EFS is in.</p>

<h3 id="instance-security-group-setup">Instance Security Group Setup</h3>

<p>Choose the default security group since the default security group allows all the incoming traffic. To be more specific, you should choose the security group that opens the 2049 port to connect with the EFS.</p>

<h3 id="environment-variable-set">Environment Variable Set</h3>

<ul>
  <li>POSTGRE_USER: <code class="language-plaintext highlighter-rouge">&lt;DB_USERNAME&gt;</code></li>
  <li>POSTGRE_PASSWORD: <code class="language-plaintext highlighter-rouge">&lt;DB_PASSWORD&gt;</code></li>
  <li>POSTGRE_HOST: <code class="language-plaintext highlighter-rouge">&lt;HOST_URL&gt;</code> # Find it under RDS &gt; Connectivity &amp; security &gt; Endpoint</li>
  <li>POSTGRE_PORT: 5432 # Find it under RDS &gt; Connectivity &amp; security &gt; Port</li>
  <li>POSTGRE_NAME: labelstudio_db</li>
  <li>DJANGO_DB: default</li>
</ul>

<p><img width="880" alt="image" src="https://user-images.githubusercontent.com/69557497/177650145-88fd6912-4fb3-4bbe-ba7c-45d59c2e450e.png" /></p>

<p>Click the “Save” button then “Create environment” button. This will take a few minutes.</p>

<p><img width="1240" alt="image" src="https://user-images.githubusercontent.com/69557497/177656691-15f9cdb4-72e8-40c8-87c3-a570ece91844.png" /></p>

<p>Now the environment is ready. Click the “Go to environment” button to see if the application works well.</p>]]></content><author><name></name></author><category term="[&quot;AWS&quot;]" /><category term="AWS" /><category term="Elastic Beanstalk" /><category term="Label Studio" /><category term="EFS" /><category term="RDS" /><category term="PostgreSQL" /><summary type="html"><![CDATA[This blog post demonstrates how to deploy the Label Studio on AWS Elastic Beanstalk with consistent storage and database]]></summary></entry><entry><title type="html">Preserving Content-Type Header on Files Uploaded Using S3 signed URL</title><link href="https://io.twigfarm.net/aws/s3-content-type/" rel="alternate" type="text/html" title="Preserving Content-Type Header on Files Uploaded Using S3 signed URL" /><published>2022-03-12T00:00:00+00:00</published><updated>2022-03-12T00:00:00+00:00</updated><id>https://io.twigfarm.net/aws/s3-content-type</id><content type="html" xml:base="https://io.twigfarm.net/aws/s3-content-type/"><![CDATA[<p>Published on March 12, 2022</p>

<p><strong>By Hyuntaek Park</strong></p>

<p><em>Senior full-stack engineer at Twigfarm</em></p>

<p>One thing I don’t like about Amazon API Gateway is that it has a 30-second timeout. It means uploading and downloading files through API Gateway might not work very well depending on the file size or network speed. The solution is simple. You upload files directly to S3 without API Gateway.</p>

<p>This is not a secure way since your S3 bucket would have public access. S3 signed URL allows you to access the S3 bucket only for a specified period while the S3 bucket stays private. Many tutorials about the S3 signed URL are online and duplicating them is not the purpose of this article.</p>

<p>In this article, I want to share a mistake that I have made; hopefully, this article helps save your time.</p>

<h2 id="architectures">Architectures</h2>

<p>Since our lambda can access to S3 and get the signed URL using JavaScript SDK: https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/S3.html. Search for <strong><em>getSignedUrl</em></strong> on the page.</p>

<h3 id="uploads">Uploads</h3>

<p><img width="566" alt="image" src="https://user-images.githubusercontent.com/69557497/157997159-eb86cfc1-d83d-4449-9671-bb6af1fc2912.png" /></p>

<h3 id="downloads">Downloads</h3>

<p><img width="570" alt="image" src="https://user-images.githubusercontent.com/69557497/157997185-f0ef9f55-b82e-49d2-ad7b-d7ec123e6070.png" /></p>

<h2 id="problem">Problem</h2>

<p>Uploading and downloading files are smooth as butter. Now you are free from timeouts. A few gigabyte files can be handled easily. However, I found something strange after I downloaded the video file I uploaded.</p>

<p><img width="866" alt="image" src="https://user-images.githubusercontent.com/69557497/158001114-9ca65895-126f-4507-85f1-0d1d9e783afe.png" /></p>

<p>The Content-Type header must be video/mp4. Most of the time we acknowledge the file type by reading the Content-Type header. Thus, we have to be sure the content-type header is consistent from the moment of uploading and downloading.</p>

<h2 id="solution">Solution</h2>

<p>Although I tried various parameters while invoking the getSignedUrl function, nothing really worked. But the solution was super simple.</p>

<div class="language-js highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">export</span> <span class="kd">const</span> <span class="nx">putSingleFile</span> <span class="o">=</span> <span class="k">async</span> <span class="p">(</span><span class="nx">url</span><span class="p">,</span> <span class="nx">file</span><span class="p">)</span> <span class="o">=&gt;</span> <span class="p">{</span>
  <span class="kd">const</span> <span class="nx">instance</span> <span class="o">=</span> <span class="nx">axios</span><span class="p">.</span><span class="nx">create</span><span class="p">();</span>
  <span class="kd">const</span> <span class="nx">response</span> <span class="o">=</span> <span class="k">await</span> <span class="nx">instance</span><span class="p">({</span>
    <span class="na">method</span><span class="p">:</span> <span class="dl">"</span><span class="s2">put</span><span class="dl">"</span><span class="p">,</span>
    <span class="nx">url</span><span class="p">,</span>
    <span class="na">data</span><span class="p">:</span> <span class="nx">file</span><span class="p">,</span>
    <span class="na">headers</span><span class="p">:</span> <span class="p">{</span>
      <span class="dl">"</span><span class="s2">Content-Type</span><span class="dl">"</span><span class="p">:</span> <span class="nx">file</span><span class="p">.</span><span class="nx">type</span><span class="p">,</span> <span class="c1">// This is what I forgot</span>
    <span class="p">},</span>
  <span class="p">});</span>
  <span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="dl">"</span><span class="s2">response: </span><span class="dl">"</span><span class="p">,</span> <span class="nx">response</span><span class="p">);</span>
<span class="p">};</span>
</code></pre></div></div>

<p>Axios doesn’t specify the Content-Type header automatically, which I overlooked. I added the Content-Type header and it worked like a charm. I wasted too much time stupidly :).</p>

<p><img width="835" alt="image" src="https://user-images.githubusercontent.com/69557497/158001523-7891163f-af3d-4327-aa98-63635b9117b6.png" /></p>

<p>Now its Content-Type is <strong><em>video/mp4</em></strong> as it is supposed to be.</p>

<p>I hope this article saves some time for you.</p>]]></content><author><name></name></author><category term="[&quot;AWS&quot;]" /><category term="AWS" /><category term="S3" /><category term="S3 signed URL" /><category term="API Gateway" /><category term="Serverless" /><category term="Axios" /><summary type="html"><![CDATA[This blog post demonstrate a simple use case that the content-type header should be retained throughout the process of uploading to S3 and downloading from S3 directly using the S3 signed URL]]></summary></entry><entry><title type="html">Zipping Large Size S3 Folders and Files Using Node.js Lambda And EFS</title><link href="https://io.twigfarm.net/aws/zip-s3-files/" rel="alternate" type="text/html" title="Zipping Large Size S3 Folders and Files Using Node.js Lambda And EFS" /><published>2022-02-10T00:00:00+00:00</published><updated>2022-02-10T00:00:00+00:00</updated><id>https://io.twigfarm.net/aws/zip-s3-files</id><content type="html" xml:base="https://io.twigfarm.net/aws/zip-s3-files/"><![CDATA[<p>Published on February 10, 2022</p>

<p><strong>By Hyuntaek Park</strong></p>

<p><em>Senior full-stack engineer at Twigfarm</em></p>

<p>AWS S3 is a very convenient cloud storage. You can upload and download files easily in various ways with AWS CLI, SDK, API, etc. But can you download an entire folder and its sub-folders and files recursively? Unfortunately, S3 does not provide such features. We need to develop our own way to recursively zip the folder and make the zip file available for download.</p>

<h2 id="requirements">Requirements</h2>

<p>Our goal is to zip entire folders, sub-folders, and files under the folders in our S3 bucket while preserving folder structure tree. The files can be large (&gt; 512 MB, which is the size of Lambda temporary storage).</p>

<h2 id="how-files-are-treated-in-s3">How files are treated in S3</h2>

<p>We have created folders and uploaded files as following in S3 bucket.</p>

<p><img width="400" alt="image" src="https://user-images.githubusercontent.com/69557497/152930395-477bcf2e-65de-4ef4-b3de-ffabfcd679bb.png" /></p>

<p>However, to be concise, they are not folders in S3. There are just four files with the following keys:</p>

<ul>
  <li>folder1/sub1/image.png</li>
  <li>folder1/sub2/test.txt</li>
  <li>folder2/large.mov</li>
  <li>folder2/test2.pdf</li>
</ul>

<h2 id="solution">Solution</h2>

<p>Although S3 does not have a concept of folders, the key of each file has folder information as prefixes. Each folder level is delimited by ‘/’ and followed by the file name. (i.e., folder1/sub1/image.png)</p>

<p>Using the key that has folder information prefix, we can create folders in EFS and then download the file from S3.</p>

<p>Then Lambda simply does the zipping and upload the zip file back to S3. Following diagram shows the sequence of our implementation and how files are represented differently in S3 and EFS.</p>

<p><img src="https://user-images.githubusercontent.com/69557497/152934649-6445dc7a-1428-40af-9e0d-47db689a1758.png" alt="image" /></p>

<p>One thing to keep in mind is that our Lambda and the EFS must be in the same VPC.</p>

<h2 id="create-efs-elastic-file-system-and-access-point">Create EFS (Elastic File System) and access point</h2>

<p>There are a couple of reasons why Amazon EFS comes in handy.</p>

<ul>
  <li>EFS is just like Linux file system. You can use file commands such as <strong>mkdir</strong>, <strong>ls</strong>, <strong>cp</strong>, <strong>rm</strong>, etc.</li>
  <li>We could use Lambda’s temporary storage has size limit: &lt; 512MB</li>
</ul>

<p>Let’s create an EFS.
Go to <strong>Elastic File System</strong> in AWS console and click <strong>Create file system</strong>.
<img src="https://user-images.githubusercontent.com/69557497/152936532-6b30c710-9b29-4b9e-8252-a72df60a36b1.png" alt="image" /></p>

<p>Then click <strong>Create</strong>.</p>

<p>Now it is time for creating an access point which to be used in Lambda function later. Choose the file system we just created. Then click <strong>Access points</strong> –&gt; <strong>Create access point</strong>.</p>

<p>Here’s the input values you should enter:</p>

<ul>
  <li>Root directory path: /efs</li>
  <li>POSIX user
    <ul>
      <li>User ID: 1000</li>
      <li>Group ID: 1000</li>
    </ul>
  </li>
  <li>Root directory creation permissions
    <ul>
      <li>Owner user ID: 1000</li>
      <li>Owner group ID: 1000</li>
      <li>POSIX permissions to apply to the root directory path: 0777</li>
    </ul>
  </li>
</ul>

<p><img src="https://user-images.githubusercontent.com/69557497/152943276-e459dfe0-4052-4627-b7aa-aaa2f8b3818a.png" alt="image" /></p>

<h2 id="create-and-configure-efs-attached-lambda-function">Create and configure EFS attached Lambda function</h2>

<p>Let’s create a Node.js Lambda function as following:</p>

<p><img src="https://user-images.githubusercontent.com/69557497/152939842-5a3daded-679a-4bf0-8987-f0c882ed9284.png" alt="image" /></p>

<p><img src="https://user-images.githubusercontent.com/69557497/152937286-18b72b59-c539-4b4d-84a3-dad1b5a542ab.png" alt="image" /></p>

<p>Once the Lambda function is created, click <strong>Configuration</strong> –&gt; <strong>File systems</strong> –&gt; <strong>Add file system</strong>.</p>

<p><img src="https://user-images.githubusercontent.com/69557497/152944563-702f1271-8ca5-4342-a8b5-5f2ef5d4d101.png" alt="image" /></p>

<p>Choose the EFS access point that we have just created. And put <strong><em>/mnt/efs</em></strong> for Local mount path. This important because <strong><em>/mnt/efs</em></strong> will be your EFS folder.</p>

<p>Click <strong>Save</strong>, now you have access to <strong><em>/mnt/efs</em></strong> from the Lambda function.</p>

<h2 id="access-to-s3-from-lambda">Access to S3 from Lambda</h2>

<h3 id="vpc-endpoints">VPC Endpoints</h3>

<p>According to https://docs.aws.amazon.com/vpc/latest/privatelink/vpc-endpoints.html,</p>

<blockquote>
  <p><strong>A VPC endpoint</strong> enables connections between a virtual private cloud (VPC) and supported services, without requiring that you use an internet gateway, NAT device, VPN connection, or AWS Direct Connect connection.</p>
</blockquote>

<p>To access to S3 buckets from Lambdas inside a VPC, we need to set up a VPC endpoint for S3. Go to <strong>VPC</strong> and click <strong>Endpoints</strong> –&gt; <strong>Create endpoint</strong>. Then select input as following:</p>

<p><img width="842" alt="image" src="https://user-images.githubusercontent.com/69557497/153161139-6c54abf4-eae0-4160-bd1a-ccf81847913f.png" /></p>

<p><img width="850" alt="image" src="https://user-images.githubusercontent.com/69557497/153162855-27f18447-06e9-47e1-ad9a-bc204d3be25e.png" /></p>

<p>Then click <strong>Create endpoint</strong>. Technically the Lambdas within the VPC can access to S3 now but one more step is required to really access to a specific S3 bucket.</p>

<h3 id="lambda-role">Lambda role</h3>

<p>A Lambda role is created while creating our Lambda function. You can use the existing role for the Lambda. Here we just created a new role. Go to our Lambda function then click <strong>Configuration</strong> –&gt; <strong>Permissions</strong>. Then choose the role under <strong>Execution role</strong>.</p>

<p><img width="1164" alt="image" src="https://user-images.githubusercontent.com/69557497/153315284-6e1e9deb-d2f1-43cb-a809-079a7a5fd54f.png" /></p>

<p>Then go to <strong>Permissions policies</strong> –&gt; click <strong>Add permissions</strong> –&gt; <strong>Create inline policy</strong>. On the next screen, choose <strong>JSON</strong> tab. Then copy and paste following. Replace YOUR_BUCKET_NAME with your own bucket name.</p>

<div class="language-json highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="p">{</span><span class="w">
  </span><span class="nl">"Version"</span><span class="p">:</span><span class="w"> </span><span class="s2">"2012-10-17"</span><span class="p">,</span><span class="w">
  </span><span class="nl">"Statement"</span><span class="p">:</span><span class="w"> </span><span class="p">[</span><span class="w">
    </span><span class="p">{</span><span class="w">
      </span><span class="nl">"Sid"</span><span class="p">:</span><span class="w"> </span><span class="s2">"VisualEditor1"</span><span class="p">,</span><span class="w">
      </span><span class="nl">"Effect"</span><span class="p">:</span><span class="w"> </span><span class="s2">"Allow"</span><span class="p">,</span><span class="w">
      </span><span class="nl">"Action"</span><span class="p">:</span><span class="w"> </span><span class="s2">"s3:*"</span><span class="p">,</span><span class="w">
      </span><span class="nl">"Resource"</span><span class="p">:</span><span class="w"> </span><span class="p">[</span><span class="w">
        </span><span class="s2">"arn:aws:s3:::YOUR_BUCKET_NAME"</span><span class="p">,</span><span class="w">
        </span><span class="s2">"arn:aws:s3:::YOUR_BUCKET_NAME/*"</span><span class="w">
      </span><span class="p">]</span><span class="w">
    </span><span class="p">}</span><span class="w">
  </span><span class="p">]</span><span class="w">
</span><span class="p">}</span><span class="w">
</span></code></pre></div></div>

<p>Click <strong>Review policy</strong>. Enter the policy name you like and then click <strong>Create policy</strong>.</p>

<h2 id="more-lambda-configuration">More Lambda configuration</h2>

<p>Since downloading takes time and file sizes can be hundreds of megabytes, Lambda’s default memory size (128 MB) and timeout (3 seconds) are not enough. For this demonstration, memory size and timeout are set to 4096 MB and 2 minutes, respectively in <strong>Configuration</strong> –&gt; <strong>General configuration</strong>.</p>

<h2 id="lambda-code">Lambda code</h2>

<p>Here’s the final Lambda code. The code implements what we have discussed.</p>

<ol>
  <li>Copies folders / file from S3 to EFS.</li>
  <li>Zips downloaded files in EFS</li>
  <li>Uploads the zip file back to S3</li>
  <li>Removes the temporary EFS files</li>
</ol>

<div class="language-js highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">const</span> <span class="p">{</span> <span class="nx">exec</span> <span class="p">}</span> <span class="o">=</span> <span class="nx">require</span><span class="p">(</span><span class="dl">"</span><span class="s2">child_process</span><span class="dl">"</span><span class="p">);</span>
<span class="kd">const</span> <span class="nx">fs</span> <span class="o">=</span> <span class="nx">require</span><span class="p">(</span><span class="dl">"</span><span class="s2">fs</span><span class="dl">"</span><span class="p">);</span>
<span class="kd">const</span> <span class="nx">archiver</span> <span class="o">=</span> <span class="nx">require</span><span class="p">(</span><span class="dl">"</span><span class="s2">archiver</span><span class="dl">"</span><span class="p">);</span>

<span class="kd">const</span> <span class="nx">AWS</span> <span class="o">=</span> <span class="nx">require</span><span class="p">(</span><span class="dl">"</span><span class="s2">aws-sdk</span><span class="dl">"</span><span class="p">);</span>
<span class="kd">const</span> <span class="nx">s3</span> <span class="o">=</span> <span class="k">new</span> <span class="nx">AWS</span><span class="p">.</span><span class="nx">S3</span><span class="p">();</span>

<span class="kd">const</span> <span class="nx">bucketName</span> <span class="o">=</span> <span class="dl">"</span><span class="s2">zip-s3-test</span><span class="dl">"</span><span class="p">;</span>
<span class="kd">const</span> <span class="nx">sourceDir</span> <span class="o">=</span> <span class="dl">"</span><span class="s2">/mnt/efs/temp</span><span class="dl">"</span><span class="p">;</span>
<span class="kd">const</span> <span class="nx">outPath</span> <span class="o">=</span> <span class="dl">"</span><span class="s2">/mnt/efs/temp.zip</span><span class="dl">"</span><span class="p">;</span>

<span class="nx">exports</span><span class="p">.</span><span class="nx">handler</span> <span class="o">=</span> <span class="k">async</span> <span class="p">()</span> <span class="o">=&gt;</span> <span class="p">{</span>
  <span class="k">await</span> <span class="nx">copyFilesFromS3BucketToEfs</span><span class="p">(</span><span class="nx">bucketName</span><span class="p">);</span>
  <span class="k">await</span> <span class="nx">zipFolders</span><span class="p">(</span><span class="nx">sourceDir</span><span class="p">,</span> <span class="nx">outPath</span><span class="p">);</span>
  <span class="k">await</span> <span class="nx">uploadZipFileToS3</span><span class="p">(</span><span class="nx">bucketName</span><span class="p">,</span> <span class="nx">outPath</span><span class="p">);</span>
  <span class="k">await</span> <span class="nx">executeSystemCommand</span><span class="p">(</span><span class="dl">"</span><span class="s2">rm -rf /mnt/efs/*</span><span class="dl">"</span><span class="p">);</span>
<span class="p">};</span>

<span class="kd">const</span> <span class="nx">copyFilesFromS3BucketToEfs</span> <span class="o">=</span> <span class="k">async</span> <span class="p">(</span><span class="nx">bucket</span><span class="p">)</span> <span class="o">=&gt;</span> <span class="p">{</span>
  <span class="kd">const</span> <span class="nx">s3Objects</span> <span class="o">=</span> <span class="k">await</span> <span class="nx">s3</span>
    <span class="p">.</span><span class="nx">listObjectsV2</span><span class="p">({</span>
      <span class="na">Bucket</span><span class="p">:</span> <span class="nx">bucket</span><span class="p">,</span>
    <span class="p">})</span>
    <span class="p">.</span><span class="nx">promise</span><span class="p">();</span>

  <span class="k">for</span> <span class="p">(</span><span class="kd">const</span> <span class="nx">content</span> <span class="k">of</span> <span class="nx">s3Objects</span><span class="p">.</span><span class="nx">Contents</span><span class="p">)</span> <span class="p">{</span>
    <span class="k">if</span> <span class="p">(</span><span class="nx">content</span><span class="p">.</span><span class="nx">Size</span> <span class="o">===</span> <span class="mi">0</span><span class="p">)</span> <span class="p">{</span>
      <span class="c1">// only zip the files with size &gt; 0</span>
      <span class="k">continue</span><span class="p">;</span>
    <span class="p">}</span>
    <span class="kd">const</span> <span class="nx">s3KeyArray</span> <span class="o">=</span> <span class="nx">content</span><span class="p">.</span><span class="nx">Key</span><span class="p">.</span><span class="nx">split</span><span class="p">(</span><span class="dl">"</span><span class="s2">/</span><span class="dl">"</span><span class="p">);</span>
    <span class="kd">const</span> <span class="nx">fileName</span> <span class="o">=</span> <span class="nx">s3KeyArray</span><span class="p">.</span><span class="nx">pop</span><span class="p">();</span>
    <span class="kd">const</span> <span class="nx">folderName</span> <span class="o">=</span> <span class="nx">s3KeyArray</span><span class="p">.</span><span class="nx">join</span><span class="p">(</span><span class="dl">""</span><span class="p">);</span>
    <span class="k">await</span> <span class="nx">executeSystemCommand</span><span class="p">(</span><span class="s2">`mkdir -p '/mnt/efs/temp/</span><span class="p">${</span><span class="nx">folderName</span><span class="p">}</span><span class="s2">'`</span><span class="p">);</span>
    <span class="kd">const</span> <span class="nx">s3Object</span> <span class="o">=</span> <span class="k">await</span> <span class="nx">s3</span>
      <span class="p">.</span><span class="nx">getObject</span><span class="p">({</span>
        <span class="na">Bucket</span><span class="p">:</span> <span class="nx">bucket</span><span class="p">,</span>
        <span class="na">Key</span><span class="p">:</span> <span class="nx">content</span><span class="p">.</span><span class="nx">Key</span><span class="p">,</span>
      <span class="p">})</span>
      <span class="p">.</span><span class="nx">promise</span><span class="p">();</span>
    <span class="nx">fs</span><span class="p">.</span><span class="nx">writeFileSync</span><span class="p">(</span><span class="s2">`/mnt/efs/temp/</span><span class="p">${</span><span class="nx">folderName</span><span class="p">}</span><span class="s2">/</span><span class="p">${</span><span class="nx">fileName</span><span class="p">}</span><span class="s2">`</span><span class="p">,</span> <span class="nx">s3Object</span><span class="p">.</span><span class="nx">Body</span><span class="p">);</span>
  <span class="p">}</span>
<span class="p">};</span>

<span class="kd">const</span> <span class="nx">zipFolders</span> <span class="o">=</span> <span class="k">async</span> <span class="p">(</span><span class="nx">sourceDir</span><span class="p">,</span> <span class="nx">outPath</span><span class="p">)</span> <span class="o">=&gt;</span> <span class="p">{</span>
  <span class="kd">const</span> <span class="nx">archive</span> <span class="o">=</span> <span class="nx">archiver</span><span class="p">(</span><span class="dl">"</span><span class="s2">zip</span><span class="dl">"</span><span class="p">);</span>
  <span class="kd">const</span> <span class="nx">stream</span> <span class="o">=</span> <span class="nx">fs</span><span class="p">.</span><span class="nx">createWriteStream</span><span class="p">(</span><span class="nx">outPath</span><span class="p">);</span>

  <span class="k">return</span> <span class="k">new</span> <span class="nb">Promise</span><span class="p">((</span><span class="nx">resolve</span><span class="p">,</span> <span class="nx">reject</span><span class="p">)</span> <span class="o">=&gt;</span> <span class="p">{</span>
    <span class="nx">archive</span>
      <span class="p">.</span><span class="nx">directory</span><span class="p">(</span><span class="nx">sourceDir</span><span class="p">,</span> <span class="kc">false</span><span class="p">)</span>
      <span class="p">.</span><span class="nx">on</span><span class="p">(</span><span class="dl">"</span><span class="s2">error</span><span class="dl">"</span><span class="p">,</span> <span class="p">(</span><span class="nx">err</span><span class="p">)</span> <span class="o">=&gt;</span> <span class="nx">reject</span><span class="p">(</span><span class="nx">err</span><span class="p">))</span>
      <span class="p">.</span><span class="nx">pipe</span><span class="p">(</span><span class="nx">stream</span><span class="p">);</span>

    <span class="nx">stream</span><span class="p">.</span><span class="nx">on</span><span class="p">(</span><span class="dl">"</span><span class="s2">close</span><span class="dl">"</span><span class="p">,</span> <span class="p">()</span> <span class="o">=&gt;</span> <span class="nx">resolve</span><span class="p">());</span>
    <span class="nx">archive</span><span class="p">.</span><span class="nx">finalize</span><span class="p">();</span>
  <span class="p">});</span>
<span class="p">};</span>

<span class="kd">const</span> <span class="nx">uploadZipFileToS3</span> <span class="o">=</span> <span class="k">async</span> <span class="p">(</span><span class="nx">bucket</span><span class="p">,</span> <span class="nx">filePath</span><span class="p">)</span> <span class="o">=&gt;</span> <span class="p">{</span>
  <span class="k">await</span> <span class="nx">s3</span>
    <span class="p">.</span><span class="nx">upload</span><span class="p">({</span>
      <span class="na">Bucket</span><span class="p">:</span> <span class="nx">bucket</span><span class="p">,</span>
      <span class="na">Key</span><span class="p">:</span> <span class="dl">"</span><span class="s2">my-archive.zip</span><span class="dl">"</span><span class="p">,</span>
      <span class="na">Body</span><span class="p">:</span> <span class="nx">fs</span><span class="p">.</span><span class="nx">readFileSync</span><span class="p">(</span><span class="nx">filePath</span><span class="p">),</span>
    <span class="p">})</span>
    <span class="p">.</span><span class="nx">promise</span><span class="p">();</span>
<span class="p">};</span>

<span class="c1">// executes linux command</span>
<span class="kd">const</span> <span class="nx">executeSystemCommand</span> <span class="o">=</span> <span class="k">async</span> <span class="p">(</span><span class="nx">command</span><span class="p">)</span> <span class="o">=&gt;</span> <span class="p">{</span>
  <span class="kd">const</span> <span class="nx">promise</span> <span class="o">=</span> <span class="k">new</span> <span class="nb">Promise</span><span class="p">((</span><span class="nx">resolve</span><span class="p">,</span> <span class="nx">reject</span><span class="p">)</span> <span class="o">=&gt;</span> <span class="p">{</span>
    <span class="nx">exec</span><span class="p">(</span><span class="nx">command</span><span class="p">,</span> <span class="p">(</span><span class="nx">error</span><span class="p">,</span> <span class="nx">stdout</span><span class="p">,</span> <span class="nx">stderr</span><span class="p">)</span> <span class="o">=&gt;</span> <span class="p">{</span>
      <span class="k">if</span> <span class="p">(</span><span class="nx">error</span><span class="p">)</span> <span class="p">{</span>
        <span class="nx">reject</span><span class="p">(</span><span class="nx">error</span><span class="p">);</span>
      <span class="p">}</span>
      <span class="k">if</span> <span class="p">(</span><span class="nx">stderr</span><span class="p">)</span> <span class="p">{</span>
        <span class="nx">reject</span><span class="p">(</span><span class="nx">stderr</span><span class="p">);</span>
      <span class="p">}</span>
      <span class="nx">resolve</span><span class="p">(</span><span class="nx">stdout</span><span class="p">);</span>
    <span class="p">});</span>
  <span class="p">});</span>

  <span class="k">return</span> <span class="nx">promise</span><span class="p">;</span>
<span class="p">};</span>
</code></pre></div></div>

<p>I hope the code itself is self-explanatory. Just one thing to mention is that we used an open source Node.js package called <strong><em>archiver</em></strong> for zipping folders and files. There are many ways that you can zip files in Node.js. You can choose whatever suits you the best.</p>

<p>Obviously there should be <strong><em>try / catch</em></strong> blocks to deal with error cases. But here we just omit them for simplicity.</p>

<h2 id="results">Results</h2>

<p>Let’s go check our S3 bucket.</p>

<p><img width="1164" alt="image" src="https://user-images.githubusercontent.com/69557497/153357596-588a922f-44e9-4bea-ab3d-45ec26282166.png" /></p>

<p>As you can see there is a new zip file, called <strong><em>my-archive.zip</em></strong>. Let’s click the file name and download and unzip the file.</p>

<p><img width="400" alt="image" src="https://user-images.githubusercontent.com/69557497/153359407-44edc423-ee9c-449b-b93f-5e414c3ad09b.png" /></p>

<p>Folder and file structure is exactly the same as the one at the top of this article.</p>

<p>We had many steps to follow to achieve this simple requirement, zipping folders and files in S3, but they are pretty standard when you have to deal with AWS.</p>

<ul>
  <li>Create and launch AWS service</li>
  <li>Give appropriate permissions</li>
  <li>Execute the logic</li>
</ul>

<p>It took a while for me to get used to it! :)</p>

<p>Thanks for reading.</p>]]></content><author><name></name></author><category term="[&quot;AWS&quot;]" /><category term="AWS" /><category term="EFS" /><category term="S3" /><category term="Lambda" /><category term="Serverless" /><summary type="html"><![CDATA[This blog post explains how to archive multiple folders and files that are stored in AWS S3 into one zip file using Node.js Lambda function and EFS]]></summary></entry><entry><title type="html">Sending Alert Text Messages Based on CloudWatch Log Patterns</title><link href="https://io.twigfarm.net/aws/cloudwatch-subscription-filter/" rel="alternate" type="text/html" title="Sending Alert Text Messages Based on CloudWatch Log Patterns" /><published>2021-12-24T00:00:00+00:00</published><updated>2021-12-24T00:00:00+00:00</updated><id>https://io.twigfarm.net/aws/cloudwatch-subscription-filter</id><content type="html" xml:base="https://io.twigfarm.net/aws/cloudwatch-subscription-filter/"><![CDATA[<p>Published on December 24, 2021</p>

<p><strong>By Hyuntaek Park</strong></p>

<p><em>Senior full-stack engineer at Twigfarm</em></p>

<h2 id="introduction">Introduction</h2>

<p>Monitoring or getting an alert when unexpected happens is essential to keep our system reliable. System faults should be notified to appropriate person as early as it can be. This can be achieved easily with <strong><em>CloudWatch</em></strong>.</p>

<p>In this post, I create a simple <strong><em>lambda</em></strong> function and a couple of tests with a normal condition and one with an error condition. Once the error condition happens SMS text message is sent to my cell number all the way from North Virginia (us-east-1) to Seoul, Korea (ap-northeast-2).</p>

<p>The idea is simple:</p>

<ul>
  <li>Exception happens during lambda execution</li>
  <li>Logging error in the <strong><em>CloudWatch</em></strong> associated with that lambda</li>
  <li><strong><em>CloudWatch</em></strong> invokes another lambda function which sends an SMS text message if a predefined expression is in the log text</li>
</ul>

<p><img src="https://user-images.githubusercontent.com/69557497/147298928-cd2a24b2-2192-4d41-b9ca-c394d479f3d5.png" alt="Architecture" /></p>

<h2 id="creating-a-simple-lambda-function">Creating a simple lambda function</h2>

<p>Go to <strong>Lambda Functions</strong> and click <strong>Create function</strong>. Then create a simple function with any name you like.</p>

<p><img src="https://user-images.githubusercontent.com/69557497/147080995-5589cab6-50f6-4c5a-93d1-da9c402d7c54.png" alt="Creating lambda function" /></p>

<p>The lambda code does simple division. Our goal is to get notified if <strong><em>DivideByZeroException</em></strong> occurs.</p>

<div class="language-js highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1">// cloudwatch-alert-test lambda code</span>
<span class="nx">exports</span><span class="p">.</span><span class="nx">handler</span> <span class="o">=</span> <span class="k">async</span> <span class="p">(</span><span class="nx">event</span><span class="p">)</span> <span class="o">=&gt;</span> <span class="p">{</span>
  <span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="dl">"</span><span class="s2">event: </span><span class="dl">"</span><span class="p">,</span> <span class="nx">JSON</span><span class="p">.</span><span class="nx">stringify</span><span class="p">(</span><span class="nx">event</span><span class="p">));</span>
  <span class="kd">const</span> <span class="p">{</span> <span class="nx">x</span><span class="p">,</span> <span class="nx">y</span> <span class="p">}</span> <span class="o">=</span> <span class="nx">event</span><span class="p">;</span>

  <span class="k">try</span> <span class="p">{</span>
    <span class="kd">const</span> <span class="nx">result</span> <span class="o">=</span> <span class="nx">divide</span><span class="p">(</span><span class="nx">x</span><span class="p">,</span> <span class="nx">y</span><span class="p">);</span>
    <span class="k">return</span> <span class="nx">result</span><span class="p">;</span>
  <span class="p">}</span> <span class="k">catch</span> <span class="p">(</span><span class="nx">e</span><span class="p">)</span> <span class="p">{</span>
    <span class="nx">console</span><span class="p">.</span><span class="nx">error</span><span class="p">(</span><span class="nx">e</span><span class="p">);</span>
    <span class="k">return</span> <span class="kc">null</span><span class="p">;</span>
  <span class="p">}</span>
<span class="p">};</span>

<span class="kd">const</span> <span class="nx">divide</span> <span class="o">=</span> <span class="p">(</span><span class="nx">dividend</span><span class="p">,</span> <span class="nx">divisor</span><span class="p">)</span> <span class="o">=&gt;</span> <span class="p">{</span>
  <span class="k">if</span> <span class="p">(</span><span class="nx">divisor</span> <span class="o">===</span> <span class="mi">0</span><span class="p">)</span> <span class="p">{</span>
    <span class="k">throw</span> <span class="nb">Error</span><span class="p">(</span><span class="dl">"</span><span class="s2">DivideByZeroException</span><span class="dl">"</span><span class="p">);</span>
  <span class="p">}</span>
  <span class="k">return</span> <span class="nx">dividend</span> <span class="o">/</span> <span class="nx">divisor</span><span class="p">;</span>
<span class="p">};</span>
</code></pre></div></div>

<h3 id="test-input-ok-case">Test input (OK case)</h3>

<div class="language-json highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="p">{</span><span class="w">
  </span><span class="nl">"x"</span><span class="p">:</span><span class="w"> </span><span class="mi">10</span><span class="p">,</span><span class="w">
  </span><span class="nl">"y"</span><span class="p">:</span><span class="w"> </span><span class="mi">2</span><span class="w">
</span><span class="p">}</span><span class="w">
</span></code></pre></div></div>

<h3 id="logs-for-ok-test-case">Logs for OK test case</h3>

<p><img src="https://user-images.githubusercontent.com/69557497/147230959-7fda96bf-a267-416e-99ed-db3d593d7dac.png" alt="ok test case" /></p>

<h3 id="test-input-error-case">Test input (Error case)</h3>

<div class="language-json highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="p">{</span><span class="w">
  </span><span class="nl">"x"</span><span class="p">:</span><span class="w"> </span><span class="mi">10</span><span class="p">,</span><span class="w">
  </span><span class="nl">"y"</span><span class="p">:</span><span class="w"> </span><span class="mi">0</span><span class="w">
</span><span class="p">}</span><span class="w">
</span></code></pre></div></div>

<h3 id="logs-for-error-test-case">Logs for error test case</h3>

<p><img src="https://user-images.githubusercontent.com/69557497/147231119-1fd23a98-554d-4a08-a6ca-22a9881547ea.png" alt="error test case" /></p>

<h2 id="sms-sender-lambda-function">SMS sender lambda function</h2>

<p>Let’s create another lambda function, called <strong><em>sms-sender</em></strong>, which gets triggered if the CloudWatch log contains certain pattern. For now this lambda function does nothing but prints out the input so that we are able to identify what the CloudWatch input format is like.</p>

<h3 id="sms-sender">sms-sender</h3>

<div class="language-js highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nx">exports</span><span class="p">.</span><span class="nx">handler</span> <span class="o">=</span> <span class="p">(</span><span class="nx">event</span><span class="p">,</span> <span class="nx">context</span><span class="p">)</span> <span class="o">=&gt;</span> <span class="p">{</span>
  <span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="dl">"</span><span class="s2">event: </span><span class="dl">"</span><span class="p">,</span> <span class="nx">JSON</span><span class="p">.</span><span class="nx">stringify</span><span class="p">(</span><span class="nx">event</span><span class="p">));</span>
<span class="p">};</span>
</code></pre></div></div>

<h2 id="cloudwatch-subscription-filters">CloudWatch Subscription Filters</h2>

<p>Now <strong><em>CloudWatch Subscription Filter</em></strong> connects following two lambda functions:</p>

<ul>
  <li>cloudwatch-alert-test</li>
  <li>sms-sender</li>
</ul>

<p>Go to CloudWatch –&gt; Logs –&gt; Log groups –&gt; /aws/lambda/cloudwatch-alert-test
<img src="https://user-images.githubusercontent.com/69557497/147301572-e7a6ca6b-eb59-4acc-9d01-5d6372d6c6e9.png" alt="CloudWatch Logs Menu" /></p>

<p>Then click on <strong><em>Subscription filters</em></strong> tab then choose <strong><em>Create Lambda subscription filter</em></strong>
<img src="https://user-images.githubusercontent.com/69557497/147301722-2a5d274c-e731-420f-9dfc-61dd5be7dc46.png" alt="CloudWatch Subscription filters" /></p>

<p>Input as following:</p>

<ul>
  <li>Lambda function: sms-sender</li>
  <li>Log format: Other</li>
  <li>Subscription filter pattern: DivideByZeroException</li>
  <li>Subscription filter name: <strong><em>ANY_NAME_YOU_LIKE</em></strong></li>
</ul>

<p>Click on <strong><em>Start streaming</em></strong> button to finish CloudWatch subscription filter setup.</p>

<p>This means that <strong><em>sms-sender</em></strong> lambda function gets invoked, if and only if the CloudWatch log contains string <strong><em>DivideByZeroException</em></strong>.</p>

<h2 id="testings">Testings</h2>

<p>We created two tests for <strong><em>cloudwatch-alert-test</em></strong>. Run each of them and check the CloudWatch log for <strong><em>sms-sender</em></strong> to see if the function is invoked only when <strong><em>DivideByZeroException</em></strong> is happened.</p>

<h2 id="input-passed-from-cloudwatch-to-sms-sender">Input passed from <strong><em>CloudWatch</em></strong> to <strong><em>sms-sender</em></strong></h2>

<p>What do you see in <strong><em>sms-sender</em></strong> CloudWatch log? Was the function triggered only on error test case? Probably yes. Now take a look at the event parameter value in the log. You would see some data value like the following:</p>

<p><img src="https://user-images.githubusercontent.com/69557497/147303300-512f07a4-7f5a-41ea-8bd6-9334433840f1.png" alt="CloudWatch logs" /></p>

<p>What is it? We have to unzip to decode the data.</p>

<h2 id="decoding-input-from-cloudwatch">Decoding input from <strong><em>CloudWatch</em></strong></h2>

<p>Following code takes care of unzipping the input from CloudWatch.</p>

<div class="language-js highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">const</span> <span class="nx">zlib</span> <span class="o">=</span> <span class="nx">require</span><span class="p">(</span><span class="dl">"</span><span class="s2">zlib</span><span class="dl">"</span><span class="p">);</span>

<span class="nx">exports</span><span class="p">.</span><span class="nx">handler</span> <span class="o">=</span> <span class="p">(</span><span class="nx">event</span><span class="p">,</span> <span class="nx">context</span><span class="p">)</span> <span class="o">=&gt;</span> <span class="p">{</span>
  <span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="dl">"</span><span class="s2">event: </span><span class="dl">"</span><span class="p">,</span> <span class="nx">JSON</span><span class="p">.</span><span class="nx">stringify</span><span class="p">(</span><span class="nx">event</span><span class="p">));</span>
  <span class="kd">const</span> <span class="nx">payload</span> <span class="o">=</span> <span class="nx">Buffer</span><span class="p">.</span><span class="k">from</span><span class="p">(</span><span class="nx">event</span><span class="p">.</span><span class="nx">awslogs</span><span class="p">.</span><span class="nx">data</span><span class="p">,</span> <span class="dl">"</span><span class="s2">base64</span><span class="dl">"</span><span class="p">);</span>

  <span class="nx">zlib</span><span class="p">.</span><span class="nx">gunzip</span><span class="p">(</span><span class="nx">payload</span><span class="p">,</span> <span class="k">async</span> <span class="p">(</span><span class="nx">err</span><span class="p">,</span> <span class="nx">result</span><span class="p">)</span> <span class="o">=&gt;</span> <span class="p">{</span>
    <span class="k">if</span> <span class="p">(</span><span class="nx">err</span><span class="p">)</span> <span class="p">{</span>
      <span class="nx">console</span><span class="p">.</span><span class="nx">error</span><span class="p">(</span><span class="nx">err</span><span class="p">);</span>
      <span class="nx">context</span><span class="p">.</span><span class="nx">fail</span><span class="p">(</span><span class="nx">err</span><span class="p">);</span>
    <span class="p">}</span> <span class="k">else</span> <span class="p">{</span>
      <span class="kd">const</span> <span class="nx">stringResult</span> <span class="o">=</span> <span class="nx">result</span><span class="p">.</span><span class="nx">toString</span><span class="p">(</span><span class="dl">"</span><span class="s2">utf-8</span><span class="dl">"</span><span class="p">);</span>
      <span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="dl">"</span><span class="s2">stringResult: </span><span class="dl">"</span><span class="p">,</span> <span class="nx">stringResult</span><span class="p">);</span>
      <span class="nx">context</span><span class="p">.</span><span class="nx">succeed</span><span class="p">();</span>
    <span class="p">}</span>
  <span class="p">});</span>
<span class="p">};</span>
</code></pre></div></div>

<p>Variable stringResult shows stringified version of the input, which looks like:</p>

<p><img src="https://user-images.githubusercontent.com/69557497/147313587-a1b7a0b5-5605-4dba-b5d1-e9ea1d1389c2.png" alt="CloudWatch logs" /></p>

<p>If your alert method requirement is webhook notifications, then you can just add a few lines of code for HTTP POST call in the lambda function. End of story.</p>

<p>Since SMS text message is a means of alert requirement, one more setup is required.</p>

<h2 id="setting-amazon-simple-notification-service-sns-for-sms-text-messaging">Setting Amazon Simple Notification Service (SNS) for SMS text messaging</h2>

<p>As of December 2021, mobile text messaging (SMS) feature is not supported in Seoul region (ap-northeast-2). So I changed my region to complete text messaging setup in SNS.</p>

<p>Supported Regions are listed here: <a href="https://docs.aws.amazon.com/sns/latest/dg/sns-supported-regions-countries.html">https://docs.aws.amazon.com/sns/latest/dg/sns-supported-regions-countries.html</a></p>

<p>After changing region to us-east-1, go to <strong><em>Amazon SNS</em></strong> –&gt; <strong><em>Mobile</em></strong> –&gt; <strong><em>Text messaging (SMS)</em></strong>. If Text messaging (SMS) is now showing in your region, it is likely that your region is not supporting this feature.</p>

<p><img src="https://user-images.githubusercontent.com/69557497/147314801-86759291-1fb1-457d-8ec6-5bfeffcbc8de.png" alt="SNS console" /></p>

<p>Under the Sandbox destination phone numbers, click <strong><em>Add phone number</em></strong> for adding recipients’ phone numbers. By default, you are in a sandbox mode which has a few restrictions such as:</p>

<ul>
  <li>Recipients’ phone numbers have to be verified</li>
  <li>1 USD is the maximum you can spend. (it suddenly stops sending messages after reaching the limit)</li>
</ul>

<p>Note: you can always request limit increase here: <a href="https://aws.amazon.com/premiumsupport/knowledge-center/sns-sms-spending-limit-increase/">https://aws.amazon.com/premiumsupport/knowledge-center/sns-sms-spending-limit-increase/</a></p>

<p>AWS support will get you out of sandbox as well upon the limit request.</p>

<p>After you add a recipient’s phone number for testing, now let’s go back to <strong><em>sms-sender</em></strong> lambda function in order to add some code for text messaging.</p>

<h2 id="publishing-text-message-code-in-sms-sender">Publishing text message code in <strong><em>sms-sender</em></strong></h2>

<p>Following is the complete lambda code for <strong><em>sms-sender</em></strong>, in which message sending feature is added.</p>

<div class="language-js highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">const</span> <span class="nx">zlib</span> <span class="o">=</span> <span class="nx">require</span><span class="p">(</span><span class="dl">"</span><span class="s2">zlib</span><span class="dl">"</span><span class="p">);</span>

<span class="kd">const</span> <span class="nx">AWS</span> <span class="o">=</span> <span class="nx">require</span><span class="p">(</span><span class="dl">"</span><span class="s2">aws-sdk</span><span class="dl">"</span><span class="p">);</span>
<span class="nx">AWS</span><span class="p">.</span><span class="nx">config</span><span class="p">.</span><span class="nx">update</span><span class="p">({</span> <span class="na">region</span><span class="p">:</span> <span class="dl">"</span><span class="s2">us-east-1</span><span class="dl">"</span> <span class="p">});</span>

<span class="nx">exports</span><span class="p">.</span><span class="nx">handler</span> <span class="o">=</span> <span class="p">(</span><span class="nx">event</span><span class="p">,</span> <span class="nx">context</span><span class="p">)</span> <span class="o">=&gt;</span> <span class="p">{</span>
  <span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="dl">"</span><span class="s2">event: </span><span class="dl">"</span><span class="p">,</span> <span class="nx">JSON</span><span class="p">.</span><span class="nx">stringify</span><span class="p">(</span><span class="nx">event</span><span class="p">));</span>
  <span class="kd">const</span> <span class="nx">payload</span> <span class="o">=</span> <span class="nx">Buffer</span><span class="p">.</span><span class="k">from</span><span class="p">(</span><span class="nx">event</span><span class="p">.</span><span class="nx">awslogs</span><span class="p">.</span><span class="nx">data</span><span class="p">,</span> <span class="dl">"</span><span class="s2">base64</span><span class="dl">"</span><span class="p">);</span>

  <span class="nx">zlib</span><span class="p">.</span><span class="nx">gunzip</span><span class="p">(</span><span class="nx">payload</span><span class="p">,</span> <span class="k">async</span> <span class="p">(</span><span class="nx">err</span><span class="p">,</span> <span class="nx">result</span><span class="p">)</span> <span class="o">=&gt;</span> <span class="p">{</span>
    <span class="k">if</span> <span class="p">(</span><span class="nx">err</span><span class="p">)</span> <span class="p">{</span>
      <span class="nx">console</span><span class="p">.</span><span class="nx">error</span><span class="p">(</span><span class="nx">err</span><span class="p">);</span>
      <span class="nx">context</span><span class="p">.</span><span class="nx">fail</span><span class="p">(</span><span class="nx">err</span><span class="p">);</span>
    <span class="p">}</span> <span class="k">else</span> <span class="p">{</span>
      <span class="kd">const</span> <span class="nx">stringResult</span> <span class="o">=</span> <span class="nx">result</span><span class="p">.</span><span class="nx">toString</span><span class="p">(</span><span class="dl">"</span><span class="s2">utf-8</span><span class="dl">"</span><span class="p">);</span>
      <span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="dl">"</span><span class="s2">stringResult: </span><span class="dl">"</span><span class="p">,</span> <span class="nx">stringResult</span><span class="p">);</span>
      <span class="k">await</span> <span class="nx">sendMessages</span><span class="p">(</span><span class="nx">JSON</span><span class="p">.</span><span class="nx">parse</span><span class="p">(</span><span class="nx">stringResult</span><span class="p">));</span>
      <span class="nx">context</span><span class="p">.</span><span class="nx">succeed</span><span class="p">();</span>
    <span class="p">}</span>
  <span class="p">});</span>
<span class="p">};</span>

<span class="kd">const</span> <span class="nx">sendMessages</span> <span class="o">=</span> <span class="k">async</span> <span class="p">(</span><span class="nx">data</span><span class="p">)</span> <span class="o">=&gt;</span> <span class="p">{</span>
  <span class="kd">const</span> <span class="nx">sns</span> <span class="o">=</span> <span class="k">new</span> <span class="nx">AWS</span><span class="p">.</span><span class="nx">SNS</span><span class="p">();</span>
  <span class="kd">const</span> <span class="nx">recipientNumbers</span> <span class="o">=</span> <span class="p">[</span><span class="nx">YOUR_NUMBERS</span><span class="p">];</span>

  <span class="k">try</span> <span class="p">{</span>
    <span class="k">for</span> <span class="p">(</span><span class="kd">const</span> <span class="nx">PhoneNumber</span> <span class="k">of</span> <span class="nx">recipientNumbers</span><span class="p">)</span> <span class="p">{</span>
      <span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="dl">"</span><span class="s2">sending to: </span><span class="dl">"</span> <span class="o">+</span> <span class="nx">PhoneNumber</span><span class="p">);</span>
      <span class="k">await</span> <span class="nx">sns</span>
        <span class="p">.</span><span class="nx">publish</span><span class="p">({</span>
          <span class="na">Message</span><span class="p">:</span> <span class="s2">`Please check </span><span class="p">${</span><span class="nx">data</span><span class="p">.</span><span class="nx">logGroup</span><span class="p">}</span><span class="s2">\n</span><span class="p">${</span><span class="nx">data</span><span class="p">.</span><span class="nx">logStream</span><span class="p">}</span><span class="s2">`</span><span class="p">,</span>
          <span class="nx">PhoneNumber</span><span class="p">,</span>
        <span class="p">})</span>
        <span class="p">.</span><span class="nx">promise</span><span class="p">();</span>
    <span class="p">}</span>
  <span class="p">}</span> <span class="k">catch</span> <span class="p">(</span><span class="nx">err</span><span class="p">)</span> <span class="p">{</span>
    <span class="nx">console</span><span class="p">.</span><span class="nx">error</span><span class="p">(</span><span class="dl">"</span><span class="s2">ERROR: </span><span class="dl">"</span><span class="p">,</span> <span class="nx">err</span><span class="p">);</span>
  <span class="p">}</span>
<span class="p">};</span>
</code></pre></div></div>

<p>Almost done. One last adjustment is left. Our lambda role needs a permission to send text messages.</p>

<h2 id="iam-role-for-text-messaging">IAM role for text messaging</h2>

<p>Let’s move to IAM role for <strong><em>sms-sender</em></strong> lambda function.</p>

<p><img src="https://user-images.githubusercontent.com/69557497/147316051-46eea916-4d87-4438-81e3-ab71f3bb629f.png" alt="IAM role for sms-sender" /></p>

<p>In the lambda role, click <strong><em>Attach policies</em></strong> –&gt; check <strong><em>AmazonSNSFullAccess</em></strong> –&gt; click <strong><em>Attach policy</em></strong> button.</p>

<h2 id="final-testing">Final testing</h2>

<p>Now all of our components are set up and ready. Go back to <strong><em>cloudwatch-alert-test</em></strong> lambda function and run error test case. Wait a few seconds, you should receive a text message if you set up everything correctly. You can modify the message to any way that you like to. Note that if your message is longer than 160 characters, they are split into separate messages.</p>

<h2 id="conclusion">Conclusion</h2>

<p>You can design your alert system in various ways by applying different log patterns without much hassle utilizing <strong><em>CloudWatch subscription filters</em></strong>.</p>

<p>Getting alerts if something goes wrong is very useful. But it might be annoying if our phones vibrate too frequently than it should be. Yes, it is very tricky to get the balance right. I know <strong><em>DivideByZeroException</em></strong> is not an appropriate case to get SMS text messaging alert :)</p>

<p>Each system has different reliability requirements. When to fire alarm should be designed carefully according to the requirements. Avoiding false alarms is crucial point to consider as well.</p>

<p>Happy Christmas and to our reliable systems!</p>]]></content><author><name></name></author><category term="[&quot;AWS&quot;]" /><category term="AWS" /><category term="CloudWatch" /><category term="Lambda" /><category term="Serverless" /><summary type="html"><![CDATA[This blog post explains how to send SMS text message based on CloudWatch log pattern]]></summary></entry></feed>