Running and debugging AWS Lambda functions locally with the Serverless framework and VS Code

One of the complaints developers often have for AWS Lambda is the inability to run and debug functions locally. For Node.js at least, the Serverless framework and VS Code provides a good solution for doing just that.

An often underused feature of the Serverless framework is the invoke local command, which runs your code locally by emulating the AWS Lambda environment. Granted, it’s not a perfect simulation and only works with Node.js and Python, but it has been good enough for most of local development needs.

With VS Code, you have the ability to debug Node.js applications, including the option to launch an external program.

Put the two together and you have the ability to locally run and debug your Lambda functions.

Step 1 : install Serverless framework as dev dependency

In general, it’s a good idea to install Serverless framework as a dev dependency in a project because:

  1. it allows other developers (and the CI server) to use the Serverless framework for deployment without having to install it themselves
  2. it prevents incompatibility issues when you have an incompatible version of Serverless framework installed to that used by the serverless.yml file in the project
  3. since Serverless v1.16.0 dev dependencies are excluded from the deployment package so it wouldn’t add to your deployment size (this is broken in the current version v1.18.0 but should be fixed shortly)

Step 2 : add debug configuration

Invoke the “sls invoke local” CLI command against the “hello” function with an empty object {} as input. It’s also possible to invoke the function with a JSON file, see doc here.

Step 3 : enjoy!

There, nice and easy :-)

Couple of things to note:

  • if your function depends on environment variables, then you can set those up in the launch.json config file in step 2
  • if your function needs to access other AWS resources, then you also need to setup the relevant environment variables (eg. AWS_PROFILE) for the aws-sdk to access those resources in the correct AWS account
  • this approach will not work for recursive functions (well, the recursion will happen on the deployed Lambda function, so you won’t be able to debug it)

Leave a Reply

Your email address will not be published.