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.

 1from aws_cdk.aws_lambda import (
 2    Runtime,
 3)
 4from aws_cdk.aws_lambda_python_alpha import BundlingOptions, PythonFunction
 5
 6
 7python.PythonFunction(self, "MyFunction",
 8    entry="/path/to/lambda/handler/module", # required
 9    runtime=Runtime.PYTHON_3_12,            # required
10    index="my_index.py",                    # optional, defaults to 'index.py', the file containing your lambda handler function
11    handler="my_lambda_handler_func"        # required
12    bundling=BundlingOptions(
13        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
14        poetry_include_hashes=False,        # when generating outputs like requirements.txt Poetry will produce hashes by default, you may wish to turn them off
15    )
16    # other properties from the aws_cdk.aws_lambda.Function class can be used too
17)