LoginSignup
1
0

AWS Lambda で CloudWatch アラームの自動有効化/無効化を行う方法

Posted at

この記事では、AWS Lambdaを使用してCloudWatchアラームを自動的に有効化または無効化する方法を詳しく説明します。
AWS EventBridgeとCloudFormationも活用し、完全に自動化されたソリューションを構築する方法について解説します。

1. Lambda関数の概要

cloudwatch-alarm-autostopcloudwatch-alarm-autostart という2つのLambda関数を作成します。
これらの関数は、CloudWatchのアラームを特定のタグに基づいて有効または無効にします。

cloudwatch-alarm-autostop

このLambda関数は、タグ Alarm-AutoStop の値が yes のアラームを無効にします。

import boto3

def lambda_handler(event, context):
    cloudwatch = boto3.client('cloudwatch')
    nt = None

    while True:
        response = cloudwatch.describe_alarms(MaxRecords=100, NextToken=nt if nt else None)
        for alarm in response['MetricAlarms']:
            tags = cloudwatch.list_tags_for_resource(ResourceARN=alarm['AlarmArn'])
            if any(tag['Key'] == 'Alarm-AutoStop' and tag['Value'] == 'yes' for tag in tags['Tags']):
                cloudwatch.disable_alarm_actions(AlarmNames=[alarm['AlarmName']])
        nt = response.get('NextToken')
        if not nt:
            break
cloudwatch-alarm-autostart

このLambda関数は、タグ Alarm-AutoStart の値が yes のアラームを有効にします。

import boto3

def lambda_handler(event, context):
    cloudwatch = boto3.client('cloudwatch')
    nt = None

    while True:
        response = cloudwatch.describe_alarms(MaxRecords=100, NextToken=nt if nt else None)
        for alarm in response['MetricAlarms']:
            tags = cloudwatch.list_tags_for_resource(ResourceARN=alarm['AlarmArn'])
            if any(tag['Key'] == 'Alarm-AutoStart' and tag['Value'] == 'yes' for tag in tags['Tags']):
                cloudwatch.enable_alarm_actions(AlarmNames=[alarm['AlarmName']])
        nt = response.get('NextToken')
        if not nt:
            break

2. IAMポリシーの設定

以下のIAMポリシーをLambda関数にアタッチすることで、必要なCloudWatch APIを呼び出す権限を付与します。

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "cloudwatch:DescribeAlarms",
                "cloudwatch:ListTagsForResource",
                "cloudwatch:DisableAlarmActions",
                "cloudwatch:EnableAlarmActions"
            ],
            "Resource": "*"
        }
    ]
}

3. EventBridgeのCloudFormation設定

以下のCloudFormationテンプレートを使用して、特定の時間にLambda関数をトリガーするEventBridgeルールを作成します。
今回は、毎日AM4:00にしてcloudwatch-alarm-autostartに付けるトリガーの場合になります。

AWSTemplateFormatVersion: '2010-09-09'
Description: CloudFormation template for EventBridge rule 'cloudwatch-alarm-autostart-0400'
Resources:
  EventRule0:
    Type: AWS::Events::Rule
    Properties:
      Description: Activate alarm at 4:00 AM
      EventBusName: default
      Name: cloudwatch-alarm-autostart-0400
      ScheduleExpression: cron(0 19 * * ? *)
      State: ENABLED
      Targets:
        - Id: k70ks679enybum7o4zas
          Arn: arn:aws:lambda:ap-northeast-1:236693288971:function:cloudwatch-alarm-autostart

この設定により、毎日日本時間の4:00 AMにcloudwatch-alarm-autostart Lambda関数が実行され、指定されたアラームが自動的に有効化されます。

まとめ

このガイドでは、AWS LambdaとEventBridgeを使用してCloudWatchアラームを自動で有効化・無効化する方法を説明しました。
これにより、運用の自動化と効率化が図れます。

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