avatarRamon Marrero

Free AI web copilot to create summaries, insights and extended knowledge, download it at here

6427

Abstract

number of the AWS CDK, run the following command:</p><div id="61e3"><pre>cdk <span class="hljs-comment">--version</span></pre></div><h2 id="1dae">Initialize AWS CDK</h2><p id="97a8">Let’s start using AWS CDK by creating the App.</p><div id="9282"><pre><span class="hljs-built_in">mkdir</span> aws-<span class="hljs-built_in">lambda</span>-container-cdk cd aws-<span class="hljs-built_in">lambda</span>-container-cdk</pre></div><blockquote id="23dc"><p><b>Important</b>: You need an empty directory in order to initialize cdk and make sure you have provided your AWS credentials via the AWS CLI.</p></blockquote><p id="1f9c">We can initialize the app using the <b>cdk init</b> command, specifying the desired template (“app”) and programming language.</p><div id="5b5c"><pre>cdk init app --<span class="hljs-keyword">language</span> <span class="hljs-keyword">python</span></pre></div><p id="e641">The <b>cdk init</b> command generates a number of files and folders inside the <code>aws-lambda-container-cdk</code> directory to help you organize the source code for your AWS CDK app.</p><p id="3927">After initializing the project, activate the project’s virtual environment. This allows the project’s dependencies to be installed locally in the project folder, instead of globally.</p><div id="53d8"><pre><span class="hljs-built_in">source</span> .venv/bin/activate</pre></div><p id="a597">The next step is to install the app’s standard dependencies:</p><div id="d3ef"><pre>python -m pip <span class="hljs-keyword">install</span> -r requirements.txt</pre></div><p id="4a7e">We can proceed to install the AWS Construct Library module for AWS Lambda by executing:</p><div id="3f94"><pre>python -m pip <span class="hljs-keyword">install</span> aws-cdk.aws-lambda</pre></div><p id="c1d5">We have installed and prepared the fundamental building blocks for our CDK application. Now let’s create the container image.</p><h2 id="2fcf">Creating the Docker Container Image</h2><p id="a89f">To create our container image, we need a Dockerfile. Let’s create a directory that contains the Dockerfile and all container related files.</p><p id="0628">Create a new directory called <b>assets </b>under <code>aws-lambda-container-cdk</code> directory.</p><div id="4910"><pre>mkdir assets</pre></div><p id="bc41">In this example, we will be using a base image for Python provide by <a href="https://docs.aws.amazon.com/lambda/latest/dg/python-image.html#python-image-clients">AWS</a>. Create a Dockerfile under the newly created directory and provide the following content:</p><div id="5dbf"><pre><span class="hljs-keyword">FROM</span> <span class="hljs-keyword">public</span>.ecr.aws<span class="hljs-regexp">/lambda/</span>python:<span class="hljs-number">3.8</span>

<span class="hljs-keyword">COPY</span> app.py ./

CMD [<span class="hljs-string">"app.handler"</span>]</pre></div><p id="8fde">I have also created a python file called <b>app.py </b>under the assets directory with the following content:</p><div id="ea47"><pre><span class="hljs-keyword">import</span> sys

def <span class="hljs-keyword">handler</span>(event, context): <span class="hljs-keyword">return</span> <span class="hljs-string">'Hello from AWS Lambda using Python'</span> + sys.<span class="hljs-keyword">version</span> + <span class="hljs-string">'!'</span></pre></div><h1 id="e972">Adding the Lambda resource</h1><p id="cd74">To create our AWS Lambda function using AWS CDK, we need to follow a few simple steps:</p><ul><li><i>Add the lambda resource to the CDK stack.</i> Find the python file by the name <b>aws_lambda_container_stack.py</b> created under the directory aws_lambda_container. Change the file as below:</li></ul> <figure id="a5dc"> <div> <div>

            <iframe class="gist-iframe" src="/gist/ramonmarrero/73e88e61ee7f1dc5e6083994e9e6c6db.js" allowfullscreen="" frameborder="0" height="undefined" width="undefined">
          </div>
        </div>
    </figure></iframe></div></div></figure><p id="189c">This code will create the AWS Lambda function and deploy all the code created in the assets folder to the AWS Lambda as a container image. For more information about AWS CDK, please one of my previous posts.</p><div id="684e" class="link-block">
      <a href="https://readmedium.com/deploying-awlambda-functions-with-aws-cdk-python-92f42d66d5f7">
        <div>
          <div>
            <h2>Deploying AWLambda Functions with AWS CDK Python</h2>
            <div><h3>This is the way!</h3></div>
            <div><p>medium.com</p></div>
          </div>
          <div>
            <div style="background-image: url(https://miro.readmedium.com/v2/resize:fit:320/1*gJr5xNaX679VJ26f2PnWkA.png)"></div>
          </div>
        </div>
      </a>
    </div><p id="b12d">You can get the complete code from this public <a href="https://github.com/ramonmarrero/aws-lambda-container-cdk.git">repository</a>. Select the <b>main branch.</b></p><h1 id="3ff0">Testing Lambda container images</h1><p id="86dc">We are now ready to test our container image locally. For testing purposes, AWS provides The AWS Lambda Runtime Interface Emulator (RIE). It is a proxy for the Lambda Runtime API that enables you to locally test your Lambda function packaged as a container image. You can get additional information about the AWS Lambda RIE <a href="https://docs.aws.amazon.com/lambda/latest/dg/images-test.html">here</a>.</p><p id="7489">The RIE allows us to test whether our function code is compatible with the Lambda environment and to test that the Lambda function runs successfully.</p><p id="a1cb">Before testing, you will need to provide AWS security credentials. You can configure the credentials by setting up the AWS CLI with:</p><ul><li><code>AWS_ACCESS_KEY_ID</code></li><li><code>AWS_SECRET_ACCESS_KEY</code></li><li><code>AWS_REGION</code></li></ul><p id="b784">These credentials can also be provided during runtime but this approach is less secure.</p><p id="7620">To test your Lambda function with the emulator:</p><ul><li>Build your image locally using the <code>docker build</code> command.</li></ul><div id="a6c9"><pre>docker build -t myfunctionname:latest .</pre></div><ul><li>Run your container image locally using the <code>docker run</code> command.</li></ul><div id="e37a"><pre><span class="hljs-attribute">docker

Options

</span> run -p <span class="hljs-number">9000</span>:<span class="hljs-number">8080</span> myfunctionname:latest</pre></div><p id="f3f2">The command above runs the image as a container and starts up an endpoint locally at <code>localhost:9000/2015-03-31/functions/function/invocations</code>.</p><ul><li>From a new terminal window, post an event to the endpoint using a <code>curl</code> command:</li></ul><div id="3136"><pre><span class="hljs-attribute">curl</span> -XPOST <span class="hljs-string">"http://localhost:9000/2015-03-31/functions/function/invocations"</span> -d <span class="hljs-string">"{}"</span></pre></div><p id="2615">This is the output from my terminal after the last command:</p><figure id="e3ec"><img src="https://cdn-images-1.readmedium.com/v2/resize:fit:800/1*BRX7o5vUIgUAGD4ERZ8bag.png"><figcaption>Image from author</figcaption></figure><p id="1259">As you can see, the container is returning the correct output from the app.py script:</p><div id="7db8"><pre><span class="hljs-keyword">return</span> <span class="hljs-string">'Hello from AWS Lambda using Python'</span> + sys.version + <span class="hljs-string">'!'</span></pre></div><p id="23a7">Now we can proceed to deploy our resources using AWS CDK.</p><h1 id="97d2">Deploy the AWS Lambda function</h1><p id="f9d2">We are ready to deploy our Lambda resource. To deploy the stack using AWS CDK, go to the console and type <b>cdk deploy</b> from the main folder.</p><figure id="5b94"><img src="https://cdn-images-1.readmedium.com/v2/resize:fit:800/1*RNhyqR_UZyGEneS_duTXog.png"><figcaption>Image from author</figcaption></figure><p id="5c29">AWS CDK will provide an overview of the resources that will be deployed. In this case, you will see the roles and policies that will be added along with the Lambda resource to be created.</p><p id="75a8">If you proceed with the changes provided, the lambda will be deployed and the IAM roles and policies will be created and added to the resource.</p><p id="a055">There will be several steps to deploy the resources:</p><ul><li>The container image will be built and push to AWS ECR.</li><li>The IAM roles will be created to provide the right policies to the AWS Lambda.</li><li>The AWS Lambda function will be deployed.</li></ul><figure id="ba6f"><img src="https://cdn-images-1.readmedium.com/v2/resize:fit:800/1*Lm3uapzPT0HhVw0yvf9q0g.png"><figcaption>Image from author</figcaption></figure><p id="4ace">You can now go to the AWS console and test your newly created AWS Lambda container image.</p><p id="870d">As you have witnessed, this new feature of AWS Lambda provides great potential. Looking forward to hearing your ideas on how it was able to help you in tackle different challenges on your individual projects.</p><p id="6e44">Happy coding! Do not forget to follow me or subscribe via email <a href="https://ramon-marrero.medium.com/subscribe"><b>here</b></a>. You can also support my writing by joining Medium using the following <a href="https://ramon-marrero.medium.com/membership"><b>link</b></a>.</p><p id="75da">For more AWS content</p><div id="f48c" class="link-block"> <a href="https://readmedium.com/running-serverless-spark-applications-with-aws-lambda-d7e25795ec1d"> <div> <div> <h2>Running Serverless Spark Applications with AWS Lambda.</h2> <div><h3>Leverage Amazon SageMaker Processing to run serverless Spark applications from AWS Lambda.</h3></div> <div><p>medium.com</p></div> </div> <div> <div style="background-image: url(https://miro.readmedium.com/v2/resize:fit:320/1*1YjB_gt-2QvwMCzpJjrFWg.png)"></div> </div> </div> </a> </div><div id="3dba" class="link-block"> <a href="https://readmedium.com/building-serverless-services-with-aws-cdk-478315b45fb8"> <div> <div> <h2>Building Serverless Services with AWS CDK</h2> <div><h3>Create serverless services in a reliable and reproducible manner using AWS CDK and Python.</h3></div> <div><p>medium.com</p></div> </div> <div> <div style="background-image: url(https://miro.readmedium.com/v2/resize:fit:320/1*tJ6h4ib27qxhqGelU_Pgfg.png)"></div> </div> </div> </a> </div><div id="9ee4" class="link-block"> <a href="https://readmedium.com/deploying-aws-lambda-layers-with-python-8b15e24bdad2"> <div> <div> <h2>Deploying AWS Lambda layers with Python</h2> <div><h3>Learn to easily deploy a Lambda Layer via AWS CDK and Python.</h3></div> <div><p>medium.com</p></div> </div> <div> <div style="background-image: url(https://miro.readmedium.com/v2/resize:fit:320/1*-gTyLrWL-jWj2GGkw63sgg.png)"></div> </div> </div> </a> </div><div id="5c66" class="link-block"> <a href="https://readmedium.com/deploying-amazon-managed-apache-airflow-with-aws-cdk-7376205f0128"> <div> <div> <h2>Deploying Amazon Managed Apache Airflow with AWS CDK</h2> <div><h3>Learn to easily deploy Apache Airflow as a managed service on AWS using Python and the AWS CDK.</h3></div> <div><p>medium.com</p></div> </div> <div> <div style="background-image: url(https://miro.readmedium.com/v2/resize:fit:320/1*sgDEpAFPZfqSBM3DDDvgmQ.png)"></div> </div> </div> </a> </div><p id="b9dd"><b>For a vibrant cloud community with more content, you can visit:</b></p><div id="b80e" class="link-block"> <a href="https://www.ready4prod.io/blog/"> <div> <div> <h2>Blog - Ready4Prod</h2> <div><h3>This website uses cookies to improve your experience while you navigate through the website. Out of these, the cookies…</h3></div> <div><p>www.ready4prod.io</p></div> </div> <div> <div style="background-image: url(https://miro.readmedium.com/v2/resize:fit:320/0*Sgx3Cn_LirFTnqxS)"></div> </div> </div> </a> </div></article></body>

Deploying AWS Lambda Container Images

Learn how to package AWS Lambda functions as container images with AWS CDK and Python.

Web illustrations by Storyset

AWS Lambda is one of the most commonly known services from AWS. As per the AWS website, it is a compute service that lets you run code without provisioning or managing servers. You will only run your code when needed and it scales automatically from few requests per day to thousands per second.

You can write your code for AWS Lambda using different runtimes. As of the time of writing the supported runtimes are: Node.js, Python, Java, C#, Ruby, Go, and PowerShell.

Recently, AWS announced support for container images and you can now package and deploy Lambda functions as container images. One of the advantages is that this allows developers to build and deploy larger workloads that rely on sizable dependencies.

Additionally, AWS is providing base images for the following supported Lambda runtimes (Python, Node.js, Java, .NET, Go, Ruby). AWS also states that will maintain and regularly update these images, in addition, to release an AWS base image when any new managed runtime becomes available.

In this post, we will explore how to package AWS Lambda functions using container images. We will use Python as the programming language for the AWS Lambda function and we will take advantage of the AWS CDK to deploy our AWS service.

If you find this article helpful, please do not forget to like or comment below.

Lambda Container Images

To package our code and dependencies as a container image, we can rely on the Docker command line interface (CLI) and the Amazon Elastic Container Registry (Amazon ECR).

When creating AWS Lambda container images you must create the Lambda function from the same account as the container registry in Amazon ECR.

You can use base images provided by AWS or you can bring alternative base images from other container registries. For the latter, AWS provides an open-source runtime client that you add to your alternative base image to make it compatible with the Lambda service.

Additionally, AWS provides a pretty useful tool as a runtime interface emulator for you to test your functions locally using Docker CLI.

Restrictions

As per AWS documentation, there are some restrictions to comply with before using container images with the AWS Lambda service:

Image Type: AWS Lambda supports any image that conforms to any of the following image manifest formats.

  • Docker image manifest V2, schema 2 (Docker version 1.10 and newer)
  • Open Container Initiative (OCI) Specifications (v1.0.0 and up)

Image Settings: AWS Lambda supports the following container image settings in the Dockerfile:

  • ENTRYPOINT — Specifies the absolute path to the entry point of the application.
  • CMD — Specifies parameters that you want to pass in with ENTRYPOINT.
  • WORKDIR — Specifies the absolute path to the working directory.
  • ENV — Specifies an environment variable for the Lambda function.

Lambda will ignore the values of any unsupported container image settings in the Dockerfile.

Container Image: The container image must implement the Lambda Runtime API. It must be able to run on a read-only file system. Your function code can access a writable /tmp directory with 512 MB of storage.

The default Lambda user must be able to read all the files required to run your function code and Lambda only supports Linux-based container images.

Now that we are aware of the requirements and restrictions, let’s create an AWS Lambda container image.

Setting up AWS CDK

As with any AWS implementation, there are several ways to create and deploy your resources to the cloud. In this case, we will be using AWS CDK.

AWS CDK is a software development framework to define your cloud application resources using familiar programming languages. It provides high-level components called constructs that preconfigure cloud resources with proven defaults, enabling the provision of resources in a safe, repeatable manner through AWS CloudFormation.

Prerequisites

To set up AWS CDK properly, we will need:

  • An AWS account and credentials.
  • Node.js.
  • Python 3.6 or later.
  • Python package installer, pip, and virtual environment manager, virtualenv.

Install the AWS CDK using the following Node Package Manager command.

npm install -g aws-cdk

To verify the correct installation and print the version number of the AWS CDK, run the following command:

cdk --version

Initialize AWS CDK

Let’s start using AWS CDK by creating the App.

mkdir aws-lambda-container-cdk
cd aws-lambda-container-cdk

Important: You need an empty directory in order to initialize cdk and make sure you have provided your AWS credentials via the AWS CLI.

We can initialize the app using the cdk init command, specifying the desired template (“app”) and programming language.

cdk init app --language python

The cdk init command generates a number of files and folders inside the aws-lambda-container-cdk directory to help you organize the source code for your AWS CDK app.

After initializing the project, activate the project’s virtual environment. This allows the project’s dependencies to be installed locally in the project folder, instead of globally.

source .venv/bin/activate

The next step is to install the app’s standard dependencies:

python -m pip install -r requirements.txt

We can proceed to install the AWS Construct Library module for AWS Lambda by executing:

python -m pip install aws-cdk.aws-lambda

We have installed and prepared the fundamental building blocks for our CDK application. Now let’s create the container image.

Creating the Docker Container Image

To create our container image, we need a Dockerfile. Let’s create a directory that contains the Dockerfile and all container related files.

Create a new directory called assets under aws-lambda-container-cdk directory.

mkdir assets

In this example, we will be using a base image for Python provide by AWS. Create a Dockerfile under the newly created directory and provide the following content:

FROM public.ecr.aws/lambda/python:3.8

COPY app.py   ./

CMD ["app.handler"]

I have also created a python file called app.py under the assets directory with the following content:

import sys

def handler(event, context):
    return 'Hello from AWS Lambda using Python' + sys.version + '!'

Adding the Lambda resource

To create our AWS Lambda function using AWS CDK, we need to follow a few simple steps:

  • Add the lambda resource to the CDK stack. Find the python file by the name aws_lambda_container_stack.py created under the directory aws_lambda_container. Change the file as below:

This code will create the AWS Lambda function and deploy all the code created in the assets folder to the AWS Lambda as a container image. For more information about AWS CDK, please one of my previous posts.

You can get the complete code from this public repository. Select the main branch.

Testing Lambda container images

We are now ready to test our container image locally. For testing purposes, AWS provides The AWS Lambda Runtime Interface Emulator (RIE). It is a proxy for the Lambda Runtime API that enables you to locally test your Lambda function packaged as a container image. You can get additional information about the AWS Lambda RIE here.

The RIE allows us to test whether our function code is compatible with the Lambda environment and to test that the Lambda function runs successfully.

Before testing, you will need to provide AWS security credentials. You can configure the credentials by setting up the AWS CLI with:

  • AWS_ACCESS_KEY_ID
  • AWS_SECRET_ACCESS_KEY
  • AWS_REGION

These credentials can also be provided during runtime but this approach is less secure.

To test your Lambda function with the emulator:

  • Build your image locally using the docker build command.
docker build -t myfunctionname:latest .
  • Run your container image locally using the docker run command.
docker run -p 9000:8080  myfunctionname:latest

The command above runs the image as a container and starts up an endpoint locally at localhost:9000/2015-03-31/functions/function/invocations.

  • From a new terminal window, post an event to the endpoint using a curl command:
curl -XPOST "http://localhost:9000/2015-03-31/functions/function/invocations" -d "{}"

This is the output from my terminal after the last command:

Image from author

As you can see, the container is returning the correct output from the app.py script:

return 'Hello from AWS Lambda using Python' + sys.version + '!'

Now we can proceed to deploy our resources using AWS CDK.

Deploy the AWS Lambda function

We are ready to deploy our Lambda resource. To deploy the stack using AWS CDK, go to the console and type cdk deploy from the main folder.

Image from author

AWS CDK will provide an overview of the resources that will be deployed. In this case, you will see the roles and policies that will be added along with the Lambda resource to be created.

If you proceed with the changes provided, the lambda will be deployed and the IAM roles and policies will be created and added to the resource.

There will be several steps to deploy the resources:

  • The container image will be built and push to AWS ECR.
  • The IAM roles will be created to provide the right policies to the AWS Lambda.
  • The AWS Lambda function will be deployed.
Image from author

You can now go to the AWS console and test your newly created AWS Lambda container image.

As you have witnessed, this new feature of AWS Lambda provides great potential. Looking forward to hearing your ideas on how it was able to help you in tackle different challenges on your individual projects.

Happy coding! Do not forget to follow me or subscribe via email here. You can also support my writing by joining Medium using the following link.

For more AWS content

For a vibrant cloud community with more content, you can visit:

AWS
AWS Lambda
Docker
Containers
Python
Recommended from ReadMedium