Published on

How to bundle your lambda with external dependencies by using BundlingOptions

Authors
  • avatar
    Name
    Katherine Moreno
    Twitter

Introduction

In this Post I'll explain you how to use the BundlingOptions Construct feature to bundle external dependencies.

How to use BundlingOptions

IMPORTANT

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

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 BundlingOptions, Stack
from aws_cdk.aws_lambda import Code, Function, Runtime
from constructs import Construct
from os import path


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

        Function(
            self,
            "AWSCdkDependenciesV2Lambda",
            code= Code.from_asset(path.join(path.dirname(__file__), "lambda"),
                bundling=BundlingOptions(
                    image= Runtime.PYTHON_3_12.bundling_image,
                    command=["bash", "-c", 
                             "pip install -r requirements.txt -t /asset-output && cp -r . /asset-output"
                    ]
                )
            ),
            runtime=Runtime.PYTHON_3_12,
            handler="my_lambda.handler"
        )

Docker will install the libraries of the requirements.txt and then bundle it to be uploaded alongside your lambda.

Thank you for reading it!