Cloudash logo
Published on

Run a Lambda function on local environment with AWS CDK and SAM

Authors

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.

  1. Install the AWS SAM (Serverless Application Model) CLI using this guide. AWS SAM CLI is available for Linux, MacOS and Windows.

  2. Run cdk synth --no-staging > template.yaml in order to create a CloudFormation template and store it in a template.yaml file

  3. 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 Type: AWS::Lambda::Function.

  4. Run the function by executing: sam local invoke MyFunction12345678 (replace MyFunction12345678 with the logical ID of your Lambda function)

  5. 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.

Stay on top of your logs. ⚡️

Cloudash overview
Introducing Cloudash, a desktop app for monitoring your serverless services performance, invocations, errors and more.
Did a production incident happen last week? Or 20 seconds ago? With Cloudash you can search, filter and browse your serverless logs and metrics effortlessly.
Search for whatever you want, whenever you want. Cloudash comes with built-in filtering capabilities enabling to get to the bottom of your problems faster than ever before.
Get started here