How to create an AWS Lambda layer

AWS Lambda is a serverless compute service that lets you run code without provisioning or managing servers. Using Lambda, you can create code that will only be run in response to an event. AWS supports lambda functions in many languages including Python.

Writing a Python Lambda function is pretty straight forward if your code does not have any external dependencies such as third party libraries. In this post, I’ll show you how to add third party libraries to Lambda using Lambda layers. According to the AWS docs, a layer is ” a .zip file archive that can contain additional code or data. A layer can contain libraries, a custom runtime, data, or configuration files”.

So, if you wanted to create a Python Lambda function that depends on Flask or requests for instance, one way to deploy it would be to create a Lambda layer, install Flask and requests in it and upload that to AWS. Let’s do it:

Prepare the layer

Create a folder for your project on your local computer:

$ mkdir aws_lambda_layer
$ cd aws_lambda_layer

Next, create the folder structure for the modules you will install:

$ mkdir -p flask_layer/python/lib/python3.8/site-packages

Once the folders are created, create a virtual environment and install the packages you need:

$ python3 -m venv .venv

$ source .venv/bin/activate

(.venv) $ pip install flask --target flask_layer/python/lib/python3.8/site-packages

Next, change directories into the flask_layer directory and create a zip file containing the contents of that folder:

$ zip -r9 flask_layer.zip .

Using your layer

Once you have created the layer, you need to upload it. If it is large, upload it to an S3 bucket, if it isn’t, you can upload it directly to the AWS Lambda interface in the AWS console. Navigate to Lambda > Layers and create a layer. Give it a reasonable name and upload. If you uploaded the layer to S3, point to it here.

Once you have uploaded the layer, you can provision a new lambda function and make it use the new layer you just created.

Thanks for reading.

 

Vuyisile