Published on

How to bundle your lambda with external dependencies by using PythonFunction

Authors
  • avatar
    Name
    Katherine Moreno
    Twitter

Introduction

In this Post I'll explain you how to use the PythonFunction library to bundle external dependencies.

How to use PythonFunction

IMPORTANT

As a Pre Requisite we need to have installed Docker as PythonFunction uses it to bundle the dependencies.

WARNING

PythonFunction is an alpha library, meaning that changes are constant and AWS does not guarantee retrocompatibility with previous previsions.

Example of use case: We are trying to deploy a dummy lambda which uses the numpy

Create a new folder called 'lambda' this folder will contain two files. The requirements file which will contain the dependencies to be bundled alongside our lambdas/

requirements.txt
numpy==2.0.0

And the my_lambda.py an example of lambda using the library defined on our requirements.txt

my_lambda.py
import numpy as np

def handler(_event, _context):
    return np.random.randint(1, 10)

Now our folder should look like something like this

  lambda  -> requirements.txt
          -> my_lambda.py

And in on our Stack we can define our lambda by using PythonFunction

stack.py
from aws_cdk import Stack
from aws_cdk.aws_lambda import Runtime
from aws_cdk.aws_lambda_python_alpha import PythonFunction
from constructs import Construct


class MyStack(Stack):
    def __init__(self, scope: Construct, construct_id: str, **kwargs) -> None:
        super().__init__(scope, construct_id, **kwargs)

        PythonFunction(
            self,
            "AWSCdkDependenciesV3Lambda",
            runtime=Runtime.PYTHON_3_11,
            index="my_lambda.py",  # Path to the directory with the Lambda function code
            entry="./lambda", # This is where it's the location of the folder which contains the definition of our dependencies
            description='This is a lambda using PythonFunction' 
        )

The entry folder should point to the folder which contains the definition of the requirements

The dependencies can not only be defined, but they can also be defined with a Pipfile or a poetry.lock

As the AWS Documentation of PythonFunction describes

Lambda with a requirements.txt

.
├── lambda_function.py # exports a function named 'handler'
├── requirements.txt # has to be present at the entry path

Lambda with a Pipfile

.
├── lambda_function.py # exports a function named 'handler'
├── Pipfile # has to be present at the entry path
├── Pipfile.lock # your lock file

Lambda with a poetry.lock

.
├── lambda_function.py # exports a function named 'handler'
├── pyproject.toml # your poetry project definition
├── poetry.lock # your poetry lock file has to be present at the entry path

Thanks for your reading, enjoy your smart lambda!