AWS CDK Lambda Deployment Example
Section titled “AWS CDK Lambda Deployment Example”Introduction
Section titled “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
Section titled “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
Section titled “Project Structure”lib/- Contains the CDK stack definition in TypeScriptbin/- Contains the CDK app entry point and deployment scripts:cdk-app.ts- Main CDK application entry pointpackage_for_lambda.py- Python script that packages Lambda code and dependencies into deployment archives
lambda/- Contains the Python Lambda function codepackaging/- Directory used to store Lambda deployment assets and dependencies
Setup and Deployment
Section titled “Setup and Deployment”- Install dependencies:
# Install Node.js dependencies including CDK and TypeScript locallynpm install
# Create a Python virtual environment (optional but recommended)python -m venv .venvsource .venv/bin/activate # On Windows: .venv\Scripts\activate
# Install Python dependencies for the local developmentpip install -r requirements.txt# Install Python dependencies for lambda with correct architecturepip install -r requirements.txt --python-version 3.12 --platform manylinux2014_aarch64 --target ./packaging/_dependencies --only-binary=:all:- Package the lambda:
python ./bin/package_for_lambda.py- Bootstrap your AWS environment (if not already done):
npx cdk bootstrap- Deploy the lambda:
npx cdk deployAfter 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.jsonIf you have jq installed, you can output the response from output.json like so:
jq -r '.' ./output.jsonOtherwise, open output.json to view the result.
Cleanup
Section titled “Cleanup”To remove all resources created by this example:
npx cdk destroy