4
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

CloudWatchのアラートをSNS経由でLambdaを実行し、Slack通知

Last updated at Posted at 2021-10-24

はじめに

今回はメモ書き程度になります。
題名の通り、構築していきます。

Webhook URLをKMSで暗号化する場合は、下記の記事通りにできます。
【AWS】CloudWatchアラーム通知をLambdaでSlack投稿する

ただ、KMSはお金がかかりますし、それほどセキュリティー対策が必要なければ、Lambdaの環境変数に、Webhook URLを設定します。

その場合のコードのみ参考記事とは異なりますので、コードを記載しておきます。
また、参考記事の①KMSを作成、②IAMを作成は不要です。

コード

環境変数
ProjectName:HOGE
hookUrl :Webhook URL

import boto3
import json
import logging
import os

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

HOOK_URL = os.environ['WebhookURL']
PROJECT_NAME = os.environ['ProjectName']

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))

    reason = message['NewStateReason']
    alarm_description = message['AlarmDescription']

    slack_message = {
        'text': "<!channel>:exclamation: *%s* \nアラーム: *%s*\n\nアラーム詳細: %s\n確認中は:eyes:、完了後は:white_check_mark:をお願いします" % (PROJECT_NAME, alarm_description, reason )
    }

    req = Request(HOOK_URL, json.dumps(slack_message).encode('utf-8'))
    try:
        response = urlopen(req)
        response.read()
    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)

以下のようにSlack通知されます。

@channel! HOGE 
アラーム: dev環境、EC2のCPUが80%を超えました。
アラーム詳細: Threshold Crossed: 1 out of the last 1 datapoints [4.687429399225447 (28/10/21 01:57:00)] was less than the threshold (80.0) (minimum 1 datapoint for OK -> ALARM transition).
確認中は:両目:、完了後は:チェックマーク_緑:をお願いします
4
7
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
4
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?