Mohan pd.
Mohan pd. Author of The Coders Blog. Also a professional fullstack javascript developer working with various tech company and client around world.

Basic of Lamda and Related Resources

Oct 19, 2019 · 4 minutes
Basic of Lamda and Related Resources

Lambda note

Quick Start

Using AWS CodeStar will be a great choice to learn how to build, test, and deploy the lambda function to AWS. The following links are the best tutorials for learning how to use CodeStart and Lambda.

SAM local

SAM local is a tool for testing AWS lambda on your local machine. Before using it, you must install docker since SAM local runs your code inside the docker container. The following snippets show a simple usage of SAM local

Invoke a lambda function

template.yml

AWSTemplateFormatVersion: 2010-09-09
Transform: AWS::Serverless-2016-10-31
Resources:
  GetHelloWorld:
    Type: AWS::Serverless::Function
    Properties:
      Handler: index.get
      Runtime: nodejs6.10
      Role:
        Fn::ImportValue:
          !Join ['-', [!Ref 'ProjectId', !Ref 'AWS::Region', 'LambdaTrustRole']]
      Events:
        GetEvent:
          Type: Api
          Properties:
            Path: /
            Method: get

Invoking the lambda function via sam local and passing the event through -e option

# invode your lambda function, GetHelloWorld, on your local machin
$ sam local invode -e "event.json" GetHelloWorld

Futher reading:

Invode a API on local

sam local start-api provides a way to invoke your lambda function through local URL. The default URL is http://localhost:3000

# invoke the api with default setting
$ sam local start-api

# invoke the api with specific port
$ sam local start-api -p 5566

A Hello World lambda

Using aws CodeStart is quiet simple, we don’t need to worry about how to deploy the lambda function. However, if we want to deploy a function from scratch, we can use sam to deploy lambda functions to aws via CloudFormation. For example:

index.js

'use strict';

console.log('Loading function');

exports.handler = (event, context, callback) => {
    callback(null, 'Hello World!');
};

template.yaml

cat template.yaml 
AWSTemplateFormatVersion : '2010-09-09'
Transform: AWS::Serverless-2016-10-31

Description: A simple Hello World Serverless project
Resources:
  HelloWorld:
    Type: AWS::Serverless::Function
    Properties:
      Runtime: nodejs6.10
      Handler: index.handler
      CodeUri: .

event.json

{
	"foo": "Foo"
}

Then we use sam local to test our lambda function HelloWorld before deploying to aws

$ sam local invoke -e event.json HelloWorld

After testing the lambda success, we package our lambda function and deploy to aws via following commands

# create packaged-template.yaml and upload your code (.zip) to s3 bucket
$ BUCKET_NAME="aws-lambda-demo-bucket"
$ sam package --template-file template.yaml \
  --s3-bucket "$BUCKET_NAME" \
  --output-template-file packaged-template.yaml
  
# deploy the lambda function to aws
$ STACK_NAME="aws-lambda-stack"
$ sam deploy --template-file packaged-template.yaml \
  --stack-name "$STACK_NAME" \
  --capabilities CAPABILITY_IAM 

Futher reading:

A Hello World API

Previous example shows how to create a simple lambda on aws. Nevertheless, we can not trigger the lambda function through HTTP methods such as GET or POST. In order to access our lambda function via HTTP, we need to add an event into our lambda

template.yaml

AWSTemplateFormatVersion : '2010-09-09'
Transform: AWS::Serverless-2016-10-31

Description: A simple Hello World Serverless project
Resources:
  HelloWorld:
    Type: AWS::Serverless::Function
    Properties:
      Runtime: nodejs6.10
      Handler: index.handler
      CodeUri: .
      Events:
        ApiEvent:
          Type: Api
          Properties:
            Path: /hello
            Method: get

index.json

'use strict';

console.log('Loading function');

exports.handler = (event, context, callback) => {
  callback(null, {
    statusCode: 200,
    body: 'Hello World!'
  });
};

Then testing our lambda function on local machine

$ sam local start-api &
$ curl http://localhost:3000/hello

Finally, we update the code and deploy the lambda function on aws

# create packaged-template.yaml and upload your code (.zip) to s3 bucket
$ BUCKET_NAME="aws-lambda-demo-bucket"
$ sam package --template-file template.yaml \
  --s3-bucket "$BUCKET_NAME" \
  --output-template-file packaged-template.yaml
  
# deploy the lambda function to aws
$ STACK_NAME="aws-lambda-stack"
$ sam deploy --template-file packaged-template.yaml \
  --stack-name "$STACK_NAME" \
  --capabilities CAPABILITY_IAM 

open the AWS lambda console and click the invoke URL for test or run the following command

$ aws lambda invoke \   
--function-name hello-world-stack-helloworld-1WRBVCZXMYVS \ 
--region ap-northeast-1 \
--log-type Tail \
--payload '{"key1":"value1", "key2":"value2", "key3":"value3"}' \
output.txt

Further reading:

sma local cheat sheet

# generate s3 event
$ sam local generate-event s3 --bucket demo-bucke

# generate dynamodb event
$ sam local generate-event dynamodb

# generate api event
$ sam local generate-event api

# generate sns event
$ sam local generate-event sns

# invoke lambda function on local machine
$ sam local invoke -e /path/to/event.json ${LambdaResource}

# invoke lambda api server
$ sam local start-api