Created
February 18, 2017 07:55
-
-
Save htnosm/bfa81dae76650b293c979ca889446eec to your computer and use it in GitHub Desktop.
[Lambda] e.g. DatadogMonitor->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
from __future__ import print_function | |
import boto3 | |
import json | |
import logging | |
import os | |
import re | |
from base64 import b64decode | |
from urllib2 import Request, urlopen, 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'] | |
HOOK_URL = "https://" + boto3.client('kms').decrypt(CiphertextBlob=b64decode(ENCRYPTED_HOOK_URL))['Plaintext'] | |
logger = logging.getLogger() | |
logger.setLevel(logging.INFO) | |
def lambda_handler(event, context): | |
logger.info("Event: " + str(event)) | |
snstext = event['Records'][0]['Sns'] | |
subject = snstext['Subject'] | |
message = snstext['Message'] | |
result = re.sub(r'\n', "", message) | |
result = re.sub(r'^.*distributionid:', "", result) | |
distributionid = re.sub(r' was .*$', "", result).upper() | |
logger.info("DistributionId: " + distributionid) | |
cf = boto3.client('cloudfront') | |
response = cf.get_distribution(Id=distributionid) | |
distributionconfig = response['Distribution']['DistributionConfig'] | |
try: | |
alias = distributionconfig['Aliases']['Items'][0] | |
except: | |
alias = '-' | |
originname = distributionconfig['Origins']['Items'][0]['DomainName'] | |
post_message = "DistributionId: " + distributionid + "\n" | |
post_message = post_message + "CNAME[0]: " + alias + "\n" | |
post_message = post_message + "Origin[0]: " + originname + "\n" | |
logger.info("Post Message: " + post_message) | |
slack_message = { | |
'channel': SLACK_CHANNEL, | |
'text': "%s\n```\n%s```" % (subject, post_message) | |
} | |
req = Request(HOOK_URL, json.dumps(slack_message)) | |
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