Skip to content

Instantly share code, notes, and snippets.

@DaisukeMiyamoto
Last active December 5, 2021 19:48
Show Gist options
  • Save DaisukeMiyamoto/32ef3a29f2d996a5283969738c0845e9 to your computer and use it in GitHub Desktop.
Save DaisukeMiyamoto/32ef3a29f2d996a5283969738c0845e9 to your computer and use it in GitHub Desktop.
Send message from Amazon SNS to Slack by AWS Lambda
import boto3
import json
import logging
import os
from urllib.request import Request, urlopen
from urllib.error import URLError, HTTPError
SLACK_CHANNEL = os.environ['slackChannel']
HOOK_URL = os.environ['slackUrl']
logger = logging.getLogger()
logger.setLevel(logging.INFO)
def lambda_handler(event, context):
logger.info("Event: " + str(event))
for record in event['Records']:
subject = record['EventSource']
if record['Sns']['Subject']:
subject += ' / ' + record['Sns']['Subject']
try:
message_json = json.loads(record['Sns']['Message'])
print(message_json)
message = json.dumps(message_json, indent=4)
color = 'good'
except (json.JSONDecodeError, TypeError):
message = str(record['Sns']['Message'])
color = 'warning'
slack_message = {
'channel': SLACK_CHANNEL,
'attachments': [
{
'title': subject,
'text': message,
'color': color,
}
]
}
req = Request(HOOK_URL, json.dumps(slack_message).encode('utf-8'))
try:
response = urlopen(req)
response.read()
logger.info("Message posted to %s", slack_message['channel'])
except HTTPError as e:
logger.error("Request failed: %d %s", e.code, e.reason)
except URLError as e:
logger.error("Server connection failed: %s", e.reason)
{
"Records": [
{
"EventSource": "aws:sns",
"EventVersion": "1.0",
"EventSubscriptionArn": "arn:aws:sns:ap-northeast-1:{{accountId}}:ExampleTopic",
"Sns": {
"Type": "Notification",
"MessageId": "95df01b4-ee98-5cb9-9903-4c221d41eb5e",
"TopicArn": "arn:aws:sns:ap-northeast-1:123456789012:ExampleTopic",
"Subject": "example subject",
"Message": "{\"c\": 0,\"b\": 0,\"a\": 0}",
"Timestamp": "1970-01-01T00:00:00.000Z",
"SignatureVersion": "1",
"Signature": "EXAMPLE",
"SigningCertUrl": "EXAMPLE",
"UnsubscribeUrl": "EXAMPLE",
"MessageAttributes": {
"Test": {
"Type": "String",
"Value": "TestString"
},
"TestBinary": {
"Type": "Binary",
"Value": "TestBinary"
}
}
}
}
]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment