티스토리 뷰

slack 메시지 포맷 편집

 

slack 메시지

 

lambda function

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['hookUrl']

logger = logging.getLogger()
logger.setLevel(logging.INFO)


def lambda_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']

    color = '00e200'
    username = 'CloudWatch'
    
    if new_state == 'ALARM':
        color = '#ff0000'

    slack_message = {
        'channel': SLACK_CHANNEL,
        'username': username,
        'pretext': "%s: %s" % (new_state, alarm_name),
        'color': color,
        'text': "%s state is now %s: %s" % (alarm_name, new_state, reason)
    }
    
    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)

 

 

댓글
댓글쓰기 폼