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.

  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:

    {
        "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.

  4. 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)
    
  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:

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 month ago