5
1

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 5 years have passed since last update.

【無料】CloudWatchのアラームをSlackへ通知する(Python版)備忘録

Last updated at Posted at 2019-09-23

#■はじめに
CloudWatchのアラームをSlackへ通知する方法に関する備忘録。
Lambdaのランタイムはpython3.7。

#■基本的な設定について
【参考】CloudWatchアラーム通知をSlackにする
https://qiita.com/hf7777hi/items/e0f43f0fb7e2effa0af8

KMSは20,000リクエストの無料枠がありますが、KMSキーの管理費用は発生する。
KMSのキー削除は最低7日間の保留期間が設定されるため即時削除できない。
bill-kms.PNG

#■KMSを使用しない設定について
【参考】Lambdaのcloudwatch-alarm-to-slackで無料と思ってKMS暗号化キーを使ったら2円かかったので関数修正した
https://qiita.com/hf7777hi/items/6226a17ddfc17ad9268c

環境変数「kmsEncryptedHookUrl」の値をIncoming WebhookのURLに設定する。
環境変数設定.PNG

環境変数に設定するURLが平文になったので、コードを修正。
(57行目あたりで2か所)

lamda_function.py
# The base-64 encoded, encrypted key (CiphertextBlob) stored in the kmsEncryptedHookUrl environment variable
###(1)次の行を修正###
HOOK_URL = os.environ['kmsEncryptedHookUrl'] 
#ENCRYPTED_HOOK_URL = os.environ['kmsEncryptedHookUrl']  #元のコードを一応記載。
# The Slack channel to send a message to stored in the slackChannel environment variable
SLACK_CHANNEL = os.environ['slackChannel']

###(2)次の行をコメントアウト###
#HOOK_URL = "https://" + boto3.client('kms').decrypt(CiphertextBlob=b64decode(ENCRYPTED_HOOK_URL))['Plaintext'].decode('utf-8')

#■テスト用データのサンプル
【参考】[JAWS-UG CLI] Lambda:#17 Lambda cloudwatch-alarm-to-slack (Python版)
https://qiita.com/tcsh/items/aba31b172cae992aebb3

サンプルデータ.json
{
        "Records": [
          {
            "EventVersion": "1.0",
            "EventSubscriptionArn": "arn:aws:sns:EXAMPLE",
            "EventSource": "aws:sns",
            "Sns": {
              "SignatureVersion": "1",
              "Timestamp": "1970-01-01T00:00:00.000Z",
              "Signature": "EXAMPLE",
              "SigningCertUrl": "EXAMPLE",
              "MessageId": "95df01b4-ee98-5cb9-9903-4c221d41eb5e",
              "Message": "{\"AlarmName\": \"testSlack\", \"NewStateValue\": \"NG\", \"NewStateReason\": \"test for Slack\"}",
              "MessageAttributes": {
                "Test": {
                  "Type": "String",
                  "Value": "TestString"
                },
                "TestBinary": {
                  "Type": "Binary",
                  "Value": "TestBinary"
                }
              },
              "Type": "Notification",
              "UnsubscribeUrl": "EXAMPLE",
              "TopicArn": "arn:aws:sns:EXAMPLE",
              "Subject": "TestInvoke"
            }
          }
        ]
}
5
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
5
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?