loading...
Lambda Store

AWS SAM Node.js Example

svenanderson profile image Sven Anderson ・3 min read

Yesterday, one of Lambda Store users complained about how difficult it is to deploy AWS Lambda functions to the AWS. I told him about AWS SAM and Serverless framework. A few hours later, he texted to thank me :) Then I decided to write this blog. I will simply create a hello world AWS lambda function (Node.js) and deploy it to AWS as well as test it in my laptop.

Step 1: Install AWS SAM as described here

Step 2: Run sam init in any folder.

  • Select AWS Quick Start Templates
  • Select 1 - nodejs12.x
  • Enter your project name.
  • Select 1 - Hello World Example SAM will generate your project in a new folder.

Step 3: Let's see the code (hello-world > app.js)

// const axios = require('axios')
// const url = 'http://checkip.amazonaws.com/';
let response;

exports.lambdaHandler = async (event, context) => {
    try {
        // const ret = await axios(url);
        response = {
            'statusCode': 200,
            'body': JSON.stringify({
                message: 'hello world',
                // location: ret.data.trim()
            })
        }
    } catch (err) {
        console.log(err);
        return err;
    }

    return response
};

You can edit the code and add some fancy stuff like reading data from redis (lambda.store 😉 )

Step 4: Let's check the SAM template file (template.yaml)

AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Description: >
  sam-nodejs-example

  Sample SAM Template for sam-nodejs-example

# More info about Globals: https://github.com/awslabs/serverless-application-model/blob/master/docs/globals.rst
Globals:
  Function:
    Timeout: 3

Resources:
  HelloWorldFunction:
    Type: AWS::Serverless::Function # More info about Function Resource: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#awsserverlessfunction
    Properties:
      CodeUri: hello-world/
      Handler: app.lambdaHandler
      Runtime: nodejs12.x
      Events:
        HelloWorld:
          Type: Api # More info about API Event Source: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#api
          Properties:
            Path: /hello
            Method: get

Outputs:
  # ServerlessRestApi is an implicit API created out of Events key under Serverless::Function
  # Find out more about other implicit resources you can reference within SAM
  # https://github.com/awslabs/serverless-application-model/blob/master/docs/internals/generated_resources.rst#api
  HelloWorldApi:
    Description: "API Gateway endpoint URL for Prod stage for Hello World function"
    Value: !Sub "https://${ServerlessRestApi}.execute-api.${AWS::Region}.amazonaws.com/Prod/hello/"
  HelloWorldFunction:
    Description: "Hello World Lambda Function ARN"
    Value: !GetAtt HelloWorldFunction.Arn
  HelloWorldFunctionIamRole:
    Description: "Implicit IAM Role created for Hello World function"
    Value: !GetAtt HelloWorldFunctionRole.Arn

Here, the file creates HelloWorldFunction also configure API gateway so you can call your function via a public URL.

Step 5: Build the application via sam build

Step 6: Deploy to the AWS via sam deploy --guided

  • Stack name: Enter a name for your application stack. All resources will be created under this stack name.
  • Choose your favorite region
  • Confirm the remaining change requests with y You should see something like this: Alt Text

Troubleshooting: If you get the following error, this probably means that your AWS CLI configuration is incorrect or missing. Check here on how to configure AWS CLI.
Error: Failed to create managed resources: An error occurred (InvalidClientTokenId) when calling the CreateChangeSet operation: The security token included in the request is invalid.

Step 7: Now let's test the function from AWS console. Find your function from AWS Lambda console. You can test using the Test button on top right. Or you can click on API Gateway and click the API Endpoint URL.
Alt Text

Step 8: Let's run the function locally via sam local invoke
Alt Text

Discussion

pic
Editor guide