Python Lambda Setup

How to package Python external libraries into an AWS Lambda Layer for use in Nomad Media Lambda functions.

Many Nomad Media Python samples require external libraries that are not available by default in the Lambda runtime. The following steps package those libraries into a Lambda Layer.

Prerequisite: You need a bash shell. If you don't have one locally, use AWS CloudShell (search for "CloudShell" in the AWS Console).

Step 1 — Install Libraries and Create the Zip

# Create a working directory
mkdir packages
cd packages

# Create and activate a virtual environment
python3 -m venv venv
source venv/bin/activate

# Create the python directory (required by Lambda layer structure)
mkdir python
cd python

# Install your required libraries into this directory
# This example installs the requests library
pip install requests -t .

# Remove .dist-info files to save space
rm -rf *dist-info

# Zip the package
cd ..
zip -r packages.zip python

If using AWS CloudShell, upload the zip to S3 for access in the next step:

aws s3 cp packages.zip s3://{your-s3-bucket-name}/

Step 2 — Create the Lambda Layer

  1. In the AWS Console, go to LambdaLayers (under Additional resources in the left sidebar).
  2. Click Create layer.
  3. Enter a Name for the layer.
  4. Under the upload section:
    • If you have the zip locally: choose Upload a .zip file.
    • If you used CloudShell and uploaded to S3: choose Upload a file from Amazon S3.
  5. Under Compatible runtimes, select the latest Python version available.
  6. Click Create.

Step 3 — Add the Layer to Your Lambda

  1. Open your Lambda function and go to the Code tab.
  2. Scroll to the bottom of the page to the Layers section.
  3. Click Add a layer.
  4. Under Choose a layer source, select Custom layers.
  5. Select the layer you just created and choose Version 1.
  6. Click Add.

Your Lambda function can now import the libraries you packaged.