Invoke your CDK configured AWS Lambda functions locally on macOS
Often times you want to execute your lambda function locally before you deploy them. Especially when you have functions configured with CDK, you don’t want to mess around with other team members environments. SAM(Serverless Application Model) provides the best solution for that. In this article, I will explain how to integrate SAM into your CDK environment, using Colima as Docker runtimes. In the last section, I share the troubleshooting guide for invoking functions.
Why Colima?
SAM uses Docker to execute functions locally. Colima has a minimum setup to run your docker-based application; it’s fast, simple cli, and has no popups asking you to download the newer version of the application every time you start your mac.
There’s already a great guide to set up Colima in your environment.
Setup SAM Cli
Just follow the steps in https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-cli-install.html. Remember, you don’t have to install Docker Desktop.
Set DOCKER_HOST
SAM cli looks into DOCKER_HOST
in your environment when invoking a function to connect to the Docker daemon. However, Colima uses its own host to work with other Docker tools such as Desktop. We need to set DOCKER_HOST
explicitly. There are two options to do it:
Option1. Modify your .zshenv
Docker socket is located at $HOME/.colima/default/docker.sock (you can find this by $ colima status
) add to your zsh environment
// .zshenv
export DOCKER_HOST="unix://${HOME}/.colima/default/docker.sock"
Then run $ source ~/.zshenv
Option2. Use symlink
You can link Colima’s docker socket. This is useful when you are not using any other Docker runtimes.
sudo ln -sf $HOME/.colima/default/docker.sock /var/run/docker.sock
Invoke a function
We will build our codebase (when you are using TypeScript) and generate CloudFormation json file with cdk synth
. This is required whenever we update our codebase or Stack configuration.
Then we can invoke a function with an event:
echo '{"queryStringParameters": { "message": "hello" }}' | sam local invoke -t ./cdk.out/{Your CloudFormation template}.template.json {functionName} --profile {your profile} --region {your region} --event -
If you are not so sure about your functionName
just add a random string, SAM will suggest you the list of functionName
you can use to execute.
Troubleshooting
Lambda fails with the message aws lambda: Error:Runtime exited with error: signal: killed
- Increasing memory size should fix the issue
Mounting volume fails with the messageTimed out while attempting to establish a connection to the container.
- Try restarting the docker container
- With Colima, you should try
colima stop && colima start
Thank you for reading! If this article helped you, please give 👏