Last active
August 7, 2019 08:29
-
-
Save htnosm/c2ff6a4f7e30b81ba80d98a6766277d1 to your computer and use it in GitHub Desktop.
[Lambda] e.g. Amazon SNS -> Lambda -> Slack
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
# -*- coding: utf-8 -*- | |
import boto3 | |
import json | |
import logging | |
import os | |
from base64 import b64decode | |
from urllib.request import Request, urlopen | |
from urllib.error import URLError, HTTPError | |
# The base-64 encoded, encrypted key (CiphertextBlob) stored in the kmsEncryptedHookUrl environment variable | |
ENCRYPTED_HOOK_URL = os.environ['kmsEncryptedHookUrl'] | |
# The Slack channel to send a message to stored in the slackChannel environment variable | |
SLACK_CHANNEL = os.environ['slackChannel'] | |
SLACK_ICON_EMOJI = os.environ.get('slackIconEmoji', ':exclamation:') | |
SLACK_USERNAME = os.environ.get('slackUsername', 'incoming-webhook') | |
HOOK_URL = "https://" + boto3.client('kms').decrypt(CiphertextBlob=b64decode(ENCRYPTED_HOOK_URL))['Plaintext'].decode('utf-8') | |
logger = logging.getLogger() | |
logger.setLevel(logging.INFO) | |
def lambda_handler(event, context): | |
logger.info("Event: " + str(event)) | |
try: | |
message = json.loads(event['Records'][0]['Sns']['Message']) | |
except json.JSONDecodeError as e: | |
logger.warning("JSONDecodeError: %s", str(e)) | |
message = event['Records'][0]['Sns']['Message'] | |
except Exception as e: | |
logger.error("failed: %s", str(e)) | |
try: | |
subject = json.loads(event['Records'][0]['Sns']['Subject']) | |
except json.JSONDecodeError as e: | |
logger.warning("JSONDecodeError: %s", str(e)) | |
subject = event['Records'][0]['Sns']['Subject'] | |
except Exception as e: | |
logger.error("failed: %s", str(e)) | |
if len(message) > 0: | |
message = "```" + str(message) + "```" | |
if len(subject) > 0: | |
message = subject + "\n" + message | |
slack_message = { | |
'channel': SLACK_CHANNEL, | |
'icon_emoji': SLACK_ICON_EMOJI, | |
'username': SLACK_USERNAME, | |
'text': "%s" % (message) | |
} | |
logger.info("slack_message: " + str(slack_message)) | |
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) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Ref. cloudwatch-alarm-to-slack-python Lambda blueprint