1
1

More than 1 year has passed since last update.

cloudwatchのアラームをslackに通知

Posted at

SNSでトピック作る

CloudWatchでアラートを設定

説明にアラート出た理由書いとく
通知先を作ったSNSのやつにする

slackのincomming webhookを発行

lambdaで関数作成

トリガーを作ったSNSのやつにする
環境変数に以下追加
hookurl #slackのincomming webhookのurl
slackchannel #通知したいslackのチャンネル名
コードに以下入れる
必要であればtextの部分を編集する

'text': "<!here> \nアラーム名: %s\nステータス: %s\nアラーム理由: %s\n説明: %s" % (alarm_name, new_state, reason, alarm_description)

import boto3
import json
import logging
import os

from urllib.request import Request, urlopen
from urllib.error import URLError, HTTPError

HOOK_URL = os.environ['hookurl']
SLACK_CHANNEL = os.environ['slackchannel']

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']
    alarm_description = message['AlarmDescription']

    slack_message = {
        'channel': SLACK_CHANNEL,
        'text': "<!here> \nアラーム名: %s\nステータス: %s\nアラーム理由: %s\n説明: %s" % (alarm_name, new_state, reason, alarm_description)
    }

    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)

awscliで作ったアラームを強制的にアラーム状態にする

--alarm-name "作ったアラーム名"
--state-value ALARM #ALAEM or OK
--state-reason "test" #本来は~minimum 2 datapoints for OK -> ALARM transitionが出力される
--profile "Profile名" #profile設定している場合は入れる

state-reasonをちゃんと見たい場合はcloudwatchのアラーム設定で適当に閾値下げる

aws cloudwatch set-alarm-state --alarm-name "作ったアラーム名" --state-value ALARM --state-reason "test" --profile "Profile名"

lambdaの環境変数で指定したチャンネルに通知されればOK
たぶんawschatbotのほうが楽

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1