Published on

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

Tired of constantly switching between AWS Console tabs? 🤕
Time to boost your productivity with Cloudash — an AWS desktop client.

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.

Tired of switching between AWS console tabs? 😒

Cloudash provides a laser-focused view of your AWS API Gateway, Lambda and other resources - all in a single app.

Logs screen