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가 인스톨되어 있지 않은, 잘 동작하고 있지 않는등이 생각할 수 있으므로, 이쪽을 확인해 주세요.

좋은 웹페이지 즐겨찾기