AWS Documentation on Adding Python Dependencies to Your Lambda Zip File

https://docs.aws.amazon.com/lambda/latest/dg/python-package.html

Note: The documentation above says this – and a lot of other things – read it for more info:

Important

To maintain full control over your dependencies and to avoid possible version misalignment issues, we recommend you add all of your function’s dependencies to your deployment package, even if versions of them are included in the Lambda runtime. This includes the Boto3 SDK.

To find out which version of the SDK for Python (Boto3) is included in the runtime you’re using, see Runtime-included SDK versions.

Under the AWS shared responsibility model, you are responsible for the management of any dependencies in your functions’ deployment packages. This includes applying updates and security patches. To update dependencies in your function’s deployment package, first create a new .zip file and then upload it to Lambda. See Creating a .zip deployment package with dependencies and Creating and updating Python Lambda functions using .zip files for more information.

It is also important that the directory structure of your “deployment zip file” complies with the documentation above. For simple imports this means (to me) that you should create a sub-directory using:

1.) pip -install <packageName> --target ./package
2.) cd package
3.) zip -r ../my-deployment.zip .
4.) cd ..
5.) zip my-deployment.zip lambda_handler.py

the 5 commands above do build the deployment zip with the proper hierarchy.. by:
1.) creating a sub-folder that contains your dependency python code –target does this or -t for short
2.) cd into that folder
3.) creating a zip of the dependency folder one level up from the dependency folder
4.) cd up and out of that dependency folder to the same level as your “lambda_handler.py”
5.) now add the lamba handler.py to the deployment zip

Now the file my-deployment.zip can be uploaded.

Effectively you have created a “flat” deployment zip with dependencies in sub-folders – JUST one level down – from the lambda_handler.py file.

One folder for the lambda_handler.py and a sub-folder for all dependencies – see using –target above.

pip install pyPkg1 pyPkg2 pyPkg3 --target ./package
# this command installs all Python modules specified in the package folder all at the same level

Note the version of python/pip you are running on your local machine – remember you did a pip install –target? should match the AWS lambda e.g. if you specify 3.11 in AWS, you better be using 3.11 locally matching the version you selected when you created the lambda function.

The youtube below has a decent example of including simple dependencies directly in your deployment zip to be uploaded to AWS

Scroll to Top