LoginSignup
2
0

More than 1 year has passed since last update.

CloudWatchアラームを自動有効化・無効化する方法

Posted at

はじめに

こんにちは、山田です。
今回はCloudWatchアラームを特定の時間、無効化する方法について記載していきます。

全体構成図

image.png
①:EventBridgeで、CloudWatchアラームを無効化する時間、CloudWAtchアラームを有効化する時間を設定します。
②:LambdaでCloudWatchアラームを無効化・有効化します。

Lambda作成

CloudWacthアラームを有効化するコードは通りです。

StartAction
import boto3

def lambda_handler(event, context):
    cloudwatch = boto3.client('cloudwatch')
    nt = ""
    while True:
        response = cloudwatch.describe_alarms(MaxRecords=100,NextToken=nt)
        alarms = response['MetricAlarms']
        for alarm in alarms:
            cloudwatch.enable_alarm_actions(
                AlarmNames=[alarm['AlarmName']],
            )
        try:
            nt = response['NextToken']
        except:
            print('error')
            break

CloudWacthアラームを無効化するコードは通りです。

StopAction
import boto3

def lambda_handler(event, context):
    cloudwatch = boto3.client('cloudwatch')
    nt = ""
    while True:
        response = cloudwatch.describe_alarms(MaxRecords=100,NextToken=nt)
        alarms = response['MetricAlarms']
        for alarm in alarms:
            cloudwatch.disable_alarm_actions(
                AlarmNames=[alarm['AlarmName']],
            )
        try:
            nt = response['NextToken']
        except:
            print('error')
            break

EventBridge作成

EventBridgeにて、スケジューリングを組みます。
今回は毎日8:00にCloudWAtchアラーム有効化、22:00に無効化するように設定します。

CloudWatchアラーム有効化スケジューリング

cron式でCloudWAtchアラームを有効化する時間帯を指定します
image.png
ターゲットタイプにLambda関数を選択し、作成したStartActionを指定します。
image.png

CloudWatchアラーム無効化スケジューリング

cron式でCloudWAtchアラームを無効化する時間帯を指定します
image.png
ターゲットタイプにLambda関数を選択し、作成したStopActionを指定します。
image.png

動作確認

指定した時間帯にCloudWatchアラームが有効化・無効化になっていればOKです。
image.png
image.png

2
0
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
2
0