Run a Lambda function on local environment with AWS CDK and SAM
- Tomasz Łakomy
When developing a CDK stack with Lambda function(s), you may want to verify the result of your changes without running
cdk deploy every few minutes. After all, CloudFormation deployments do take a while (alternatively you might consider using CDK hotswaps to speed up your CDK deployments).
Luckily, there's another way - running a CDK-based Lambda function on local environment with AWS SAM.
Install the AWS SAM (Serverless Application Model) CLI using this guide. AWS SAM CLI is available for Linux, MacOS and Windows.
cdk synth --no-staging > template.yamlin order to create a CloudFormation template and store it in a
Find the logical ID for your Lambda function in template.yaml. It will look like MyFunction12345678, where 12345678 represents an 8-character unique ID that the AWS CDK generates for all resources. The line right after it should look like
Run the function by executing:
sam local invoke MyFunction12345678(replace
MyFunction12345678with the logical ID of your Lambda function)
We can also pass custom events to the function. To execute a lambda function locally with a custom event, run
sam local invoke HelloLambda3D9C82D6 -e sample_events/hello.json
And we're done! Now you can see the output of your Lambda function in the console.
Tired of switching between AWS console tabs? 😒
Cloudash provides clear access to CloudWatch logs and metrics, to help you make quicker decisions.
Try it for free: