Skip to content

AWS CDK Lambda Deployment Example

Introduction

This is a TypeScript-based CDK (Cloud Development Kit) example that demonstrates how to deploy a Python function to AWS Lambda. The example deploys a weather forecaster application that requires AWS authentication to invoke the Lambda function.

Prerequisites

  • AWS CLI installed and configured
  • Node.js (v18.x or later)
  • Python 3.12 or later
  • jq (optional) for formatting JSON output

Project Structure

  • lib/ - Contains the CDK stack definition in TypeScript
  • bin/ - Contains the CDK app entry point and deployment scripts:
  • cdk-app.ts - Main CDK application entry point
  • package_for_lambda.py - Python script that packages Lambda code and dependencies into deployment archives
  • lambda/ - Contains the Python Lambda function code
  • packaging/ - Directory used to store Lambda deployment assets and dependencies

Setup and Deployment

  1. Install dependencies:
# Install Node.js dependencies including CDK and TypeScript locally
npm install

# Create a Python virtual environment (optional but recommended)
python -m venv .venv
source .venv/bin/activate  # On Windows: .venv\Scripts\activate

# Install Python dependencies for the local development
pip install -r requirements.txt
# Install Python dependencies for lambda with correct architecture
pip install -r requirements.txt --platform manylinux2014_aarch64 --target ./packaging/_dependencies --only-binary=:all:
  1. Bootstrap your AWS environment (if not already done):
npx cdk bootstrap
  1. Package the lambda & deploy the stack:
python ./bin/package_for_lambda.py
npx cdk deploy

Usage

After deployment, you can invoke the Lambda function using the AWS CLI or AWS Console. The function requires proper AWS authentication to be invoked.

aws lambda invoke --function-name AgentFunction \
      --region us-east-1 \
      --cli-binary-format raw-in-base64-out \
      --payload '{"prompt": "What is the weather in New York?"}' \
      output.json

If you have jq installed, you can output the response from output.json like so:

jq -r '.' ./output.json

Otherwise, open output.json to view the result.

Cleanup

To remove all resources created by this example:

npx cdk destroy

Additional Resources