Skip to content

How do I use a Lambda function to publish a message to an Amazon SNS topic?

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 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:

  1. Open the Amazon SNS console.

  2. Create an Amazon SNS topic.

  3. On the details page, copy the Amazon Resource Name (ARN) to use in a later step.

  4. Open the Lambda console.

  5. Create a Lambda function.

  6. 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.

  7. Choose Deploy.

  8. Choose the Configuration tab, and then choose Permissions.

  9. Choose Role name, select Add permissions, and then select Create inline policy.

  10. 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.

  11. 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?

AWS OFFICIALUpdated 4 months ago