How can I publish a message to an Amazon SNS topic using a Lambda function?

2 minute read
0

I want to publish a message to an Amazon Simple Notification Service (Amazon SNS) topic from an AWS Lambda function.

Resolution

Follow these steps to send a message to an Amazon SNS topic using a Lambda function.

Note: The example in this article uses a Python runtime, but you can use your preferred Lambda runtimes.

1.    Create an Amazon SNS topic.

2.    Create a Lambda function.

3.    From the Lambda function, make sure that the Lambda execution role has permissions to publish the SNS message similar to the following:

Note: Replace your-region, your-account-number, and your-topic-name with your variables.

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "PublishSNSMessage",
      "Effect": "Allow",
      "Action": "sns:Publish",
      "Resource": "arn:aws:sns:<your-region>:<your-account-number>:<your-topic-name>"
    }
  ]
}

4.     Choose the Code tab. Then, in Code source, copy and paste the following code for the Publish Boto3 action into the code editor:

import json
import boto3
client = boto3.client('sns')
def lambda_handler(event, context):
   response = client.publish(TopicArn='arn:aws:sns:<region>:<account-number>:<topic-name>',Message="Test message")
   print("Message published")
   return(response)

5.    Test your Lambda function.

If your Lambda function is connected to an Amazon Virtual Private Cloud (Amazon VPC), then do one of the following:

If your Lambda function requires internet access, make sure that you grant internet access. For more information, see How do I give internet access to a Lambda function that's connected to an Amazon VPC?

-or-

For private networks, create an Amazon VPC endpoint for Amazon SNS in the same VPC. For more information, see Creating an Amazon VPC endpoint for Amazon SNS.

Related information

Why do I get an authorization error when I try to subscribe my Lambda function to my Amazon SNS topic?

AWS OFFICIAL
AWS OFFICIALUpdated a year ago