🗓️

EventBridge SchedulerでAuroraの自動停止を設定する

2023/02/27に公開

概要

AWSにはEventBridge Schedulerというタスクスケジューラサービスがあります。
EventBridge Rulesによるスケジュールトリガーと比較して、ターゲットが大幅に増え、タイムウィンドウやタイムゾーンを設定できるなど機能が大幅に向上しています。

この記事ではよくあるタスクとしてAuroraの自動停止を設定します。
Schedulerは直接 StopDBCluster のAPIを実行できますが、実行履歴が簡単に確認できるようにSSM Automation経由で実行するようにします。また、設定はAWS CLIから行います

IAM Roleの作成

Schedulerが使用するIAM Roleを作成します。
まずIAM Policyを作成します。

aws iam create-policy \
--policy-name db-scheduler-policy \
--policy-document \
'{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "StartStopDbCluster",
            "Effect": "Allow",
            "Action": [
                "rds:StartDBCluster",
                "rds:StopDBCluster",
                "rds:DescribeDBClusters"
            ],
            "Resource": "*"
        },
        {
            "Sid": "SsmAutomation",
            "Effect": "Allow",
            "Action": "ssm:StartAutomationExecution",
            "Resource": "*"
        }
    ]
}'

次にIAM Roleを作成します。信頼ポリシーには scheduler.amazonaws.com を許可します。

aws iam create-role \
--role-name db-scheduler-role \
--assume-role-policy-document \
'{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Principal": {
                "Service": "scheduler.amazonaws.com"
            },
            "Action": "sts:AssumeRole"
        }
    ]
}'

作成したRoleにPolicyを紐づけます。

aws iam attach-role-policy \
  --role-name db-scheduler-role \
  --policy-arn arn:aws:iam::123456789012:policy/db-scheduler-policy

Schedulerの設定

設定する引数が多いため、ファイルを読み込む形にします。以下は aurora-cluster という名前のクラスターを毎日18時に停止する場合です。

stop-input.yaml
Name: 'stop-db-cluster'
FlexibleTimeWindow:
  Mode: OFF
ScheduleExpression: 'cron(0 18 * * ? *)'
ScheduleExpressionTimezone: 'Asia/Tokyo'
Target:
  Arn: 'arn:aws:scheduler:::aws-sdk:ssm:startAutomationExecution'
  RoleArn: 'arn:aws:iam::123456789012:role/db-scheduler-role'
  Input: |
    {
      "DocumentName": "AWS-StartStopAuroraCluster",
      "Parameters": {
        "ClusterName": ["aurora-cluster"],
        "Action": ["Stop"]
      }
    }

次に以下のコマンドを実行してスケジュールを作成します。

aws scheduler create-schedule --cli-input-yaml file://stop-input.yaml 

{
    "ScheduleArn": "arn:aws:scheduler:ap-northeast-1:123456789012:schedule/default/stop-db-cluster"
}

これでEventBridge SchedulerでAuroraを自動停止する設定ができました。

参考

https://docs.aws.amazon.com/ja_jp/scheduler/latest/UserGuide/what-is-scheduler.html
https://awscli.amazonaws.com/v2/documentation/api/latest/reference/scheduler/index.html

Discussion