thomaspaulin.me

How to write a Python Lambda function in AWS CDK (without Docker)

Most of the time you when you write Python code for AWS Lambda Functions you’ll include external dependencies such as boto3. There are two approaches you can take to including those dependencies.

  1. You create a Docker-based function and run pip install or otherwise within the image build process.
  2. You create a zip file containing your code and the appropriate vendor code e.g. you bundle your virtualenv’s site-packages folder and configure your PYTHONPATH as appropriate.
  3. Bonus: You take the same approach as 2. but put some of your dependencies as layers for re-use across different AWS Lambda functions. As of April 2024 you may only have five (5) layers so choose wisely.

If you use AWS CDK there is a fourth option in the form of the PythonFunction construct, provided via the aws-lambda-python-alpha module. This construct will bundle your dependencies automatically if it detects a requirements.txt, Pipfile, or poetry.lock file.

A brief example of what using this construct might look like is shown below.

from aws_cdk.aws_lambda import (
    Runtime,
)
from aws_cdk.aws_lambda_python_alpha import BundlingOptions, PythonFunction


python.PythonFunction(self, "MyFunction",
    entry="/path/to/lambda/handler/module", # required
    runtime=Runtime.PYTHON_3_12,            # required
    index="my_index.py",                    # optional, defaults to 'index.py', the file containing your lambda handler function
    handler="my_lambda_handler_func"        # required
    bundling=BundlingOptions(
        asset_excludes=[".pytest_cache", "__pycache__", "..."], # the paths to exclude from the final product, I like to omit what isn't relevant to the final runtime
        poetry_include_hashes=False,        # when generating outputs like requirements.txt Poetry will produce hashes by default, you may wish to turn them off
    )
    # other properties from the aws_cdk.aws_lambda.Function class can be used too
)