AWS lambda 'hello world' using serverless - Part 2
In the previous post, we learn the basics of serverless.
This post we are going to learn how to create simple hello world lambda function using serverless.
Install Pre-requisites
- Create AWS account.
- Download Node
- Download AWS IAM credentials from AWS console and save it locally.
Step-1: Install Serverless framework
npm i -g serverless
Step-2: Add AWS credentials to serverless framework
sls config credentials --provider aws --key AKIASFFZ4C46CH46OPOT --secret X607c+ju1HQQ9H0emwqeXm9mO1234jahgdjasdfuowlF
Step-3: Create a serverless service
serverless create --template aws-nodejs --path my-hellow-world-service
Step-4: Deploy lambda function to cloud
sls deploy
Step-5: Invoke lambda function from local machine
sls invoke --function hello
Step-6: Get cloud lambda function logs
serverless logs -f hello
Step-7: Execute a lambda function from locally
sls invoke local --function hello
Step-8: Remove lambda function from cloud
serverless remove
Serverless commands
npm i -g serverless
serverless
sls
sls config credentials --provider aws --key AKIASFFZ4C46CH46OPOT --secret X607c+ju1HQQ9H0emwqeXm9mO1234jahgdjasdfuowlF
sls create --help
sls create --template aws-nodejs
sls deploy
sls invoke --function hello
sls invoke local --function hello
serverless logs -f hello
serverless remove
Hello World Lambda Function
- After run step-3 it will create a simple hello world application.
- Folder contains handler.js file and serverless.yml file.
- Just go to handler.js file and write below code
'use strict';
module.exports.hello = async (event) => {
return {
statusCode: 200,
body: JSON.stringify({
message: 'Serverless Hello world'
}, null, 2),
};
};
- Update serverless.yml file with below details
service: my-hellow-world-service
provider:
name: aws
runtime: nodejs10.x
stage: dev
region: us-east-1
functions:
hello:
handler: handler.hello
events:
- http:
path: getData
method: GET
- After the above changes, just run, step-4 & 5 commands
- It gives a response in the console like below
{
message: 'Serverless Hello world'
}