SSM AutomationでRDS Clusterの自動停止起動設定（Cloudformation）

### はじめに
普段、私はCDKでCloudformationを作成します。
今回はCDKでEventBridgeのターゲットにSSＭ Automationを設定することがL2 Constructではできなかったため一部を手動で設定してCloudformationを作成しました。
そのためスケジューラの部分などパラメータ化されていない部分もありますので、ご了承ください。
構成としてはCloudwatchスケジューラにSSM AutomationとRDSクラスタの実行権限を付与し、AWSが提供しているRDSクラスタの自動起動停止用のドキュメントをスケジュールで実行しています。
### 前提
- RDSクラスタが作成されていること
- Cloudformationの実行権限があること

![2021-07-01_09h27_39.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/222041/a5f0ed42-454c-08f3-fc4c-e9d204c1dcbc.png)

### Cloudformation
全体はこちらです。

```
{
  "Parameters": {
    "RDSCluster1": {
      "Type": "String",
      "Description": "RDSCluster1",
      "Default": "test-cluster"
    }
  },
  "Resources": {
    "rdsautomationrole": {
      "Type": "AWS::IAM::Role",
      "Properties": {
        "AssumeRolePolicyDocument": {
          "Statement": [
            {
              "Action": "sts:AssumeRole",
              "Effect": "Allow",
              "Principal": {
                "Service": "events.amazonaws.com"
              }
            }
          ],
          "Version": "2012-10-17"
        },
        "ManagedPolicyArns": [
          {
            "Fn::Join": [
              "",
              [
                "arn:",
                {
                  "Ref": "AWS::Partition"
                },
                ":iam::aws:policy/service-role/AmazonSSMAutomationRole"
              ]
            ]
          }
        ],
        "RoleName": "rds_automation_role"
      }
    },
    "rdsautomationroleDefaultPolicy": {
      "Type": "AWS::IAM::Policy",
      "Properties": {
        "PolicyDocument": {
          "Statement": [
            {
              "Action": [
                "rds:DescribeDBInstances",
                "rds:DescribeDBClusters",
                "rds:StartDBCluster",
                "rds:StopDBCluster"
              ],
              "Effect": "Allow",
              "Resource": "*"
            }
          ],
          "Version": "2012-10-17"
        },
        "PolicyName": "rdsautomationroleDefaultPolicy",
        "Roles": [
          {
            "Ref": "rdsautomationrole"
          }
        ]
      }
    },
    "RDSStartSceduleRule": {
      "Type": "AWS::Events::Rule",
      "Properties": {
        "Name": "rds_start_schedule_rule",
        "ScheduleExpression": "cron(00 23 ? * SUN-THU *)",
        "State": "ENABLED",
        "Targets": [
          {
            "Arn": "arn:aws:ssm:ap-northeast-1::automation-definition/AWS-StartStopAuroraCluster:$DEFAULT",
            "Id": "TargetStartAuroraCluster1",
            "RoleArn": {
              "Fn::Sub":"${rdsautomationrole.Arn}"
            },
            "Input": {
              "Fn::Sub": "{\"Action\":[\"Start\"],\"ClusterName\":[\"${RDSCluster1}\"]}"
            }
          }
        ]
      }
    },
    "RDSStopSceduleRule": {
      "Type": "AWS::Events::Rule",
      "Properties": {
        "Name": "rds_stop_schedule_rule",
        "ScheduleExpression": "cron(00 15 * * ? *)",
        "State": "ENABLED",
        "Targets":  [
          {
            "Arn": "arn:aws:ssm:ap-northeast-1::automation-definition/AWS-StartStopAuroraCluster:$DEFAULT",
            "Id": "TargetStopAuroraCluster1",
            "RoleArn": {
              "Fn::Sub":"${rdsautomationrole.Arn}"
            },
            "Input": {
              "Fn::Sub": "{\"Action\":[\"Stop\"],\"ClusterName\":[\"${RDSCluster1}\"]}"
            }
          }
        ]
      }
    }
  }
}
```

#### RDSクラスタ名をパラメータ化しています。

```
{
  "Parameters": {
    "RDSCluster1": {
      "Type": "String",
      "Description": "RDSCluster1",
      "Default": "test-cluster"
    }
  },
```

#### EventBridgeが実行する権限を定義します。

```
"Resources": {
    "rdsautomationrole": {
      "Type": "AWS::IAM::Role",
      "Properties": {
        "AssumeRolePolicyDocument": {
          "Statement": [
            {
              "Action": "sts:AssumeRole",
              "Effect": "Allow",
              "Principal": {
                "Service": "events.amazonaws.com"
              }
            }
          ],
          "Version": "2012-10-17"
        },
        "ManagedPolicyArns": [
          {
            "Fn::Join": [
              "",
              [
                "arn:",
                {
                  "Ref": "AWS::Partition"
                },
                ":iam::aws:policy/service-role/AmazonSSMAutomationRole"
              ]
            ]
          }
        ],
        "RoleName": "rds_automation_role"
      }
    },
    "rdsautomationroleDefaultPolicy": {
      "Type": "AWS::IAM::Policy",
      "Properties": {
        "PolicyDocument": {
          "Statement": [
            {
              "Action": [
                "rds:DescribeDBInstances",
                "rds:DescribeDBClusters",
                "rds:StartDBCluster",
                "rds:StopDBCluster"
              ],
              "Effect": "Allow",
              "Resource": "*"
            }
          ],
          "Version": "2012-10-17"
        },
        "PolicyName": "rdsautomationroleDefaultPolicy",
        "Roles": [
          {
            "Ref": "rdsautomationrole"
          }
        ]
      }
    },
```

#### 起動設定と停止設定をそれぞれ定義します。

```
"RDSStartSceduleRule": {
      "Type": "AWS::Events::Rule",
      "Properties": {
        "Name": "rds_start_schedule_rule",
        "ScheduleExpression": "cron(00 23 ? * SUN-THU *)",
        "State": "ENABLED",
        "Targets": [
          {
            "Arn": "arn:aws:ssm:ap-northeast-1::automation-definition/AWS-StartStopAuroraCluster:$DEFAULT",
            "Id": "TargetStartAuroraCluster1",
            "RoleArn": {
              "Fn::Sub":"${rdsautomationrole.Arn}"
            },
            "Input": {
              "Fn::Sub": "{\"Action\":[\"Start\"],\"ClusterName\":[\"${RDSCluster1}\"]}"
            }
          }
        ]
      }
    },
    "RDSStopSceduleRule": {
      "Type": "AWS::Events::Rule",
      "Properties": {
        "Name": "rds_stop_schedule_rule",
        "ScheduleExpression": "cron(00 15 * * ? *)",
        "State": "ENABLED",
        "Targets":  [
          {
            "Arn": "arn:aws:ssm:ap-northeast-1::automation-definition/AWS-StartStopAuroraCluster:$DEFAULT",
            "Id": "TargetStopAuroraCluster1",
            "RoleArn": {
              "Fn::Sub":"${rdsautomationrole.Arn}"
            },
            "Input": {
              "Fn::Sub": "{\"Action\":[\"Stop\"],\"ClusterName\":[\"${RDSCluster1}\"]}"
            }
          }
        ]
      }
    }
  }
}
```

### 構築したサービス
- EventBridge(旧Cloudwatch Schedule)
実際に構築されるものはEventBridgeだけです。

![2021-07-01_09h27_22.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/222041/bdfcbfc4-c3d2-0f70-b280-7e80536c8a2f.png)

詳細は編集で確認できます。
![2021-07-01_23h47_12.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/222041/e37100b0-94e2-58d4-758e-500a1050a6b0.png)
![2021-07-01_23h47_27.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/222041/54728184-e03b-3c1d-28aa-e6f97edd2af7.png)

# yaml ver
```
Parameters:
  RDSCluster1:
    Type: String
    Description: RDSCluster1
    Default: test-cluster
Resources:
  rdsautomationrole:
    Type: 'AWS::IAM::Role'
    Properties:
      AssumeRolePolicyDocument:
        Statement:
          - Action: 'sts:AssumeRole'
            Effect: Allow
            Principal:
              Service: events.amazonaws.com
        Version: 2012-10-17
      ManagedPolicyArns:
        - !Join 
          - ''
          - - 'arn:'
            - !Ref 'AWS::Partition'
            - ':iam::aws:policy/service-role/AmazonSSMAutomationRole'
      RoleName: rds_automation_role
  rdsautomationroleDefaultPolicy:
    Type: 'AWS::IAM::Policy'
    Properties:
      PolicyDocument:
        Statement:
          - Action:
              - 'rds:DescribeDBInstances'
              - 'rds:DescribeDBClusters'
              - 'rds:StartDBCluster'
              - 'rds:StopDBCluster'
            Effect: Allow
            Resource: '*'
        Version: 2012-10-17
      PolicyName: rdsautomationroleDefaultPolicy
      Roles:
        - !Ref rdsautomationrole
  RDSStartSceduleRule:
    Type: 'AWS::Events::Rule'
    Properties:
      Name: rds_start_schedule_rule
      ScheduleExpression: cron(00 23 ? * SUN-THU *)
      State: ENABLED
      Targets:
        - Arn: >-
            arn:aws:ssm:ap-northeast-1::automation-definition/AWS-StartStopAuroraCluster:$DEFAULT
          Id: TargetStartAuroraCluster1
          RoleArn: !Sub '${rdsautomationrole.Arn}'
          Input: !Sub '{"Action":["Start"],"ClusterName":["${RDSCluster1}"]}'
  RDSStopSceduleRule:
    Type: 'AWS::Events::Rule'
    Properties:
      Name: rds_stop_schedule_rule
      ScheduleExpression: cron(00 15 * * ? *)
      State: ENABLED
      Targets:
        - Arn: >-
            arn:aws:ssm:ap-northeast-1::automation-definition/AWS-StartStopAuroraCluster:$DEFAULT
          Id: TargetStopAuroraCluster1
          RoleArn: !Sub '${rdsautomationrole.Arn}'
          Input: !Sub '{"Action":["Stop"],"ClusterName":["${RDSCluster1}"]}'

```