4
1

More than 1 year has passed since last update.

CloudWatchアラームごとにSNS通知メッセージをカスタマイズする。

Posted at

はじめに

こんにちは、山田です。
今回は、CloudWatchアラームごとにSNSの通知メッセージを変更する方法を記載していきます。

構成図

全体構成図は以下の通りです。
image.png
CloudWatchアラームは2つ作成します。
SNSトピックに関しては、LamndaのトリガーになるものとLambdaの送信先になるものの2つ作成します。

SNSトピックの作成

SNSトピックを2つ作成します。
1つはLambdaのトリガーになるもので、1つはLambdaの送信先になるものです。

image.png

CloudWatchアラームの作成

CloudWatchアラームを2つ作成します。
作成したアラームごとに、通知メッセージをカスタマイズしていきます。
image.png

SNSトピックは2つとも、to_lamnbdaを選択します
image.png

Lambda関数の作成

Lambda関数を、Python 3.9で作成します。

import json
import boto3

def lambda_handler(event, context):
    client = boto3.client('sns')

    TOPIC_ARN = 'arn:aws:sns:ap-northeast-1:804052945400:send_message'  //送信先SNSトピック指定

    msg = json.dumps(event['Records'][0]['Sns']['Subject'])  //SNSのイベント取得

    if "test1" in msg:  //SNSのイベントにtest1の文字が含まれている場合の処理
        subject = 'test1です'
        message = 'test1です'
    elif "test2" in msg:  //SNSのイベントにtest2の文字が含まれている場合の処理
        subject = 'test2です'
        message = 'test2です'

    response = client.publish(
        TopicArn = TOPIC_ARN,  //SNSトピック
        Message = message,  //本文
        Subject = subject  //件名
    )
    return response

先ほど作成したSNSトピックをLambdaのトリガー、送信先として設定します。

image.png

動作確認

CloudWatchアラームをそれぞれ、アラーム状態にして通知されるメッセージが異なることを確認します。

test1をアラーム状態にします。
image.png

通知メッセージを確認します。
image.png

test2をアラーム状態にします。
image.png

通知メッセージを確認します。
image.png

通知メッセージの内容が異なっていれば完了です!

4
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
4
1