How do I use webhooks to publish Amazon SNS messages to Amazon Chime, Slack, or Microsoft Teams?

4 minute read
0

I want to send notifications from Amazon Simple Notification Service (Amazon SNS) messages to Amazon Chime, Slack, or Microsoft Teams.

Short description

You can use Amazon SNS to send notification messages to HTTP or HTTPS endpoints, such as webhook URLs. However, certain webhooks expect JSON key-value pairs that Amazon SNS doesn't support when the HTTP or HTTPS subscription is confirmed.

For example, Amazon Chime webhooks expect a JSON request with a message string that corresponds to a Content key. Similarly, Slack and Microsoft Teams webhooks expect a JSON request with a message string that corresponds to a text key.

To transform the JSON document of an Amazon SNS message body so that the webhook endpoint can process, use an AWS Lambda function.

Note: For a list of the key-value pairs in the JSON document of an Amazon SNS message body, see HTTP/HTTPS subscription confirmation JSON format.

Resolution

Create an SNS topic

If you haven't done so already, create an SNS topic with a unique name.

Create a Lambda function

Follow the instructions to create a Lambda function. Your Lambda function code must include logic to transform your SNS topic's notification messages for the type of webhook endpoint that you use.

For examples, see the following Python code snippets for Amazon Chime, Slack, and Microsoft Teams webhooks.

Example Python code snippet for Amazon Chime

Amazon Chime webhooks expect a JSON request with a message string that corresponds to a Content key. For more information, see Creating webhooks for Amazon Chime.

import urllib3import json

http = urllib3.PoolManager()

def lambda_handler(event, context):
    url = "https://hooks.chime.aws/incomingwebhooks/xxxxxxx"
    msg = {"Content": event["Records"][0]["Sns"]["Message"]}
    encoded_msg = json.dumps(msg).encode("utf-8")
    resp = http.request("POST", url, body=encoded_msg)
    print(
        {
            "message": event["Records"][0]["Sns"]["Message"],
            "status_code": resp.status,
            "response": resp.data,
        }
    )

Note: Replace https://hooks.chime.aws/incomingwebhooks/xxxxxxx with your webhook URL.

Example Python code snippet for Slack

Slack webhooks expect a JSON request with a message string that corresponds to a text key. They also support message customization to add a username and icon, or override the webhook's default channel. For more information, see Sending messages using incoming webhooks on the Slack website.

import urllib3import json

http = urllib3.PoolManager()

def lambda_handler(event, context):
    url = "https://hooks.slack.com/services/xxxxxxx"
    msg = {
        "channel": "#CHANNEL_NAME",
        "username": "WEBHOOK_USERNAME",
        "text": event["Records"][0]["Sns"]["Message"],
        "icon_emoji": "",
    }

    encoded_msg = json.dumps(msg).encode("utf-8")
    resp = http.request("POST", url, body=encoded_msg)
    print(
        {
            "message": event["Records"][0]["Sns"]["Message"],
            "status_code": resp.status,
            "response": resp.data,
        }
    )

Note: Replace https://hooks.slack.com/services/xxxxxxx with your webhook URL, and #CHANNEL_NAME with the destination channel's name.

Example Python code snippet for Microsoft Teams

Microsoft Teams webhooks expect a JSON request with a message string that corresponds to a text key. For more information, see Create and send messages on the Microsoft Teams website.

import urllib3import json

http = urllib3.PoolManager()

def lambda_handler(event, context):
    url = "https://outlook.office.com/webhook/xxxxxxx"
    msg = {"text": event["Records"][0]["Sns"]["Message"]}
    encoded_msg = json.dumps(msg).encode("utf-8")
    resp = http.request("POST", url, body=encoded_msg)
    print(
        {
            "message": event["Records"][0]["Sns"]["Message"],
            "status_code": resp.status,
            "response": resp.data,
        }
    )

Note: Replace https://outlook.office.com/webhook/xxxxxxx with your webhook URL.

Test the Lambda function

Complete the following steps:

  1. On the Functions page of the Lambda console, choose your function.
  2. Open the Test tab. In Event name, enter a name.
  3. Choose the Template dropdown list, and then select SNS Topic Notification.
  4. Choose Save, and then choose Test.

If the test invocation succeeds with a 200 status code, then the Amazon SNS notification message was accepted by your webhook and delivered to the channel.

If the test invocation fails with a 4xx status code, then verify that the webhook URL key-value pair is correct and accepted by your destination webhook.

For more information, see Invoke the Lambda function using the console code editor.

Add an SNS topic and subscribe the Lambda function to it

Complete the following steps:

  1. On the Functions page of the Lambda console, choose your function.
  2. Under Function overview, choose Add trigger.
  3. Choose the Trigger configuration dropdown list, and then select SNS.
  4. For SNS topic, choose the SNS topic that you created earlier.
  5. Choose Add.
  6. Subscribe your Lambda function to the SNS topic.

Now that you subscribed your function to your SNS topic, messages published to the topic are forwarded to the function and your webhook.

Related information

How can I resolve the error that I receive when I subscribe a Lambda function to a push-based event source in CloudFormation?

Monitoring AWS services using Amazon Q Developer in chat applications

2 Comments

I would like to know how AWS Lambda function will authenticate to the Microsoft team channel to post the message. once I create the incoming webhooks in teams channel and update the link in the Lambda function, is there any IAM roles I need to setup for Lambda function to publish the message / notification to team channel ?

replied 5 months ago

Thank you for your comment. We'll review and update the Knowledge Center article as needed.

profile pictureAWS
MODERATOR
replied 5 months ago