티스토리 뷰

cloudwatch 메시지를 slack으로 받기

 

시스템 구성

 

1. SNS

1-1. 주제 생성

 

1-2 구독

 

1-3 메시지 게시(메시지 발송 테스트)

 

2. slack webhooks url 생성

slack webhooks(incoming webhooks) 생성 방법 - https://sangchul.kr/784

#cluodwatchalert
https://hooks.slack.com/services/T018562TM6A/T017ZZ55YUV/wE5gd1fbfjNgxUeLqPUDMTbLR

 

3. lambda

AWS 콘솔에서 Lambda > 함수 > 함수 생성 > 블루프린트 > cloudwatch-alarm-to-slack-python > 환경 변수 값 입력

환경 변수

- slackChannel : test
- kmsEncryptedHookUrl :  test

 

lambda 함수 생성 후 코드 및 환경 변수 편집

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

    slack_message = {
        'channel': SLACK_CHANNEL,
        '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)

 환경 변수 편집

 - 키:값 생성

   = hookUrl:webhook URL

   = slackChannel:#채널명

 

IAM 권한 추가

- CloudWatchReadOnlyAccess

- AWSLambdaBasicExecutionRole-xxxx

- kms derypt

kms-lambda-cloudwatch-notification

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "Stmt1443036478000",
            "Effect": "Allow",
            "Action": [
                "kms:Decrypt"
            ],
            "Resource": [
                "arn:aws:kms:ap-northeast-2:123456789:key/d3s3ceb5-cc9b-4a25-b123-11d86gr346ce4"
            ]
        }
    ]
}

 

5. cloudwatch 경고 설정

 

6. slack 메시지

 

7. 기타(메시지 포맷 편집)

lambda > lambda_function > slack_message 편집

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: state - %s" % (alarm_name, new_state),
        '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)

댓글
댓글쓰기 폼