How to create AWS Lambda layers

Anil Koppula
2 min readMay 8, 2023

--

AWS Lambda Layers is a feature of AWS Lambda that allows you to separate your code into independent layers that can be reused across multiple functions. A layer is a package of libraries, dependencies, or other assets that can be bundled together and uploaded to AWS Lambda as a ZIP archive.

  1. Create a new directory for your layer, and navigate into it:
mkdir requests-layer
cd requests-layer

2. Create a requirements.txt file with the following contents:

requests

This file specifies the dependencies required by the requests module.

3. Install the dependencies into a site-packages directory within the layer:

pip install -r requirements.txt -t python/lib/python3.10/site-packages/

This command installs the requests module and its dependencies into a site-packages directory within the layer. You can specify a different version of Python by changing the path to the python directory.

4. Zip the contents of the layer directory:

zip -r requests-layer.zip . -x requirements.txt

This command creates a zip file containing the contents of the layer directory and excludes requirements.txt

5. Upload the layer to AWS Lambda using the AWS CLI:

aws lambda publish-layer-version --layer-name requests-layer --zip-file fileb://requests-layer.zip --compatible-runtimes python3.10

This command uploads the layer to AWS Lambda, and specifies that it is compatible with the Python 3.10 runtime. Make sure to replace requests-layer with a unique name for your layer.

[OR]

You can use AWS console to create a layer and upload the zip file

6. Add the layer to your Lambda function:
You can add the requests layer to your Lambda function using the AWS Management Console or CLI.

Using console: In the console, navigate to the "Layers" section of your function's configuration, and click "Add a layer". Select "Custom layers" and choose the requests layer that you just created.

Using CLI: In the CLI, use the update-function-configuration command to add the layer to your function:

aws lambda update-function-configuration --function-name MyFunction --layers arn:aws:lambda:us-east-1:123456789012:layer:requests-layer:1

This command adds the requests layer to a function named MyFunction. Replace the layer ARN with the ARN of your own layer.

Once you have added the requests layer to your Lambda function, you can import and use the requests module in your function code without needing to include it in your deployment package.

lambda_function.py

import json
import requests

def lambda_handler(event, context):
r = requests.get("https://www.google.com")
print(r)
print("Hello")
return {
'statusCode': 200,
'body': json.dumps('Hello from Lambda!')
}

What is AWS Lambda Layer and its benefits: https://medium.com/@koppulaanil1786/what-is-aws-lambda-layer-3f69ac97d870

More Info: https://docs.aws.amazon.com/lambda/latest/dg/configuration-layers.html

--

--