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 use a Lambda function to send a message to an Amazon SNS topic.
Note: The example in this article uses a Python runtime, but you can also use your preferred Lambda runtimes.
-
Create an Amazon SNS topic.
-
Create a Lambda function.
-
From the Lambda function, make sure that the Lambda execution role has permissions to publish the SNS message, similar to the following:
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "PublishSNSMessage",
"Effect": "Allow",
"Action": "sns:Publish",
"Resource": "arn:aws:sns:your-region:your-account-number:your-topic-name"
}
]
}
Note: Replace your-region, your-account-number, and your-topic-name with your variables.
-
On the Lambda Functions page, 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:your-region:account-number:topic-name',Message="Test message")
print("Message published")
return(response)
-
Test your Lambda function.
If your Lambda function is connected to an Amazon Virtual Private Cloud (Amazon VPC), then do one of the following:
Related information
Why do I get an authorization error when I try to subscribe my Lambda function to my Amazon SNS topic?