Invoking lambda function using SNS Trigger

Introduction

In this post, we are going to learn invoking lambda function using SNS Trigger. We will use SNS topic to display how lambda function captures SNS notifications.

Prerequisites

  • SNS topic
  • Lambda function

Create SNS Topic

Go to SNS management console. Create a new topic with name LambdaSNSTopic. For more information see AWS documentation on Creating SNS topic.

Add trigger to a lambda function

Go to Lambda console and create a new lambda function.

  1. Under Configure triggers -> Add trigger SNS.
  2. Select SNS Topic LambdaSNSTopic and click on ‘Enter value’. It will replace SNS topic name from its ARN. Click Next.
  3. Under basic information. Enter name : lambdaSNSIntegrationFunction. Select runtime Java 8.
  4. Upload function package*: aws-examples-0.0.1-SNAPSHOT.jar file (Download from here).
  5. Enter Handler*: com.aws.example.lambda.SNSNotificationHandler::handleRequest
  6. Choose an existing role (lambdaFunctionTestRole) if already created. Otherwise select ‘create new role from templates’ and enter Role name:lambdaFunctionTestRole. Select Policy templates: Basic Edge Lambda permissions. For more details follow: configure and test lambda functions.
  7. Click Next
  8. Click on ‘Create Function’

We have successfully added a trigger to our lambda function.

AWS Lambda function test

Now, we need to test our function. Enter following text as an input for ‘Hello World’ sample test event.

{
"Type": "Notification",
"Subject": "My First Message",
"Message": "lambda function called!"
}

Now click on Save and Test button. You must see ‘Execution result: succeeded’. Expand details label to see returned string from lambda function.

Publish SNS message to lambda function

Now, its time to test our lambda function by consuming SNS notification message. Go to SNS dashboard and select SNS topic: LambdaSNSTopic. On Topic LambdaSNSTopic details page click on ‘Publish to topic’ button and enter:
Subject: My First Message
Message format: Raw
Message: lambda function called!

Click on ‘Publish Message’.

To check success we need to open cloud monitor logs. Open Monitoring section under Lambda function (lambdaSNSIntegrationFunction) details page. There is a link View Logs in CloudWatch. Open that link and you will be redirected to Cloud watch Logs section for lambdaSNSIntegrationFunction. To find success logs of SNS notification open recent log stream.

Conclusion

I hope this post will help you to understand How to add SNS trigger with a lambda function.

Leave a Reply

Your email address will not be published. Required fields are marked *