I wanted to write a quick how to blog in reference to show someone how to include dependencies with their python AWS Serverless function.
The Use Case
You have been assigned a project and you need to create a Lambda Serverless function in python that needs to execute a stored procedure or a SQL statement against a RDS Postgres Database. You need this function to be ran on a time schedule and it has to interact with the Postgres database.
What is AWS Layers
AWS has implemented some nice functionality called layers for us to easily include dependencies that our python script needs. Layers allow you to configure your Lambda function to pull in additional code and content in the form of layers. A layer is a ZIP archive that contains libraries, a custom runtime, or other dependencies. With layers, you can use libraries in your function without needing to include them in your deployment package. This allows your deployment package to be smaller.
Prerequisite: You have gone through the steps of writing and saving your Lambda function written in python you now want to add the psycopg2 library for your code to use.
Step one: Download the psycopg2 from https://github.com/jkehler/awslambda-psycopg2
Step two: Create a directory name python and put the psycopg2 folder inside the newly created python folder
Step three: Zip up the python directory that you created in step two
Step four: Save your function and then go to the Lambda home screen and click on “Layers”
Step five: Click the “Create Layer” button located at the top right part of the AWS console
Step six: Layer Configuration. Give your Layer a unique name. Enter a description of your layer. Click the “Upload” button and browse to your python zip file and select. Choose the Runtime version that you want. Click the “Create” button.
Step seven: Now that your layer is created time to setup in your function. Go back to the Lambda home screen and select functions. Choose the function that you created and has the dependency for psycopg2.
Step eight: Select the Layers box right under the name of your function
Step nine: Select the “Add Layer” button
Step ten: Select the Layer your created from the “layer” dropdown. Select the version from the “Version” dropdown. Click the “Add” Button.
You have now added a layer to your Lambda python function and you can go ahead and test it. Hope this helps.