How To Set Up A Local AWS Lambda Function
Services
15/07/2021
This is a quick, no frills guide to setting up your own Lambda function locally.
Step 1 - Install the SAM CLI
First off, you need the AWS SAM CLI to even get started. Instructions on how to install it for your respective operating system can be found here.
Grab a drink ☕️ as this might take a while.
Step 2 - Create a new SAM application
Some of you might be wondering, what the hell is a SAM application? Also called Serverless Application Model, it's basically a framework that hosts your Lambda function and any associated functionality (e.g. APIs, events and databases).
Once the CLI is installed, you can then create a new project with sam init
. You'll be guided through the process. And in my case, I've chosen the Hello World application template with Node.js as a runtime.
-----------------------Generating application:-----------------------Name: sam-tutorialRuntime: nodejs12.xDependency Manager: npmApplication Template: hello-worldOutput Directory: .
Step 3 - Understand the project structure
Open up your project in an IDE of your choice and you'll be greeted with the following structure. 🌳 Of course, file names may slightly differ depending on your configuration.
sam-tutorial/ ├── events/ │ └── event.json ├── hello_world/ # Contains the Lambda function │ ├── tests/ │ ├── .npmignore │ ├── app.js # Contains the Lambda handler logic │ └── package.json ├── .gitignore ├── README.md └── template.yaml # Configuration file of your SAM application
Step 4 - Run the Lambda function
In your terminal, change the directory to your SAM application and run sam build
. Be aware that for any changes that you make in the Lambda function, you will need to re-run this command.
Next on the list, Docker! 🐳 Boot up that bad boy. Now, you've got 2 options regarding how to run your function.
Invoke it with an event
You can invoke the function using an event specified in events/event.json
. To do that, simply run sam local invoke
.
Run an API server
Or perhaps you prefer to host your Lambda function with an API server that listens to any incoming calls. For that, run sam local start-api
.