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 commands to install libraries compatible with your runtime in the appropriate sub folder (Replace python3.8 with the version of your Python):
- Zip the python folder and create the layer package by running the following command:
- 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.
certifi==2021.5.30 charset-normalizer==2.0.4 confluent-kafka==1.7.0 greenlet==1.1.1 idna==3.2 numpy==1.21.2 pandas==1.3.3 PyMySQL==1.0.2 python-dateutil==2.8.2 pytz==2021.1 requests==2.26.0 six==1.16.0 SQLAlchemy==1.4.23 telnetlib3==1.0.4 urllib3==1.26.6
Note: You must have docker installed on your computer to run the command given below:Use the commands with sudo if you get permission error:
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 -r mylibs.zip python > /dev/null