AWS CDK Python Lambda Alpha Library

2.248.0a0 · active · verified Sat Apr 11

The CDK Construct Library for AWS Lambda in Python, providing constructs to define and manage Python Lambda functions. It simplifies packaging and dependency management by leveraging Docker for bundling. This is an alpha package, meaning its APIs are experimental and subject to non-backward compatible changes, with breaking changes announced in release notes rather than following strict semantic versioning. Current version is 2.248.0a0 and it is under active development.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to define a Python Lambda function using `PythonFunction` from the `aws-cdk.aws-lambda-python-alpha` library. It dynamically creates a `lambda_code` directory with a simple `lambda_handler.py` file. The `PythonFunction` construct automatically bundles your code and its dependencies (if a `requirements.txt`, `Pipfile`, `uv.lock`, or `poetry.lock` is present in the `entry` directory) using Docker during `cdk synth`.

import os
from aws_cdk import (
    App,
    Stack,
    aws_lambda as _lambda,
)
from aws_cdk.aws_lambda_python_alpha import PythonFunction
from constructs import Construct

# Create a dummy lambda_code directory and handler file for the example
lambda_code_dir = os.path.join(os.path.dirname(__file__), "lambda_code")
os.makedirs(lambda_code_dir, exist_ok=True)
with open(os.path.join(lambda_code_dir, "lambda_handler.py"), "w") as f:
    f.write("""
import json

def handler(event, context):
    print("Lambda received event:", event)
    return {
        'statusCode': 200,
        'body': json.dumps('Hello from Python Lambda Alpha!')
    }
""")
# Add a dummy requirements.txt if you want to test dependency bundling
# with open(os.path.join(lambda_code_dir, "requirements.txt"), "w") as f:
#     f.write("requests\n")

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

        PythonFunction(
            self,
            "MyPythonLambda",
            entry=lambda_code_dir, # Path to the directory containing your handler and dependencies
            runtime=_lambda.Runtime.PYTHON_3_9, # Specify a supported Python runtime
            index="lambda_handler.py", # Optional, defaults to 'index.py'
            handler="handler", # Optional, defaults to 'handler'
            # Set an environment variable (optional)
            environment={
                "MY_ENV_VAR": os.environ.get('MY_ENV_VAR', 'default_value')
            }
        )

app = App()
MyPythonLambdaStack(app, "MyPythonLambdaStack")
app.synth()

view raw JSON →