<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Melon on Medium]]></title>
        <description><![CDATA[Stories by Melon on Medium]]></description>
        <link>https://medium.com/@melon.ruet?source=rss-a8e972b6b5bd------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*ZMALd9mJwRHMdKUuEEwqfw.jpeg</url>
            <title>Stories by Melon on Medium</title>
            <link>https://medium.com/@melon.ruet?source=rss-a8e972b6b5bd------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 00:12:24 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@melon.ruet/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Terraform support for job templates and output presets of AWS Elemental MediaConvert]]></title>
            <link>https://medium.com/craftsmenltd/terraform-support-for-job-templates-and-output-presets-of-aws-elemental-mediaconvert-6a76bda4f487?source=rss-a8e972b6b5bd------2</link>
            <guid isPermaLink="false">https://medium.com/p/6a76bda4f487</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[aws-media-services]]></category>
            <category><![CDATA[infrastructure-as-code]]></category>
            <category><![CDATA[media-convert]]></category>
            <category><![CDATA[terraform]]></category>
            <dc:creator><![CDATA[Melon]]></dc:creator>
            <pubDate>Fri, 11 Sep 2020 04:08:16 GMT</pubDate>
            <atom:updated>2020-09-11T04:08:16.185Z</atom:updated>
            <content:encoded><![CDATA[<p><a href="https://aws.amazon.com/mediaconvert/">AWS Elemental MediaConvert</a> is a media <a href="https://en.wikipedia.org/wiki/Transcoding">transcoding</a> service of AWS. For supporting vast VOD service, MediaConvert is very useful and reliable. <a href="https://www.terraform.io/">Terraform</a> is an <a href="https://en.wikipedia.org/wiki/Infrastructure_as_code">Infrastructure as Code (IaC)</a> tool which supports multiple Cloud platforms like AWS, Azure, and GCP. Unfortunately due to a lot of configurations of MediaConvert, terraform does not support MediaConvert resource and settings management yet. In this tutorial, we are going to take a look at how can we achieve this.</p><h4>MediaConvert Job Templates</h4><figure><img alt="MediaConvert at AWS console" src="https://cdn-images-1.medium.com/max/765/1*PLHK5q7jjnUnY_8RcRSlcw.png" /></figure><p>The job template is a part of MediaConvert. If we create some templates with input(s) and output(s) of transcoding, we can use that for every time to transcoding some files. Let’s say your platform needs 3 types of video outputs with different bitrate and resolution. So we can save that template and reuse for the next transcoding jobs. There is another section called <strong>Output presets </strong>in MediaConvert console. These preset store output configurations of transcoding jobs. And in the template, we can use one or more output presets.</p><h4>Setting the Goal</h4><p>So our plan is to manage MediaConvert templates with terraform as terraform does not support MediaConvert. So we will create templates and output presets at the time of <strong>Terraform apply </strong>command and destroy with <strong>Terraform destroy </strong>command.</p><h4>MediaConvert presets and template</h4><p>For the MediaConvert preset, we will use one preset for video and one preset for audio for simplicity. And we will use <a href="https://www.microsoft.com/silverlight/smoothstreaming/">MS Smooth streaming</a> protocol for transcoding.</p><p>A1 — Audio preset<br>P1 — Video preset</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/87aead9fa171497cb04e6f017059e21f/href">https://medium.com/media/87aead9fa171497cb04e6f017059e21f/href</a></iframe><p>For the MediaConvert job template, we are going to use the following configuration. The presets A1 and P1 are mentioned in MS Smooth output settings.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6fce22bf11102c56b69725b9d86ac9d2/href">https://medium.com/media/6fce22bf11102c56b69725b9d86ac9d2/href</a></iframe><h4>Terraform Configs</h4><p>For each AWS region, there is a separate MediaConvert endpoint URL. Our first goal is to grab that endpoint URL because to get create preset and template we need MediaConvert endpoint URL. We are going to use AWS CLI for that. Let’s install that from <a href="https://aws.amazon.com/cli/">here</a>. Then we will write a simple bash script to grab the MediaConvert endpoint URL. We need to format the output with jq — A JSON processor (will explain why after some moments). Let&#39;s install jq from <a href="https://stedolan.github.io/jq/">here</a>. Then our script will be like this in <strong>mediaconvert_url.sh </strong>file</p><pre><strong># mediaconvert_url.sh</strong></pre><pre>#!/bin/bash<strong><br></strong>set -e<br><br>eval &quot;$(jq -r &#39;@sh &quot;export profile=\(.profile) region=\(.region)&quot;&#39;)&quot;<br>aws mediaconvert describe-endpoints --profile &quot;$profile&quot; --region &quot;$region&quot; | jq -r .Endpoints[0]</pre><p>Don’t forget to run</p><pre>chmod a+x mediaconvert_url.sh</pre><p>Now lets set AWS provider in <strong>provider.tf</strong></p><pre><strong># provider.tf</strong></pre><pre>provider &quot;aws&quot; {<br>  region = &quot;eu-west-1&quot;<br>  profile = <em>local</em>.aws_profile<br>}<br><br>locals {<br><em>//  This profile name used in multiple places<br>//  So keeping it in a local var<br>  </em>aws_profile = &quot;your-aws-profile&quot;<br>}<br><br><em>// For getting AWS region dynamically<br></em>data &quot;aws_region&quot; &quot;current&quot; {}</pre><p>Now we have to pass the AWS profile set by us and region to <strong>mediaconvert_url.sh</strong> to get the MediaConvert endpoint URL. So we are going to use an <a href="https://registry.terraform.io/providers/hashicorp/external/latest/docs/data-sources/data_source">external data source of Terraform</a> and run the <strong>mediaconvert_url.sh. </strong>But terraform external data source only accepts JSON formatted output. That’s why we are using jq to format the output of the <strong>AWS MediaConvert describe-endpoints </strong>command. Let’s add an external terraform source in <strong>mediaconvert_url.tf</strong></p><pre><strong># mediaconvert_url.tf</strong></pre><pre>locals {<br><em>//  Keeping the mediaconvert endpoint URL to a local var<br>  </em>mediaconvert_endpoint = <em>data</em>.external.mediaconvert_endpoint.result.Url<br>}<br><br><em>// Run external program using terraform&#39;s data external<br></em>data &quot;external&quot; &quot;mediaconvert_endpoint&quot; {<br>  program = [&quot;/bin/bash&quot;, &quot;-c&quot;, &quot;${<em>path</em>.module}/mediaconvert_url.sh&quot;]<br><br>  query = {<br>    profile = <em>local</em>.aws_profile<br>    region = <em>data</em>.aws_region.current.name<br>  }<br>}<br><br><em>// Terraform output - mediaconvert URL<br></em>output &quot;mediaconvert_endpoint&quot; {<br>  value = <em>local</em>.mediaconvert_endpoint<br>}</pre><p>Now let’s keep our presets in <strong>presets</strong> directory and MediaConvert templates in <strong>templates </strong>directory like this</p><figure><img alt="presets and templates directory" src="https://cdn-images-1.medium.com/max/408/1*Pb92tUD-yRujjc8kmqwLvw.png" /></figure><p>So we will use AWS CLI to create presets and job templates. But we will add this using a bash script. Also, our same bash script will be used to destroy. So a flag <strong>ACTION </strong>will be used to differentiate between creating and destroying. The script will look like this in <strong>mediaconvert.sh</strong> file.</p><pre><strong>#</strong> <strong>mediaconvert.sh</strong></pre><pre>#!/bin/bash<strong><br><br></strong>find presets/* -prune -type f | while IFS= read -r preset; do<br>  echo &quot;$preset&quot;<br>  PRESET_NAME=$(jq -r &#39;.Name&#39; &quot;$preset&quot;)<br>  PRESET_SETTINGS=$(jq &#39;.Settings&#39; &quot;$preset&quot;)<br><br>  if [ &quot;$ACTION&quot; = &quot;destroy&quot; ]; then<br>      aws mediaconvert delete-preset \<br>      --name &quot;$PRESET_NAME&quot; \<br>      --endpoint-url &quot;$MEDIACONVERT_URL&quot; \<br>      --profile &quot;$AWS_PROFILE&quot; \<br>      --region &quot;$REGION&quot;<br>  else<br>      aws mediaconvert create-preset \<br>      --name &quot;$PRESET_NAME&quot; \<br>      --settings &quot;$PRESET_SETTINGS&quot; \<br>      --endpoint-url &quot;$MEDIACONVERT_URL&quot; \<br>      --profile &quot;$AWS_PROFILE&quot; \<br>      --region &quot;$REGION&quot;<br>  fi<br>done<br><br>find templates/* -prune -type f | while IFS= read -r template; do<br>  echo &quot;$template&quot;<br>  TEMPLATE_NAME=$(jq -r &#39;.Name&#39; &quot;$template&quot;)<br>  TEMPLATE_SETTINGS=$(jq &#39;.Settings&#39; &quot;$template&quot;)<br><br>  if [ &quot;$ACTION&quot; = &quot;destroy&quot; ]; then<br>      aws mediaconvert delete-job-template \<br>      --name &quot;$TEMPLATE_NAME&quot; \<br>      --endpoint-url &quot;$MEDIACONVERT_URL&quot; \<br>      --profile &quot;$AWS_PROFILE&quot; \<br>      --region &quot;$REGION&quot;<br>  else<br>      aws mediaconvert create-job-template \<br>      --name &quot;$TEMPLATE_NAME&quot; \<br>      --settings &quot;$TEMPLATE_SETTINGS&quot; \<br>      --endpoint-url &quot;$MEDIACONVERT_URL&quot; \<br>      --profile &quot;$AWS_PROFILE&quot; \<br>      --region &quot;$REGION&quot;<br>  fi<br>done</pre><p>Also, don’t forget to run</p><pre>chmod a+x mediaconvert.sh</pre><p>As we can see that we have to pass environment variables ACTION, MEDIACONVERT_URL, AWS_PROFILE, and REGION. To do this we are going to use a <a href="https://www.terraform.io/docs/provisioners/local-exec.html">local-exe</a>c provisioner of Terraform in a <a href="https://registry.terraform.io/providers/hashicorp/null/latest/docs/resources/resource">null resource</a>. We are going to add 2 provisioner — one to create presets and template and another for destroy. And we will pass environment vars of <strong>mediaconvert.sh </strong>from this provisioners. Let’s do it in <strong>mediaconvert.tf</strong> file.</p><pre><strong># mediaconvert.tf</strong></pre><pre>resource &quot;null_resource&quot; &quot;mediaconvert_creation&quot; {<br>  <em>//Provisioner for creation<br>  </em>provisioner &quot;local-exec&quot; {<br>    when    = create<br>    command = &quot;./${<em>path</em>.module}/mediaconvert.sh&quot;<br><br>    environment = {<br>      ACTION           = &quot;create&quot;<br>      AWS_PROFILE      = <em>local</em>.aws_profile<br>      REGION           = <em>data</em>.aws_region.current.name<br>      MEDIACONVERT_URL = <em>local</em>.mediaconvert_endpoint<br>    }<br>  }<br><br>    <em>// Provisioner for destroying<br>    </em>provisioner &quot;local-exec&quot; {<br>      when = destroy<br>      command = &quot;./${<em>path</em>.module}/mediaconvert.sh&quot;<br><br>      environment = {<br>        ACTION = &quot;destroy&quot;<br>        AWS_PROFILE = <em>local</em>.aws_profile<br>        REGION = <em>data</em>.aws_region.current.name<br>        MEDIACONVERT_URL = <em>local</em>.mediaconvert_endpoint<br>      }<br>    }<br>}</pre><p>Finally, our project will look like this</p><pre>tree</pre><pre>.<br>├── mediaconvert.sh<br>├── mediaconvert.tf<br>├── mediaconvert_url.sh<br>├── mediaconvert_url.tf<br>├── presets<br>│   ├── aws-mediaconvert-preset-a-1.json<br>│   └── aws-mediaconvert-preset-p-1.json<br>├── provider.tf<br>├── templates<br>   └── aws-mediaconvert-template.json</pre><h4><strong>Time to test 😹</strong></h4><p>Now lets test with</p><pre>terraform init   # for initialization terraform<br>terraform plan   # planning what to create and/or destroy<br>terraform apply -auto-approve     # create all<br>terraform destroy -auto-approve   # To destroy all</pre><p>After terraform apply we can see our output presets and job template in the AWS console</p><figure><img alt="MediaConvert output preset" src="https://cdn-images-1.medium.com/max/1024/1*-r4AHJbKPt754G42sm_9yw.png" /></figure><figure><img alt="MediaConvert job template" src="https://cdn-images-1.medium.com/max/1024/1*bGwf574KcG7o6wbBFdWvvA.png" /></figure><p>Finally, you can run a MediaConvert job with the template to test it. Before that don’t forget to create an IAM role for MediaConvert with necessary S3 bucket permission.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6a76bda4f487" width="1" height="1" alt=""><hr><p><a href="https://medium.com/craftsmenltd/terraform-support-for-job-templates-and-output-presets-of-aws-elemental-mediaconvert-6a76bda4f487">Terraform support for job templates and output presets of AWS Elemental MediaConvert</a> was originally published in <a href="https://medium.com/craftsmenltd">Craftsmen — Software Maestros</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A journey to AWS Lambda integration testing with Python, Localstack and Terraform]]></title>
            <link>https://medium.com/craftsmenltd/a-journey-to-aws-lambda-integration-testing-with-python-localstack-and-terraform-2f17043c7dda?source=rss-a8e972b6b5bd------2</link>
            <guid isPermaLink="false">https://medium.com/p/2f17043c7dda</guid>
            <category><![CDATA[localstack]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[terraform]]></category>
            <category><![CDATA[aws-lambda]]></category>
            <category><![CDATA[integration-testing]]></category>
            <dc:creator><![CDATA[Melon]]></dc:creator>
            <pubDate>Sun, 30 Aug 2020 04:36:01 GMT</pubDate>
            <atom:updated>2020-08-31T15:50:16.818Z</atom:updated>
            <content:encoded><![CDATA[<h3>A journey to AWS Lambda integration testing with Python, Localstack, and Terraform</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*NlfyArijVlnMd20F" /><figcaption>Photo by <a href="https://unsplash.com/@thisisengineering?utm_source=medium&amp;utm_medium=referral">ThisisEngineering RAEng</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>To start with <a href="https://en.wikipedia.org/wiki/Unit_testing">unit testing</a> for <a href="https://aws.amazon.com/lambda/">AWS Lambda</a>, we can just choose a testing framework and start writing our beautiful unit tests. For testing AWS services we also can use some mock tools like <a href="https://pypi.org/project/moto/">moto</a>. But what about <a href="https://en.wikipedia.org/wiki/Integration_testing">integration testing</a>? A solution may be to deploy with the <a href="https://en.wikipedia.org/wiki/Continuous_deployment">Continuous Deployment</a> tool and run some test code against real AWS services. But there are some problems:</p><ul><li>It takes more time to deploy every time</li><li>Running test code against AWS takes more time</li><li>Increases the AWS bills</li></ul><p>So one good solution could be using a local infrastructure that resembles the same as AWS real infrastructure. So here comes our friend <a href="https://localstack.cloud/">Localstack</a> to solve the problem. And today we will take a look at how we can use Localstack for integration testing of AWS Lambda.</p><h3>Prerequisite</h3><ul><li><a href="https://www.python.org/">Python</a> for lambda code</li><li><a href="https://www.python.org/">Python</a> for test code</li><li><a href="https://pypi.org/project/pipenv/">Pipenv</a> to manage python virtual environment</li><li><a href="https://www.terraform.io/">Terraform</a>, an <a href="https://en.wikipedia.org/wiki/Infrastructure_as_code">IaC</a> tool to deploy lambda at the <a href="https://localstack.cloud/">Localstack</a></li><li><a href="https://localstack.cloud/">Localstack</a> to use AWS infrastructure locally</li></ul><h3>Background</h3><p><a href="https://medium.com/craftsmenltd/automate-python-libraries-deployment-at-aws-lambda-layer-from-pipfile-with-terraform-d28de0eb765f">In one of my medium posts</a>, the way of deploying python codes at Lambda with python packages at the lambda layer was described. So here we will not describe that part here. Also as Lambda Layer is a part of the <a href="https://github.com/localstack/localstack#overview"><strong>pro version of Localstack</strong></a>, we will avoid the lambda layer. The only change will be rather deploying to real infrastructure, we will deploy to Localstack. So let’s start with sharing the end result <a href="https://github.com/melon-ruet/lambda-testing-localstack">GitHub repository</a> first 😄 🤫</p><h3>The skeleton</h3><p>Let’s start with installing pipenv from <a href="https://pipenv-fork.readthedocs.io/en/latest/install.html">here</a>. Then we will install terraform from <a href="https://learn.hashicorp.com/tutorials/terraform/install-cli">here</a>.</p><pre># Create project directory <br><strong>mkdir lambda-testing-localstack<br>cd lambda-testing-localstack</strong></pre><pre># Create directory for lambda codes<br><strong>mkdir lambda</strong></pre><pre># Add handler.py file in lambda directory<br><strong>touch lambda/handler.py</strong></pre><pre># Create directory for terraform<br><strong>mkdir terraform</strong></pre><pre># Add Pipfile in project root directory<br><strong>touch Pipfile</strong></pre><pre># Create directory for test code<br><strong>mkdir tests</strong></pre><pre># Create test code python file<br><strong>touch tests/test_lambda.py</strong></pre><pre># So the skeleton will look like this<br><strong>tree<br></strong>.<br>├── lambda<br>│   └── handler.py<br>├── Pipfile<br>├── terraform<br>└── tests<br>    └── test_lambda.py</pre><h3>Add requirements</h3><p>Let’s add some python requirements and python version 3.8 in <strong>Pipfile</strong></p><pre>[[source]]<br>name = &quot;pypi&quot;<br>url = &quot;https://pypi.org/simple&quot;<br>verify_ssl = <em>true<br><br></em>[dev-packages]<br>localstack = &quot;==0.11.3.3&quot;<br>pipenv = &quot;==2020.8.13&quot;<br><em># Below packages are required to start localstack from python code<br></em>h11 = &quot;==0.10.0&quot;<br>amazon_kclpy = &quot;==2.0.1&quot;<br>quart = &quot;==0.13.0&quot;<br>flask_cors = &quot;==3.0.8&quot;<br>moto = &quot;==1.3.14&quot;<br>moto-ext = &quot;&gt;=1.3.15.12&quot;<br>crontab = &quot;==0.22.9&quot;<br>pyOpenSSL = &quot;==19.1.0&quot;<br><br>[requires]<br>python_version = &quot;3.8&quot;</pre><p>As Localstack will not be in with lambda codes, so it is added in dev-packages section. Run</p><pre>pipenv install --dev</pre><p>to initiate a virtual environment and install packages with <strong>pipenv</strong></p><h3>Add Lambda Code</h3><p>We will add a very simple code. Our lambda will just get the webpage <a href="https://example.com/">https://example.com</a> and return the page source as text.</p><pre># lambda/lambda_handler.py</pre><pre>import logging<br>import urllib.request<br><br>LOGGER = logging.getLogger()<br>LOGGER.setLevel(logging.INFO)<br><br><br>def lambda_handler(event, context):<br>    with urllib.request.urlopen(<strong>&#39;https://example.com&#39;</strong>) as response:<br>        html = response.read().decode(<strong>&#39;utf-8&#39;</strong>)<br>        LOGGER.info(html)<br>        return html</pre><h3>Add Files to deploy Lambda</h3><p>Let’s add a terraform variable for the lambda function name. So from our test code, we will provide the lambda function name and then test it to make the testing more dynamic.</p><pre># terraform/vars.tf</pre><pre>variable &quot;lambda_function_name&quot; {<br>  type = string<br>  default = &quot;test-lambda-function&quot;<br>}</pre><p>Now add terraform code for lambda at <a href="https://github.com/melon-ruet/lambda-testing-localstack/blob/master/terraform/lambda.tf"><strong>terraform/lambda.tf</strong></a></p><pre># terraform/lambda.tf</pre><pre><em>// Zip lambda function codes<br></em>data &quot;archive_file&quot; &quot;lambda_zip_file&quot; {<br>  output_path = &quot;${<em>path</em>.module}/lambda_zip/lambda.zip&quot;<br>  source_dir  = &quot;${<em>path</em>.module}/../lambda&quot;<br>  excludes    = [&quot;__pycache__&quot;, &quot;*.pyc&quot;]<br>  type        = &quot;zip&quot;<br>}</pre><pre><br><em>// IAM Policy document for lambda assume role<br></em>data &quot;aws_iam_policy_document&quot; &quot;lambda_assume_role&quot; {<br>  version = &quot;2012-10-17&quot;<br><br>  statement {<br>    sid    = &quot;LambdaAssumeRole&quot;<br>    effect = &quot;Allow&quot;<br>    actions = [<br>      &quot;sts:AssumeRole&quot;<br>    ]<br>    principals {<br>      identifiers = [<br>        &quot;lambda.amazonaws.com&quot;<br>      ]<br>      type = &quot;Service&quot;<br>    }<br>  }<br>}</pre><pre><br><em>// Lambda IAM role<br></em>resource &quot;aws_iam_role&quot; &quot;lambda_role&quot; {<br>  name               = &quot;test-lambda-role&quot;<br>  assume_role_policy = <em>data</em>.aws_iam_policy_document.lambda_assume_role.json<br><br>  lifecycle {<br>    create_before_destroy = true<br>  }<br>}<br></pre><pre><em>// Lambda function terraform code<br></em>resource &quot;aws_lambda_function&quot; &quot;lambda_function&quot; {<br>  function_name    = <em>var</em>.lambda_function_name<br>  filename         = <em>data</em>.archive_file.lambda_zip_file.output_path<br>  source_code_hash = <em>data</em>.archive_file.lambda_zip_file.output_base64sha256<br>  handler          = &quot;handler.lambda_handler&quot;<br>  role             = aws_iam_role.lambda_role.arn<br>  runtime          = &quot;python3.8&quot;<br><br>  lifecycle {<br>    create_before_destroy = true<br>  }<br>}</pre><p>Now we are going to add <a href="https://github.com/melon-ruet/lambda-testing-localstack/blob/master/terraform/localstack.tf"><strong>terraform/localstack.tf</strong></a><strong> </strong>to which will tell terraform to use Localstack for deployment</p><pre># terraform/localstack.tf</pre><pre>provider &quot;aws&quot; {<br>  region                      = &quot;eu-west-1&quot;<br>  access_key                  = &quot;fakekey&quot;<br>  secret_key                  = &quot;fakekey&quot;<br>  skip_credentials_validation = true<br>  skip_metadata_api_check     = true<br>  skip_requesting_account_id  = true<br>  s3_force_path_style         = true<br><br>  endpoints {<br>    lambda         = &quot;http://localhost:4566&quot;<br>    iam            = &quot;http://localhost:4566&quot;<br>  }<br>}</pre><h3>Deploy to Localstack with Terraform</h3><p>Now time to test deployment at LocalStack</p><pre># Start localstack service only for Lambda and IAM<strong><br>SERVICES=lambda,iam localstack start</strong></pre><pre># In another terminal <br># Terraform initialization<br><strong>terraform init</strong></pre><pre># Plan to build<br><strong>terraform plan</strong></pre><pre># Deploy all<br><strong>terraform apply -auto-approve</strong></pre><pre># Destroy all because we will make it automated as we <br># are going to implement automated test<br><strong>terraform destroy -auto-approve</strong></pre><pre># Kill the localstack service using <strong>Ctrl + C</strong> in 1st terminal</pre><h3>Automate Test Code</h3><p>Now time to automate the lambda testing. Our strategy:</p><ul><li>Deploy terraform to LocalStack from test code e.g python code</li><li>Execute lambda using boto3</li><li>Check if we get the webpage as text</li><li>Destroy infrastructure with terraform to LocalStack using test code</li></ul><p>Now add terraform helper function at <strong>tests/terraform_helper.py</strong> which will responsible for creating infrastructure at test start and destroy after the test</p><pre># tests/terraform_helper.py</pre><pre>import subprocess<br><br>import os<br><br>TERRAFORM_DIR_PATH = os.path.dirname(os.path.realpath(__file__)) + <strong>&quot;/../terraform/&quot;<br><br><br></strong>def terraform_init():<br>    <em>&quot;&quot;&quot;Terraform init command&quot;&quot;&quot;<br>    </em>tf_init = [<strong>&quot;terraform&quot;</strong>, <strong>&quot;init&quot;</strong>, TERRAFORM_DIR_PATH]<br>    subprocess.check_call(tf_init)<br><br><br>def create_resources():<br>    <em>&quot;&quot;&quot;Create a tf resource.&quot;&quot;&quot;<br>    </em>proc = subprocess.Popen(<strong>&quot;terraform apply -auto-approve &quot; </strong>+ TERRAFORM_DIR_PATH, shell=True)<br>    proc.wait()<br><br><br>def destroy_resources():<br>    <em>&quot;&quot;&quot;Destroy all tf resources.<br><br>    This method will destroy any resources it can find in the state file,<br>    and delete all resources from the state file.<br>    &quot;&quot;&quot;<br>    </em>tf_destroy = [<br>        <strong>&quot;terraform&quot;</strong>,<br>        <strong>&quot;destroy&quot;</strong>,<br>        <strong>&quot;-auto-approve&quot;</strong>,<br>        TERRAFORM_DIR_PATH<br>    ]<br>    subprocess.call(tf_destroy)<br><br>    tf_refresh = [<br>        <strong>&quot;terraform&quot;</strong>,<br>        <strong>&quot;refresh&quot;</strong>,<br>        TERRAFORM_DIR_PATH<br>    ]<br>    subprocess.call(tf_refresh)<br><br><br>def terraform_start():<br>    <em>&quot;&quot;&quot; teardown and create resources at the beginning of feature test &quot;&quot;&quot;<br>    </em>terraform_init()<br>    destroy_resources()<br>    return create_resources()</pre><p>Let’s add test code and we are going to use python’s unit test module to test our code</p><pre># tests/test_lambda.py</pre><pre>import os<br>import unittest<br><br>import boto3<br>from localstack.services import infra<br><br>from tests import terraform_helper<br><br><br>class AWSLambdaTest(unittest.TestCase):<br>    localstack_endpoint = <strong>&#39;http://localhost:4566&#39;<br>    </strong>lambda_function_name = <strong>&#39;dynamic-test-lambda-function&#39;<br><br>    </strong>def set_tf_var(self):<br>        os.environ[<strong>&quot;TF_VAR_lambda_function_name&quot;</strong>] = self.lambda_function_name<br><br>    def setUp(self):<br>        <em># Start localstack <br>        </em>infra.start_infra(apis=[<strong>&#39;lambda&#39;</strong>, <strong>&#39;iam&#39;</strong>, <strong>&#39;cloudwatch&#39;</strong>], asynchronous=True)<br>        self.set_tf_var()<br>        terraform_helper.terraform_start()<br><br>    def test_lambda_response(self):<br>        client = boto3.client(<br>            service_name=<strong>&#39;lambda&#39;</strong>,<br>            endpoint_url=self.localstack_endpoint<br>        )<br>        response = client.invoke(<br>            FunctionName=self.lambda_function_name,<br>            InvocationType=<strong>&#39;RequestResponse&#39;<br>        </strong>)<br>        assert response[<strong>&#39;StatusCode&#39;</strong>] == 200<br>        assert response[<strong>&#39;Payload&#39;</strong>]<br>        html = response[<strong>&#39;Payload&#39;</strong>].read().decode(<strong>&#39;utf-8&#39;</strong>)<br>        <em># Check if &quot;Example Domain&quot; text exists in example.com<br>        </em>assert <strong>&#39;Example Domain&#39; </strong>in html<br><br>    def tearDown(self):<br>        terraform_helper.destroy_resources()<br>        <em># Stop localstack<br>        </em>infra.stop_infra()<br><br><br>if __name__ == <strong>&#39;__main__&#39;</strong>:<br>    unittest.main()</pre><p>Finally, the project will look like this</p><pre><strong>tree<br></strong>.<br>├── lambda<br>│   └── handler.py<br>├── Pipfile<br>├── Pipfile.lock<br>├── terraform<br>│   ├── lambda.tf<br>│   ├── localstack.tf<br>│   └── vars.tf<br>└── tests<br>    ├── __init__.py<br>    ├── terraform_helper.py<br>    └── test_lambda.py</pre><h3>Time to test the Test</h3><p>Now come to the moment of playing 🎻</p><p>As we implemented the tests with the unit test module, we can run the test using</p><pre>pipenv shell<br>python -m unittest</pre><p>After a lot of logs we can see final output like this</p><pre>.<br>-------------------------------------------------------<br>Ran 1 test in 36.943s</pre><pre>OK</pre><h3>⚠️ WARNING</h3><p>Localstack is growing very faster. So if it works today may break tomorrow if the required packages are not fixed. So please try to fix all the packages version in Pipfile. Sometimes it may require some python packages to start various services like DynamoDB or StepFuntions. Add those at Pipfile accordingly.</p><h3>Final codes</h3><p>Again mentioning the GitHub repository:</p><p><a href="https://github.com/melon-ruet/lambda-testing-localstack"><strong><em>https://github.com/melon-ruet/lambda-testing-localstack</em></strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2f17043c7dda" width="1" height="1" alt=""><hr><p><a href="https://medium.com/craftsmenltd/a-journey-to-aws-lambda-integration-testing-with-python-localstack-and-terraform-2f17043c7dda">A journey to AWS Lambda integration testing with Python, Localstack and Terraform</a> was originally published in <a href="https://medium.com/craftsmenltd">Craftsmen — Software Maestros</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deal with change of field data type of PynamoDB, an ORM of DynamoDB]]></title>
            <link>https://medium.com/craftsmenltd/deal-with-change-of-field-data-type-of-pynamodb-an-orm-of-dynamodb-67690323d285?source=rss-a8e972b6b5bd------2</link>
            <guid isPermaLink="false">https://medium.com/p/67690323d285</guid>
            <category><![CDATA[pynamodb]]></category>
            <category><![CDATA[aws-dynamodb]]></category>
            <category><![CDATA[boto3]]></category>
            <category><![CDATA[motos]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Melon]]></dc:creator>
            <pubDate>Wed, 26 Aug 2020 12:26:00 GMT</pubDate>
            <atom:updated>2020-08-26T12:26:00.860Z</atom:updated>
            <content:encoded><![CDATA[<h3>Deal with the change of field data type of PynamoDB, an ORM of DynamoDB</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ywd_QK_ptvoPt5Tk0PAYBA.jpeg" /><figcaption>Source (Free to use): <a href="https://www.pexels.com/photo/interior-of-office-building-325229/">https://www.pexels.com/photo/interior-of-office-building-325229/</a></figcaption></figure><p><a href="https://pynamodb.readthedocs.io/">PynamoDB</a>, with a Python interface, is a great <a href="https://en.wikipedia.org/wiki/Object-relational_mapping">ORM</a> for <a href="https://aws.amazon.com/dynamodb/">AWS DynamoDB</a>. DynamoDB is a <a href="https://en.wikipedia.org/wiki/NoSQL">NoSQL</a> database with scalability and security and it has awesome <a href="https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/HowItWorks.API.html">API</a> and <a href="https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/GettingStarted.html">SDKs</a>. PynamoDB wraps the underneath APIs of DynamoDB and gives a beautiful <a href="https://www.dictionary.com/browse/pythonic">pythonic</a> way to use DynamoDB.</p><p>In real-world our DB fields are not constant. It can change with the requirements update of our project. The hard part is when you have to maintain the old and new features. For example, a field data type can change from <a href="https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/HowItWorks.NamingRulesDataTypes.html#HowItWorks.DataTypes">String to Binary</a>. So if any API e.g. <a href="https://en.wikipedia.org/wiki/Representational_state_transfer">REST API</a> with versioning is working with DynamoDB, you have to accept both old data type (String) and new data type (Binary). We are going to find a solution in such a case.</p><h4>Setting the goal</h4><p>Let’s start with setting a goal. Assume we have a field with Dynamo data type List. But after times it changes to Map. So we will do</p><ul><li>Accept Map object and save to DynamoDB</li><li>Accept List object and change it to Map according to requirement and save to DynamoDB as our field changed to Map</li><li>Return Map object according to requirement change</li></ul><h4>Setting the project</h4><p>Let’s add a couple of files to do our task.</p><pre># Add project folder<br><strong>mkdir change-field-ddb</strong><br><strong>cd change-field-ddb</strong></pre><pre># Add Pipfile for requirements mange with <a href="https://pipenv-fork.readthedocs.io/">pipenv</a><br><strong>touch Pipfile</strong></pre><pre># For Custom PynamoDB attributes<br><strong>touch attributes.py</strong></pre><pre># Add models.py to add pynamo model<br><strong>touch models.py</strong></pre><pre># To test everything<br><strong>touch test.py</strong></pre><h4>Add python requirements</h4><p>Add following requirements to <strong>Pipfile</strong></p><pre>[dev-packages]<br>pipenv = &quot;==2020.8.13&quot;<br>moto = &quot;==1.3.14&quot;<br><br>[packages]<br>pynamodb = &quot;==4.3.2&quot;<br><br>[requires]<br>python_version = &quot;3.8&quot;</pre><p>Now initiate pipenv with</p><pre>pipenv install</pre><p>Now the project will look like</p><pre><strong>tree</strong><br>.<br>├── attributes.py<br>├── models.py<br>├── Pipfile<br>├── Pipfile.lock<br>└── test.py</pre><h4>The changed datatype</h4><p>Let&#39;s assume our previous datatype (List) for a field <strong>result</strong> is</p><pre>[3.75, 3.17, 3.90, 3.67, .......]</pre><p>So the <strong>result </strong>stores CGPA of a student from 1st semester to final semester e.g. <strong>result[0]</strong> as 1st semester, <strong>result[1] </strong>as 2nd semester, and so on. But we will make it better (Map) at the updated version</p><pre>{<br>    <strong>&#39;semester 1&#39;</strong>: 3.75,<br>    <strong>&#39;semester 2&#39;</strong>: 3.17,<br>    <strong>&#39;semester 3&#39;</strong>: 3.90,<br>    <strong>&#39;semester 4&#39;</strong>: 3.67,<br>    ..................<br>}</pre><h4><strong>PynamoDB attributes</strong></h4><p>Add the custom PynamoDB attribute to accept old (List) and new (Map) attribute and saves only as Map. But at return time it will return old (List) data as Map and also new data as Map. Also, we are going to use custom <strong>UUIDAttribute </strong>which will be used as a hash key.</p><pre># attributes.py</pre><pre>import uuid<br><br>import pynamodb.attributes<br><br><br><em># UUID  Attribute will use as Dynamo hash key<br></em>class UUIDAttribute(pynamodb.attributes.UnicodeAttribute):<br><br>    def serialize(self, value):<br>        return super().serialize(str(value))<br><br>    def deserialize(self, value):<br>        return uuid.UUID(super().deserialize(value))<br><br><br><em># Add custom attribute to serialize and deserialize data<br></em>class ResultAttribute(pynamodb.attributes.MapAttribute):<br><br>    @classmethod<br>    def is_raw(cls):<br>        <em># Set to use as AttributeContainer<br>        # https://pynamodb.readthedocs.io/en/latest/api.html#pynamodb.attributes.MapAttribute<br>        </em>return True<br><br>    @staticmethod<br>    def _parse_value(values):<br>        return {<br>            <strong>f&#39;semester </strong>{idx+1}<strong>&#39;</strong>: val for idx, val in enumerate(values)<br>        }<br><br>    def serialize(self, values):<br>        <em># Convert python list to native pynamo<br>        </em>if isinstance(values, (list, tuple)):<br>            values = self._parse_value(values)<br>        return super().serialize(values)<br><br>    def get_value(self, value):<br>        try:<br>            <em># Convert from<br>            # {&#39;L&#39;: [{&#39;N&#39;: &#39;3.75&#39;}, {&#39;N&#39;: &#39;3.17&#39;}]}<br>            # to<br>            # {&#39;M&#39;: {&#39;semester 1&#39;: {&#39;N&#39;: &#39;3.75&#39;}, &#39;semester 2&#39;: {&#39;N&#39;: &#39;3.17&#39;}}}<br>            </em>value = {<strong>&#39;M&#39;</strong>: self._parse_value(value[<strong>&#39;L&#39;</strong>])}<br>        except (KeyError, TypeError):<br>            pass<br>        return super().get_value(value)</pre><h4>The PynamoDB Model</h4><p>We are going to start with a simple PynamoDB Model only with 2 fields</p><pre># models.py</pre><pre>import uuid<br><br>import pynamodb.models<br>import pynamodb.attributes<br><br>from attributes import UUIDAttribute, ResultAttribute<br><br><br>class ResultModel(pynamodb.models.Model):<br>    id = UUIDAttribute(hash_key=True, default=uuid.uuid4)<br>    result = ResultAttribute()<br><br>    class Meta:<br>        table_name = <strong>&quot;test-ddb-table&quot;</strong></pre><h4>Time to Test</h4><p>Add some tests in test.py</p><pre>from decimal import Decimal<br><br>from decimal import Decimal<br><br>import boto3<br>import moto<br><br>from models import ResultModel<br><br>with moto.mock_dynamodb2():<br>    region = <strong>&#39;eu-west-1&#39;<br>    </strong>ResultModel.Meta.region = region<br>    ResultModel.create_table(wait=True)<br><br>    <em># Data<br>    </em>result_map = {<br>        <strong>&#39;semester 1&#39;</strong>: 3.75,<br>        <strong>&#39;semester 2&#39;</strong>: 3.17,<br>        <strong>&#39;semester 3&#39;</strong>: 3.90,<br>        <strong>&#39;semester 4&#39;</strong>: 3.67<br>    }<br>    result_list = [3.75, 3.17, 3.90, 3.67]<br><br>    <em># Insert as Map with PynamoDB<br>    </em>result1 = ResultModel(result=result_map)<br>    result1.save()<br>    assert ResultModel.count() == 1<br>    result1_id = result1.id<br>    print(result1_id)<br><br>    <em># Retrieve the data from inserted as list<br>    </em>result1_retr = ResultModel.get(result1_id)<br>    assert result1_retr.result.attribute_values == result_map<br><br>    <em># Insert as list so it will convert and saved as map<br>    </em>result2 = ResultModel(result=result_list)<br>    result2.save()<br>    assert ResultModel.count() == 2<br>    result2_id = result2.id<br>    print(result2_id)<br><br>    <em># Retrieve the data from inserted as list<br>    </em>result2_retr = ResultModel.get(result2_id)<br>    assert result2_retr.result.attribute_values == result_map<br><br>    <em># Insert list value in result with boto3<br>    </em>dynamodb = boto3.resource(<strong>&#39;dynamodb&#39;</strong>, region)<br>    table = dynamodb.Table(ResultModel.Meta.table_name)<br><br>    <em># float is not supported by boto3. But decimal is supported. So converted to Decimal<br>    </em>item = [Decimal(str(v)) for v in result_list]<br>    <em># Updating item instead of creating because result is MapAttribute by default<br>    </em>table.update_item(<br>        Key={<strong>&#39;id&#39;</strong>: str(result1_id)},<br>        AttributeUpdates={<br>            <strong>&#39;result&#39;</strong>: {<strong>&#39;Value&#39;</strong>: item, <strong>&#39;Action&#39;</strong>: <strong>&#39;PUT&#39;</strong>}<br>        }<br>    )<br><br>    assert table.get_item(Key={<strong>&#39;id&#39;</strong>: str(result1_id)})[<strong>&#39;Item&#39;</strong>][<strong>&#39;result&#39;</strong>] == item<br><br>    <em># Retrieve the data that is a list in dynamodb<br>    </em>result1_retr = ResultModel.get(result1_id)<br>    assert result1_retr.result.attribute_values == result_map</pre><p>Run tests with</p><pre><strong>pipenv shell<br>python3 test.py</strong></pre><p>Full code can be found here:</p><pre><a href="https://github.com/melon-ruet/change-field-ddb">https://github.com/melon-ruet/change-field-ddb</a></pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=67690323d285" width="1" height="1" alt=""><hr><p><a href="https://medium.com/craftsmenltd/deal-with-change-of-field-data-type-of-pynamodb-an-orm-of-dynamodb-67690323d285">Deal with change of field data type of PynamoDB, an ORM of DynamoDB</a> was originally published in <a href="https://medium.com/craftsmenltd">Craftsmen — Software Maestros</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Automate python libraries deployment at AWS Lambda layer from Pipfile with Terraform]]></title>
            <link>https://medium.com/craftsmenltd/automate-python-libraries-deployment-at-aws-lambda-layer-from-pipfile-with-terraform-d28de0eb765f?source=rss-a8e972b6b5bd------2</link>
            <guid isPermaLink="false">https://medium.com/p/d28de0eb765f</guid>
            <category><![CDATA[iac]]></category>
            <category><![CDATA[pipenv]]></category>
            <category><![CDATA[serverless]]></category>
            <category><![CDATA[aws-lambda]]></category>
            <category><![CDATA[terraform]]></category>
            <dc:creator><![CDATA[Melon]]></dc:creator>
            <pubDate>Sat, 22 Aug 2020 17:31:07 GMT</pubDate>
            <atom:updated>2020-08-22T17:31:07.510Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*VDD-OL46OGf5IoVm" /><figcaption>Photo by <a href="https://unsplash.com/@franckinjapan?utm_source=medium&amp;utm_medium=referral">Franck V.</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><a href="https://aws.amazon.com/lambda">AWS Lambda</a>, a part of Amazon Web Services (AWS) is a <a href="https://en.wikipedia.org/wiki/Serverless_computing">serverless</a> computing service that works as <a href="https://en.wikipedia.org/wiki/Function_as_a_service">FaaS (Function as a Service)</a>. A FaaS is a service which provides users to develop and manage application service without thinking about infrastructure.</p><p><a href="https://www.hashicorp.com/products/terraform">Terraform</a> is an Infrastructure as Code (<a href="https://en.wikipedia.org/wiki/Infrastructure_as_code">IaC</a>) tool which is developed by <a href="https://www.hashicorp.com/">Hasi Corp</a> to manage resources of cloud services like AWS, Google Cloud, Azure, etc. It is open-source and developed by <a href="https://golang.org/">golang</a>.</p><p>It is always challenging to zip the codes and upload them for AWS Lambda every time at the time of deployment. The more complex part is to upload codes of libraries e.g python libraries. At <a href="https://www.craftsmenltd.com/">Craftsmen</a>, we need to manage a lot of lambdas for various development purposes. So a smart solution for uploading lambda function code and libraries while deployment is a crying need.</p><p>Our approach is to upload function codes as function level and libraries in lambda layer. The reasons are <br>1. Share python libraries between lambdas<br>2. The console code editor can only visualize <a href="https://docs.aws.amazon.com/lambda/latest/dg/gettingstarted-limits.html">3MB of code</a>. So uploading libraries can make a chance to see codes in console editor.</p><h3>Setting the project</h3><p>Let’s start by setting the project skeleton. We are going to use <a href="https://docs.pipenv.org/">pipenv</a> because it’s more developer-friendly to maintain dev and release packages. First, we install pipenv from <a href="https://pipenv-fork.readthedocs.io/en/latest/install.html">here</a>. Then we will install terraform from <a href="https://learn.hashicorp.com/tutorials/terraform/install-cli">here</a></p><pre># Create a project directory<br><strong>mkdir lambda-with-terraform<br>cd lambda-with-terraform</strong></pre><pre># Create lambda code directory<br><strong>mkdir lambda</strong></pre><pre># Create Terraform directory<br><strong>mkdir terraform</strong></pre><pre># Add handler.py file in lambda directory<br><strong>touch lambda/handler.py</strong></pre><pre># Add Pipfile in project root directory<br><strong>touch Pipfile</strong></pre><pre># So our skeleton will look like this<br><strong>tree</strong></pre><pre>├── lambda<br>│   └── handler.py<br>├── Pipfile<br>└── terraform</pre><h4>Add python libraries</h4><p>We will only use a single library called <a href="https://requests.readthedocs.io/"><strong>requests</strong></a><strong> </strong>in [packages] and pipenv at [dev-packages]. Also, we are going to use <a href="https://www.python.org/downloads/release/python-380/"><strong>python 3.8</strong></a>. Let’s add all to <strong>Pipfile</strong>.</p><pre># Pipfile</pre><pre>[[source]]<br>name = &quot;pypi&quot;<br>url = &quot;<a href="https://pypi.org/simple">https://pypi.org/simple</a>&quot;<br>verify_ssl = true</pre><pre>[dev-packages]<br>pytest = &quot;==5.3.5&quot;<br>pipenv = &quot;==2020.8.13&quot;</pre><pre>[packages]<br>requests = &quot;==2.23.0&quot;</pre><pre>[requires]<br>python_version = &quot;3.8&quot;</pre><p>Initiate python virtual environment by pipenv with</p><pre>pipenv install</pre><p>This will add the <strong>Pipfile.lock </strong>file which contains information on all python packages.</p><h4>Add function code</h4><p>Let’s start with a simple lambda function which just gets a web page and log it.</p><pre># handler.py</pre><pre>import requests<br>import logging</pre><pre>LOGGER = logging.getLogger()<br>LOGGER.setLevel(logging.INFO)</pre><pre>def lambda_handler(event, context):<br>    response = requests.get(&quot;https://example.com&quot;)<br>    LOGGER.info(response.text)</pre><h4>Add Terraform code</h4><p>At first, we will add some files for Terraform</p><pre># Create file for lambda terraform codes<br><strong>touch terraform/lambda.tf</strong></pre><pre># Create file for lambda layer terraform codes<br><strong>touch terraform/lambda_layer.tf</strong></pre><pre># Create python file for make pip requirements file from Pipfile<br><strong>touch terraform/requirements_creator.py</strong></pre><pre># Add shell script to generate pip requirements and make zip file of # lambda libraries<br><strong>touch terraform/build_layer.sh<br>chmod a+x terraform/build_layer.sh</strong></pre><p>In <strong>requirements_creator.py</strong>, a python argument parser will be added which gets the filename of pip requirements e.g. <strong>requirements.txt</strong></p><pre># terraform/requirements_creator.py</pre><pre>import argparse<br>from pipenv.project import Project<br>from pipenv.utils import convert_deps_to_pip<br><br>def _make_requirements_file(file_path):<br>    pipfile = Project(chdir=False).parsed_pipfile<br><br>    requirements = convert_deps_to_pip(pipfile[<strong>&#39;</strong>packages<strong>&#39;</strong>], r=False)<br>    with open(file_path, &#39;w&#39;) as req_file:<br>        req_file.write(<strong>&#39;</strong>\n<strong>&#39;</strong>.join(requirements))<br><br>def run():<br>    parser = argparse.ArgumentParser()<br>    parser.add_argument(<br>         <strong>&#39;--file_path&#39;</strong>, <br>         <strong>&#39;-file_path&#39;</strong>, <br>         type=str,<br>         default=<strong>&#39;requirements.txt&#39;<br>    </strong>)<br>    args = parser.parse_args()<br>    _make_requirements_file(args.file_path)<br><br><br>if __name__ == <strong>&quot;__main__&quot;</strong>:<br>    run()</pre><p>Now let’s add shell script to generate a zip file for lambda layer with python libraries</p><pre># terraform/build_layer.sh</pre><pre>DESTINATION_DIR=${DESTINATION_DIR:-$PWD}<br>MODULE_DIR=${MODULE_DIR:-$PWD}<br>ZIPFILE_NAME=${ZIPFILE_NAME:-layer}<br>echo &quot;Module dir $MODULE_DIR&quot;<br>echo &quot;Destination dir $DESTINATION_DIR&quot;<br><br>TARGET_DIR=$DESTINATION_DIR/$ZIPFILE_NAME<br>echo &quot;Target dir $TARGET_DIR&quot;<br>mkdir -p &quot;$TARGET_DIR&quot;</pre><pre>REQUIREMENTS_FILE_PATH=$MODULE_DIR/requirements.txt<br>python3 &quot;$MODULE_DIR&quot;/requirements_creator.py --file_path &quot;$REQUIREMENTS_FILE_PATH&quot;</pre><pre>pip install -r &quot;$REQUIREMENTS_FILE_PATH&quot; -t &quot;$TARGET_DIR&quot;/python<br>(cd &quot;$TARGET_DIR&quot; &amp;&amp; zip -r &quot;$DESTINATION_DIR&quot;/&quot;$ZIPFILE_NAME&quot;.zip ./* -x &quot;*.dist-info*&quot; -x &quot;*__pycache__*&quot; -x &quot;*.egg-info*&quot;)</pre><pre>rm &quot;$REQUIREMENTS_FILE_PATH&quot;<br>rm -r &quot;$TARGET_DIR&quot;</pre><p>Now add lambda layer terraform code</p><pre>// terraform/lambda_layer.tf</pre><pre>locals {<br>  <em>// All lambda codes zip and layer zip file directory<br>  </em>lambda_artifact_dir = &quot;${<em>path</em>.module}/lambda_zip&quot;<br>  lambda_layer_zipfile_name = &quot;layer&quot;<br>  python_version = &quot;python${<em>data</em>.external.python_version.result.version}&quot;<br>}<br><br><em>// Grab python version from Pipfile. Default is 3.8 if not mentioned // in Pipfile<br></em>data &quot;external&quot; &quot;python_version&quot; {<br>  program = [<br>    &quot;python3&quot;,<br>    &quot;-c&quot;,<br>    &quot;from pipenv.project import Project as P; import json; _p = P(chdir=False); print(json.dumps({&#39;version&#39;: _p.required_python_version or &#39;3.8&#39;}))&quot;<br>  ]<br>}<br><br><em>// Generate zipfile for lambda layer<br></em>resource &quot;null_resource&quot; &quot;build_lambda_layer&quot; {<br>  provisioner &quot;local-exec&quot; {<br>    when    = create<br>    command = &quot;./${<em>path</em>.module}/build_layer.sh&quot;<br><br>    environment = {<br>      DESTINATION_DIR = abspath(<em>local</em>.lambda_artifact_dir)<br>      MODULE_DIR      = abspath(<em>path</em>.module)<br>      ZIPFILE_NAME      = <em>local</em>.lambda_layer_zipfile_name<br>    }<br>  }<br><br>  triggers = {<br>    <em>// Trigger only when something changes in Pipfile<br>    </em>run_on_pipfile_change = filemd5(&quot;${abspath(<em>path</em>.module)}/../Pipfile&quot;)<br>  }<br>}<br><br>resource &quot;aws_lambda_layer_version&quot; &quot;lambda_layer&quot; {<br>  filename            = &quot;${<em>local</em>.lambda_artifact_dir}/${<em>local</em>.lambda_layer_zipfile_name}.zip&quot;<br>  layer_name          = &quot;lambda_layer&quot;<br>  compatible_runtimes = [<em>local</em>.python_version]<br>  <em>// It will run after lambda layer zipfile build<br>  </em>depends_on          = [null_resource.build_lambda_layer]<br><br>  lifecycle {<br>    create_before_destroy = true<br>  }<br>}</pre><p>Finally, we are going to add lambda terraform code</p><pre><em>// terraform/lambda.tf</em></pre><pre><em>// Zip lambda function codes<br></em>data &quot;archive_file&quot; &quot;lambda_zip_file&quot; {<br>  output_path = &quot;${<em>local</em>.lambda_artifact_dir}/lambda.zip&quot;<br>  source_dir  = &quot;${<em>path</em>.module}/../lambda&quot;<br>  excludes    = [&quot;__pycache__&quot;, &quot;*.pyc&quot;]<br>  type        = &quot;zip&quot;<br>}<br><br>data &quot;aws_iam_policy_document&quot; &quot;lambda_assume_role&quot; {<br>  version = &quot;2012-10-17&quot;<br><br>  statement {<br>    sid    = &quot;LambdaAssumeRole&quot;<br>    effect = &quot;Allow&quot;<br>    actions = [<br>      &quot;sts:AssumeRole&quot;<br>    ]<br>    principals {<br>      identifiers = [<br>        &quot;lambda.amazonaws.com&quot;<br>      ]<br>      type = &quot;Service&quot;<br>    }<br>  }<br>}<br><br><em>// Lambda IAM role<br></em>resource &quot;aws_iam_role&quot; &quot;lambda_role&quot; {<br>  name               = &quot;test-lambda-role&quot;<br>  assume_role_policy = <em>data</em>.aws_iam_policy_document.lambda_assume_role.json<br><br>  lifecycle {<br>    create_before_destroy = true<br>  }<br>}</pre><pre>// Lambda function terraform code<br>resource &quot;aws_lambda_function&quot; &quot;lambda_function&quot; {<br>  function_name    = &quot;test-lambda-function&quot;<br>  filename         = <em>data</em>.archive_file.lambda_zip_file.output_path<br>  source_code_hash = <em>data</em>.archive_file.lambda_zip_file.output_base64sha256<br>  handler          = &quot;handler.lambda_handler&quot;<br>  role             = aws_iam_role.lambda_role.arn<br>  runtime          = <em>local</em>.python_version<br>  layers           = [aws_lambda_layer_version.lambda_layer.arn]<br><br>  lifecycle {<br>    create_before_destroy = true<br>  }<br>}</pre><h4>Time to test</h4><p>To test if everything works, we have to add Terraform provider. In our case the provider is AWS. Let’s add a file <strong>provider.tf </strong>in terraform directory</p><pre># terraform/provider.tf<br>provider &quot;aws&quot; {<br>  region  = &quot;eu-west-1&quot;<br>  profile = &quot;aws-profile-name-from-aws-config-file-at-your-machine&quot;<br>}</pre><p>The project will look like</p><pre>.<br>├── lambda<br>│   └── handler.py<br>├── Pipfile<br>├── Pipfile.lock<br>└── terraform<br>    ├── build_layer.sh<br>    ├── lambda_layer.tf<br>    ├── lambda.tf<br>    ├── provider.tf<br>    └── requirements_creator.py</pre><p>Let’s build infrastructure 😹</p><pre># Activate pipenv virtual environment<br><strong>pipenv shell</strong></pre><pre># Go to terraform directory<br><strong>cd terraform</strong></pre><pre># Initialize terraform <br><strong>terraform init</strong></pre><pre># Check terraform infrastructure component to deploy<br><strong>terraform plan</strong></pre><pre># And deploy with<br><strong>terraform apply</strong></pre><pre># If you want to destroy all<br><strong>terraform destroy</strong></pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d28de0eb765f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/craftsmenltd/automate-python-libraries-deployment-at-aws-lambda-layer-from-pipfile-with-terraform-d28de0eb765f">Automate python libraries deployment at AWS Lambda layer from Pipfile with Terraform</a> was originally published in <a href="https://medium.com/craftsmenltd">Craftsmen — Software Maestros</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>