OneCompiler

AWS lambda 'hello world' using serverless - Part 2

474

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

  1. Create AWS account.
  2. Download Node
  3. 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

  1. After run step-3 it will create a simple hello world application.
  2. Folder contains handler.js file and serverless.yml file.
  3. 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),
  };
};

  1. 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
  1. After the above changes, just run, step-4 & 5 commands
  2. It gives a response in the console like below
{
     message: 'Serverless Hello world'
}