Deploying a Lambda function to AWS for every minor update can slow down development.
The AWS SAM CLI (sam local) enables you to run and debug Lambda functions on your local machine inside a Docker container that replicates the AWS Lambda runtime.
1. Prerequisites
Before starting, ensure you have:
- AWS SAM CLI installed
- Docker must be installed and running, as SAM relies on it to simulate the Lambda execution environment.
- Your Lambda code has a valid template.yaml file
- VS Code or your preferred IDE if you want to use breakpoints
2. Example SAM Template
Example template.yaml:
Resources:
MyFunction:
Type: AWS::Serverless::Function
Properties:
Handler: app.lambda_handler
Runtime: python3.11
CodeUri: .
MemorySize: 128
Timeout: 10
- Handler: . (e.g., app.lambda_handler → app.py file with lambda_handler function)
- Runtime: Should match the runtime your Lambda uses
3. Create a Test Event
Make an event.json file to simulate Lambda input:
{
"name": "Test User",
"id": 123
}
4. Run the Lambda Locally
To execute your function locally without deploying:
sam local invoke MyFunction --event event.json
- Runs your code in a Docker container
- Uses the Lambda runtime specified in your template
- Outputs logs to your terminal
5. Debug with Breakpoints
Step A: Start in Debug Mode
Run the Lambda with a debug port open:
sam local invoke MyFunction \
--event event.json \
--debug-port 5858
For API Gateway events:
sam local start-api --debug-port 5858
Step B: Attach the Debugger (VS Code Example)
Create .vscode/launch.json:
{
"version": "0.2.0",
"configurations": [
{
"name": "Connect to AWS SAM Local (Python)"
"type": "python",
"request": "attach",
"connect": { "host": "localhost", "port": 5858 },
"pathMappings": [
{
"localRoot": "${workspaceFolder}",
"remoteRoot": "/var/task"
}
]
}
]
}