I tried adding Layers to Lambda Functions for Python Packages

Hi, this is Charu from Classmethod and in this blog, we will walk through the process of adding layers to a Lambda function for Python packages.

I was working with my lambda function but I wanted to add a python package 'pytz'(for timezone) into my code. But I was clueless on how to add a package without changing anything in my code structure. After few research, I got to know about lambda layers.

Lambda functions in AWS provide a serverless computing environment that allows you to run code without provisioning or managing servers. One powerful feature of Lambda is the ability to add layers, which are external dependencies or libraries that can be shared across multiple Lambda functions. Layers enable you to separate your application logic from external dependencies, making your Lambda functions cleaner and more modular.

Let's get started:

1. Start by creating a new directory for your Python package on your local machine(like vscode).

2. Install the required library (in this case pytz) in that folder. You can use pip to do this:

mkdir pytz-layer
cd pytz-layer
pip install pytz -t ./

3. If you have more than one packages, you can install them all together. Inside the directory, create a new file named requirements.txt and list all the Python packages you want to include in your layer. For example:

requests
numpy
pandas
pytz

Install the Python packages listed in the requirements.txt file by running the following command:

pip install -r requirements.txt

4. Once you've installed the pytz library in the pytz-layer folder, create a .zip package. This is the package you will upload to AWS Lambda:

cd ..
zip -r pytz-layer.zip pytz-layer

5. Create the Lambda layer:

  • Open your AWS Management Console and navigate to the AWS Lambda service.
  • Click on "Layers" in the left-hand menu and then click the "Create layer" button.
  • Provide a name and description for your layer.
  • Choose the appropriate runtime for your Lambda function.
  • Click on "Upload" and select the layer.zip file you created in the previous step.
  • Specify a compatible license if required.
  • Click the "Create" button to create the layer.
  • 6. Attach the layer to a Lambda function:

  • Create a new or open an existing Lambda function that you want to attach the layer to.
  • Scroll down to the "Layers" section in the function configuration.
  • Click on "Add a layer" and select the layer you created in the previous step.
  • Specify the ARN of the layer to use.
  • Click the "Save" button to apply the changes.
  • Once you've completed these steps, your Lambda function should be able to import the packages module without any issues. Now you can reuse the same layer across multiple Lambda functions, reducing duplication and improving maintenance.

    Thank you!

    Happy Learning :)