Listening to SNS events

alt text alt text

You will require the following AWS permissions:

  • sns:Publish
  • sns:CreateTopic
  • sns:sns:SetTopicAttributes
  • lambda:CreateEventSourceMapping

 

Create a lambda function configuration that will listen to customSNSTopic.

functions:
  customSnsListener:
    handler: handler.customSnsListener
    events:
      - sns: customSNSTopic

Let's create a handler.js file.

module.exports.customSnsListener = (event, context, callback) => {
  console.log('EVENT', JSON.stringify(event)),
  callback(null);
}

 

After deploying, you can retrieve the SNS Topic ARN that was generated. The output of serverless deploy -v will contain the string

CustomSnsListenerLambdaFunctionQualifiedArn: arn:aws:lambda:eu-west-1:xxxxxxxxxxxx:function:sns-event-handler-dev-customSnsListener:1

where xxxxxxxxxxxx - is aws account id. Just use it to generate the SNS topic id: arn:aws:sns:eu-west-1:xxxxxxxxxxxx:customSNSTopic.

Now, you can publish something to this topic using aws cli:

aws sns publish --topic-arn arn:aws:sns:eu-west-1:xxxxxxxxxxxx:customSnsListener --subject test --message "this is a string message"

You should get a response, similar to:

{
    "MessageId": "xxx"
}

 

Now, if you check logs of the lambda function, you'll see that we successfully invoked the event:

{
    "Records": [
        {
            "EventSource": "aws:sns",
            "EventVersion": "1.0",
            "EventSubscriptionArn": "arn:aws:sns:eu-west-1:xxxxxxxxxxxx:customSnsListener:81d84698-6385-4845-9650-39ab67cc2c9f",
            "Sns": {
                "Type": "Notification",
                "MessageId": "xxxxxxxxxxxx",
                "TopicArn": "arn:aws:sns:eu-west-1:xxxxxxxxxxxx:customSnsListener",
                "Subject": "test",
                "Message": "this is a string message",
                "Timestamp": "2018-06-05T11:34:53.797Z",
                "SignatureVersion": "1",
                "Signature": "xxxxxxxxxxxx",
                "SigningCertUrl": "xxxxxxxxxxxx",
                "UnsubscribeUrl": "xxxxxxxxxxxx",
                "MessageAttributes": {}
            }
        }
    ]
}