Deploying a simple Lambda function using the Serverless framework and AWS as the provider
- Set up your Serverless project:
# Install the Serverless CLI
npm install -g serverless
# Create a new project
serverless create --template aws-nodejs --path my-service
2. Define your Lambda functions:
In the handler.js file, add the following code:
// handler.js
exports.helloWorld = async (event, context) => {
// Return a simple greeting
return {
statusCode: 200,
body: JSON.stringify({ message: 'Hello, World!' })
};
};
In the serverless.yml
file, add the following code:
service: my-service
provider:
name: aws
runtime: nodejs14.x
functions:
helloWorld:
handler: handler.helloWorld
This defines a service with a single function called “hello” that uses the handler.hello
function as its entry point.
3. Install dependencies:
In this case, there are no external dependencies to install.
4. Deploy your functions:
serverless deploy
This will package your code and upload it to AWS Lambda. The output will include the endpoint URL for your function.
5. Test your functions in AWS:
serverless invoke -f helloWorld
This will invoke the “hello” function and display the response.
6. Test your function locally:
serverless invoke local -f helloWorld
The output will be
{
"statusCode": 200,
"body": "{\"message\":\"Hello, World!\"}"
}
These are just a few example commands, but they should give you an idea of how to use the Serverless framework to deploy Lambda functions.