How to trigger a Lambda with a SQS message

AWS SAM template to execute a Lambda Function by writing a message in a SQS queue. Cloudformation world


May 12, 2021
featured image

Overview

AWS resources we need

  • Lambda Function
  • SQS queue
  • Lambda Role
  • SQS Policy

Lambda Function

      
let response;

exports.lambdaHandler = async (event, context) => {
    try {
        response = {
            'statusCode': 200,
            'body': JSON.stringify({
                message: 'hello world',
            })
        }
    } catch (err) {
        console.log(err);
        return err;
    }

    return response
};

     

SAM template

      
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Description: >
  Trigger a Lambda function when writing a message in SQS

Parameters:
  Environment:
    Type: String
    Description: example, staging

Resources:
  MyQueue:
    Type: AWS::SQS::Queue
    Properties:
      QueueName: !Sub "${Environment}-my-queue"

  MyFunction:
    Type: AWS::Serverless::Function
    DependsOn:
      - MyQueue
    Tags:
      Name: !Sub "${Environment}-my-function"
    Properties:
      CodeUri: hello-world/
      Handler: app.lambdaHandler
      Runtime: nodejs12.x
      Events:
        MySQSEvent:
          Type: SQS
          Properties:
            Queue: !GetAtt MyQueue.Arn
            BatchSize: 10
        Role:
          Fn::GetAtt:
            - MyFunctionRole
            - Arn
  MyQueuePolicy:
    Type: AWS::SQS::QueuePolicy
    DependsOn:
      - MyQueue
    Properties:
      PolicyDocument:
        Version: "2012-10-17"
        Statement:
          - Effect: Allow
            Principal:
              Service:
                - "sqs.amazonaws.com"
            Action:
              - "sqs:*"
            Resource:
              Fn::GetAtt:
                - MyQueue
                - Arn
      Queues:
        - Ref: MyQueue

  MyFunctionRole:
    Type: AWS::IAM::Role
    Properties:
      AssumeRolePolicyDocument:
        Statement:
          - Effect: Allow
            Action: "sts:AssumeRole"
            Principal:
              Service:
                - "lambda.amazonaws.com"
        Version: "2012-10-17"
      ManagedPolicyArns:
        - arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole
      Policies:
        - PolicyName: AccessAll
          PolicyDocument:
            Statement:
              - Effect: Allow
                Action: "sqs:*"
                Resource:
                  - Fn::GetAtt:
                      - "MyQueue"
                      - "Arn"
            Version: "2012-10-17"

     

Deploy

Build our lambda and template. This will check also the syntax of your template
      
sam build
      
Only for the first time run and follow the steps
      
sam deploy --guided
      
The second time and so on you can execute
      
sam deploy --no-confirm-changeset
      

Resources

Photo by Juan Rumimpunu on Unsplash


aws sqs lambda nodejs dev