-
-
Save vvalorous/68709f5d91b8bf7e1891de6c939c5cd4 to your computer and use it in GitHub Desktop.
This is a simple python script to post to Slack from a SNS Topic (CloudWatch Trigger).
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 | |
# Written by: Robert J. | |
# Email: [email protected] | |
import boto3 | |
import json | |
import logging | |
import os, sys | |
from urllib2 import Request, urlopen, URLError, HTTPError | |
HOOK_URL = os.environ['HOOK_URL'] | |
SLACK_CHANNEL = os.environ['SLACK_CHANNEL'] | |
ENVIRONMENT = os.environ['EnvType'] | |
ICON_EMOJI = ':cloudwatch:' | |
USERNAME = 'CloudWatch Bot' | |
logger = logging.getLogger() | |
logger.setLevel(logging.INFO) | |
def main(event, context): | |
env_blacklist = ['beta'] | |
if ENVIRONMENT in env_blacklist: | |
logger.info("Ignoring CloudWatch event since it is part of the %s stack." % (ENVIRONMENT)) | |
else: | |
message = json.loads(event['Records'][0]['Sns']['Message']) | |
json_payload = generate_payload(message) | |
post_payload(json_payload) | |
logger.info("Exiting Lambda Function.") | |
def error(message, code=1): | |
logger.error(message) | |
sys.exit(code) | |
def generate_payload(message): | |
try: | |
alarm_name = message['AlarmName'] | |
old_state = message['OldStateValue'] | |
new_state = message['NewStateValue'] | |
reason = message['NewStateReason'] | |
metric_name = message['Trigger']['MetricName'] | |
resource = message['Trigger']['Dimensions'][0]['value'] | |
except KeyError as e: | |
error("Key Missing: " + str(e)) | |
if new_state == "ALARM": | |
color = "#A30200" | |
elif new_state == "OK": | |
color = "#2eb886" | |
else: | |
color = "#dddddd" | |
slack_message = { | |
"attachments": [ | |
{ | |
"fallback": reason, | |
"color": color, | |
"title": alarm_name, | |
"title_link": "https://us-west-2.console.aws.amazon.com/cloudwatch/home?region=us-west-2#alarm:alarmFilter=ANY", | |
"fields": [ | |
{ | |
"title": "State", | |
"value": "%s -> %s" % (old_state, new_state), | |
"short": False | |
}, | |
{ | |
"title": "Reason", | |
"value": reason, | |
"short": False | |
}, | |
{ | |
"title": "Metric Name", | |
"value": metric_name, | |
"short": False | |
}, | |
{ | |
"title": "Affected Resource", | |
"value": resource, | |
"short": False | |
}, | |
] | |
} | |
], | |
'channel': SLACK_CHANNEL, | |
'username': USERNAME, | |
'icon_emoji': ICON_EMOJI | |
} | |
return slack_message | |
def post_payload(json_payload): | |
req = Request(HOOK_URL, json.dumps(json_payload)) | |
try: | |
response = urlopen(req) | |
response.read() | |
logger.info("Message posted to %s", json_payload['channel']) | |
except HTTPError as e: | |
error("Request failed: %d %s", e.code, e.reason) | |
except URLError as e: | |
error("Server connection failed: %s", e.reason) | |
def lambda_handler(event, context): | |
logger.info(json.dumps(event, indent=4)) | |
try: | |
main(event, context) | |
except Exception as msg: | |
error(str(msg)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment