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.
Complete the following steps:
-
Open the Amazon SNS console.
-
Create an Amazon SNS topic.
-
On the details page, copy the Amazon Resource Name (ARN) to use in a later step.
-
Open the Lambda console.
-
Create a Lambda function.
-
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-sns-topic-arn',Message="Test message")
print("Message published")
return(response)
Note: Replace your-sns-topic-arn with your Amazon SNS topic ARN that you copied in a previous step.
-
Choose Deploy.
-
Choose the Configuration tab, and then choose Permissions.
-
Choose Role name, select Add permissions, and then select Create inline policy.
-
Choose the JSON tab, and enter the following AWS Identity and Access Management (IAM) policy:
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "PublishSNSMessage",
"Effect": "Allow",
"Action": "sns:Publish",
"Resource": "arn:aws:sns:your-sns-topic-arn"
}
]
}
Note: Replace your-sns-topic-arn with your Amazon SNS topic ARN that you copied in a previous step.
-
Choose Next, and then choose Create policy.
If your Lambda function's 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?