Add Python Dependencies to AWS Lambda Example
In this tutorial, I will explain you how to add/install Python dependencies to AWS Lambda function.
Follow the steps below:
- Open your terminal and create a folder:
- Navigate inside the folder you just created:
- Create a requirements.txt file inside that folder and add all the libraries that your function needs. For Example:
- Run the following command to install libraries compatible with your runtime in the appropriate sub folder (Replace python3.8 with the version of your Python):
Note: You must have docker installed on your computer to run the command given below:
docker run -v "$PWD":/var/task "lambci/lambda:build-python3.8" /bin/sh -c "pip3.8 install -r requirements.txt -t python/lib/python3.8/site-packages/; exit"
- Zip the python folder and create the layer package by running the following command:
zip -r mylibs.zip python > /dev/null
- Go to the AWS Lambda console > Layers. Enter the details, upload the zip file you created with and click on the Create button. Refer to the image below for example:
- Go to your Lambda Function and scroll down until you see the option to Add a Layer as shown in the example image below:
- On the Add layer page, select Custom layers for Layer source. Select the layer you created from the dropdown list for Custom layers. Finally select the version and choose the Add button. Refer to the image below for example:
- Now, you can import modules from the libraries you added in your AWS Lambda function.