備忘録用
(notice_unhealthy_to_slack)
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 Slack channel to send a message to stored in the slackChannel environment variable
SLACK_CHANNEL = os.environ['slackChannel']
HOOK_URL = os.environ['hook_URL']
logger = logging.getLogger()
logger.setLevel(logging.INFO)
def handler(event, context):
logger.info("Event: " + str(event))
message = json.loads(event['Records'][0]['Sns']['Message'])
logger.info("Message: " + str(message))
alarm_name = message['AlarmName']
#old_state = message['OldStateValue']
new_state = message['NewStateValue']
#reason = message['NewStateReason']
slack_message = {
'channel': SLACK_CHANNEL,
# 'text': "<@UL0TNE657> 【ENV: dev/stg】 %s // state is now %s" % (alarm_name, new_state)
'text': "<@UL0TNE657> 【ENV: dev/stg】 %s // state is now %s" % (alarm_name, new_state)
}
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)