How do I subscribe a Lambda function to an Amazon SNS topic in the same account?

Last updated: 2019-08-30

I want to subscribe my AWS Lambda function to an Amazon Simple Notification Service (Amazon SNS) topic in my AWS account. How do I do that?

Resolution

Note: The instructions in this article follow those in Tutorial: Using AWS Lambda with Amazon Simple Notification Service. However, this article provides same-account setup instructions. For prerequisites and cross-account setup instructions, see the tutorial.

1.    Create an Amazon SNS topic by running this command:

Note: Replace lambda-same-account with the name that you want for your topic.

$ aws sns create-topic --name lambda-same-account

Note the topic's Amazon Resource Name (ARN) returned in the command output. You'll need it later.

2.    Create an execution role for Lambda to access AWS resources. Note the role's ARN. You'll need it later.

3.    Create a deployment package. (Follow steps 1 and 2 in the tutorial.)

4.    Create a Lambda function by running this command:

Note: Replace sns-same-account with the name you want for your function. Replace arn:aws:iam::123456789012:role/service-role/lambda-sns-role with your execution role's ARN.

$ aws lambda create-function --function-name sns-same-account \
--zip-file fileb://function.zip --handler index.handler --runtime nodejs8.10 \
--role arn:aws:iam::123456789012:role/service-role/lambda-sns-role \
--timeout 60

Note the function's ARN returned in the command output. You'll need it in the next step.

5.    Add Lambda permissions for your Amazon SNS topic by running this command:

Note: Replace sns-same-account with the name you gave your function. Replace arn:aws:sns:us-east-1:123456789012:lambda-same-account with your topic's ARN.

$ aws lambda add-permission --function-name sns-same-account \
--source-arn arn:aws:sns:us-east-1:123456789012:lambda-same-account \
--statement-id sns-same-account --action "lambda:InvokeFunction" \
--principal sns.amazonaws.com

6.    Subscribe your Lambda function to the Amazon SNS topic by running this command:

Note: Replace arn:aws:sns:us-east-1:123456789012:lambda-same-account with your topic's ARN. Replace arn:aws:lambda:us-east-1:123456789012:function:sns-same-account with your function's ARN.

$ aws sns subscribe --protocol lambda \
--topic-arn arn:aws:sns:us-east-1:123456789012:lambda-same-account \
--notification-endpoint arn:aws:lambda:us-east-1:123456789012:function:sns-same-account

7.    Test the subscription by publishing a sample message by running this command:

Note: Replace arn:aws:sns:us-east-1:123456789012:lambda-same-account with your topic's ARN.

$ aws sns publish --message "Hello World" --subject Test \
--topic-arn arn:aws:sns:us-east-1:123456789012:lambda-same-account

This returns a message ID, confirming that the message is successfully published to your topic.


Did this article help you?

Anything we could improve?


Need more help?