Systems Managerで特定タグを持ったEC2のAMIを指定時間に取るCloudformationテンプレート


AWS Systems Manager(旧称SSM)のメンテナンスウィンドウとAutomationを使って、時間指定でAMIを取得する処理をCloudformation化したので書いておきます。

コード

---
AWSTemplateFormatVersion: "2010-09-09"
Description: Create AMI with SSM
Parameters:
  CronScheduleExpression:
    Type: String
    Description: refs https://docs.aws.amazon.com/systems-manager/ladtest/userguide/reference-cron-and-rate-expressions.html#reference-cron-and-rate-expressions-maintenance-window
    Default: cron(0 0 0 ? * * *)

Resources:

  AutomationRole:
    Type: AWS::IAM::Role
    Properties:
      RoleName: !Sub "BackupAutomation"
      Path: /
      AssumeRolePolicyDocument:
        Version: "2012-10-17"
        Statement:
          - Effect: Allow
            Principal:
              Service:
              - ssm.amazonaws.com
              - ec2.amazonaws.com
            Action: sts:AssumeRole
      ManagedPolicyArns:
        - arn:aws:iam::aws:policy/service-role/AmazonSSMAutomationRole
      Policies:
        - PolicyName: ECSClusterPowerUser
          PolicyDocument:
            Version: '2012-10-17'
            Statement:
            - Effect: Allow
              Action:
              - iam:PassRole
              Resource: !Sub "arn:aws:iam::${AWS::AccountId}:role/BackupAutomation"

  CreateAmiMaintenanceWindow:
    Type: AWS::SSM::MaintenanceWindow
    Properties:
      Name: !Sub CreateAmiMaintenanceWindow
      Description: Maintenance Window to Create AMI
      AllowUnassociatedTargets: false
      Cutoff: 0
      Duration: 1
      Schedule: !Ref CronScheduleExpression
      ScheduleTimezone: Asia/Tokyo

  CreateAmiMaintenanceWindowTarget:
      Type: AWS::SSM::MaintenanceWindowTarget
      Properties:
          Description: target for AMI Creation
          Name: CreateAmiTargets
          ResourceType: INSTANCE
          Targets:
              - Key: tag:Create-AMI
                Values:
                  - true
          WindowId: !Ref CreateAmiMaintenanceWindow

  MaintenanceWindowAutomationTask:
    Type: AWS::SSM::MaintenanceWindowTask
    Properties:
      Name: CreateAMITask
      WindowId: !Ref CreateAmiMaintenanceWindow
      Targets:
      - Key: WindowTargetIds
        Values:
        - !Ref CreateAmiMaintenanceWindowTarget
      TaskArn: AWS-CreateImage
      ServiceRoleArn: !GetAtt AutomationRole.Arn
      TaskType: AUTOMATION
      TaskInvocationParameters:
        MaintenanceWindowAutomationParameters:
          Parameters:  
            InstanceId:
              - '{{RESOURCE_ID}}'
            NoReboot:
              - false
      Priority: 1
      MaxConcurrency: 10
      MaxErrors: 5
    DependsOn: CreateAmiMaintenanceWindowTarget

使い方

スケジュールは CronScheduleExpression のCfnパラメータで指定します。こちらの公式ドキュメント等を確認してください。

ターゲットとなるインスタンスはこちらで指定しています。AMIを取得したいEC2のタグに Create-AMI=true を設定すると処理対象となります。

  CreateAmiMaintenanceWindowTarget:
      Type: AWS::SSM::MaintenanceWindowTarget
      Properties:
          Description: target for AMI Creation
          Name: CreateAmiTargets
          ResourceType: INSTANCE
          Targets:
              - Key: tag:Create-AMI
                Values:
                  - true

時間が来るとタグを設定したEC2に対してrebootを伴うAMI取得が行われます。

その他

「No invocations to execute」となる場合は、SSM Agentがインストールされていない、上手く動いていないなどが考えられるので、こちらを確認してください。