AWS Lambda Builders

1.63.0 · active · verified Sat Apr 11

AWS Lambda Builders is a Python library (currently v1.63.0) designed to compile, build, and package AWS Lambda functions for various runtimes and frameworks. It serves as the core logic behind the 'sam build' command in the AWS Serverless Application Model (SAM) CLI. The library has an active release cadence, frequently adding support for new runtimes and improving existing build workflows.

Warnings

Install

Imports

Quickstart

This example demonstrates how to programmatically use `aws-lambda-builders` to package a simple Python Lambda function with a dependency. It creates a dummy source directory, defines build parameters like runtime and output directories, then invokes the `LambdaBuilder` to create the deployment package. The output will be a zip-ready artifact in the specified `artifacts_dir`.

import os
from aws_lambda_builders.builder import LambdaBuilder
from aws_lambda_builders.exceptions import BuildError

# Create a dummy source directory with a requirements.txt and app.py
# In a real scenario, this would be your Lambda function's source code.
source_dir = './my_lambda_app_source'
artifacts_dir = './my_lambda_app_build'

os.makedirs(source_dir, exist_ok=True)
os.makedirs(artifacts_dir, exist_ok=True)

with open(os.path.join(source_dir, 'requirements.txt'), 'w') as f:
    f.write('requests==2.28.1\n')

with open(os.path.join(source_dir, 'app.py'), 'w') as f:
    f.write('import requests\n\ndef handler(event, context):\n    response = requests.get("https://api.github.com")\n    return {\n        "statusCode": 200,\n        "body": f"Hello from Lambda! GitHub status: {response.status_code}"\n    }\n')

# Define build parameters
# runtime: The target AWS Lambda runtime (e.g., 'python3.9', 'nodejs18.x')
# build_options: Specific options for the workflow (e.g., 'uv' for Python)
build_parameters = {
    "source_dir": source_dir,
    "artifacts_dir": artifacts_dir,
    "scratch_dir": './.aws-lambda-builders-scratch',
    "runtime": 'python3.9',
    "architecture": 'x86_64',
    "optimizations": {},
    "options": {
        "artifact_executable_name": "app.py", # Entry point for Python
        "handler": "app.handler"
    }
}

try:
    print("Starting Lambda build...")
    # Initialize the LambdaBuilder
    builder = LambdaBuilder(
        lambda_builders_version='1.0.0', # Placeholder for internal tracking
        **build_parameters
    )

    # Execute the build
    builder.build()

    print(f"Lambda function successfully built to: {artifacts_dir}")
    print(f"Contents: {os.listdir(artifacts_dir)}")
    # Clean up dummy files
    os.remove(os.path.join(source_dir, 'requirements.txt'))
    os.remove(os.path.join(source_dir, 'app.py'))
    os.rmdir(source_dir)
    os.rmdir(build_parameters['scratch_dir'])
    os.rmdir(artifacts_dir)
except BuildError as e:
    print(f"Build failed: {e}")
except Exception as e:
    print(f"An unexpected error occurred: {e}")

view raw JSON →