AWS_EN

Create AMI using SSM Automation (one-time/scheduled)

スポンサーリンク
Create AMI using SSM Automation (one-time/scheduled) AWS_EN
スポンサーリンク
スポンサーリンク

Create AMI using SSM Automation (one-time/scheduled)

There are several ways to create an AMI.

For example, the following page shows how to create one from the Management Console.

Create an AMI from an Amazon EC2 Instance - AWS Toolkit for Visual Studio
How to use the Toolkit for Visual Studio to create an AMI from an EC2 instance.

It can also be created using the AWS CLI.

create-image — AWS CLI 1.32.45 Command Reference

In this case, we will use the SSM Automation Runbook AWS-CreateImage to create an AMI.

AWS-CreateImage - AWS Systems Manager Automation runbook reference
Create a new AMI from an EC2 instance.

Specifically, two of the following will be implemented

  • Create SSM Automation Runbook associations to create one-off images.
  • Set up a maintenance window to create mehtimes on a regular basis.

Environment

Diagram of creating AMI using SSM Automation (one-time/scheduled)

Create two EC2 instances in one private subnet.
The instances will be the latest Amazon Linux 2.

Run the SSM Automation runbook AWS-CreateImage on both instances to get the image.
One instance creates an SSM association and runs the runbook on a one-off basis.
The other instance creates a maintenance window and runs the runbook periodically (once every 15 minutes).

CloudFormation template files

The above configuration is built with CloudFormation.
The CloudFormation templates are placed at the following URL

https://github.com/awstut-an-r/awstut-fa/tree/main/118

Explanation of key points of template files

IAM Role for SSM Automation

Resources:
  CreateImageRole:
    Type: AWS::IAM::Role
    DeletionPolicy: Delete
    Properties:
      AssumeRolePolicyDocument:
        Version: 2012-10-17
        Statement:
          - Effect: Allow
            Action: sts:AssumeRole
            Principal:
              Service:
                - ssm.amazonaws.com
      Policies:
        - PolicyName: CreateImagePolicy
          PolicyDocument:
            Version: 2012-10-17
            Statement:
              - Effect: Allow
                Action:
                  - ec2:CreateImage
                  - ec2:DescribeInstances
                Resource:
                  - "*"
Code language: YAML (yaml)

To create an AMI using AWS-CreateImage, SSM must be authorized to create the AMI.
Create an IAM role with SSM as the principal.
The permissions to be granted to the IAM role were taken from the following page.

AWS-CreateImage - AWS Systems Manager Automation runbook reference
Create a new AMI from an EC2 instance.

SSM Associations

Resources:
  CreateImageAssociation:
    Type: AWS::SSM::Association
    Properties:
      AssociationName: !Sub "${Prefix}-createimage-association"
      AutomationTargetParameterName: InstanceId
      Name: AWS-CreateImage
      Parameters:
        AutomationAssumeRole:
          - !Ref CreateImageRoleArn
        InstanceId:
          - "{{RESOURCE_ID}}"
      Targets:
        - Key: !Sub "tag:${TagKey}"
          Values:
            - !Ref TagValue1
      WaitForSuccessTimeoutSeconds: !Ref WaitForSuccessTimeoutSeconds
Code language: YAML (yaml)

Specify the target of association with the Targets property.
In this case, instances with the following tags are targeted for association.

  • Tag Key: CreateImage
  • Tag Value: Group1

Specify the parameters for running AWS-CreateImage in the Parameters property.
Specify the aforementioned IAM role in AutomationAssumeRole.
Specify “{{RESOURCE_ID}}” for InstanceId.
This is called a pseudo-parameter, and by using this notation, you can refer to the ID of each instance.

AWS Systems Manager

In the AutomationTargetParameterName property, use a pseudo-parameter to specify the parameter from which automation will branch.
In this case, we specified a pseudo-parameter for “InstanceId,” so we specify this.

Maintenance Window

Resources:
  MaintenanceWindow:
    Type: AWS::SSM::MaintenanceWindow
    Properties: 
      AllowUnassociatedTargets: true
      Cutoff: 1
      Description: My-First-Maintenance-Window
      Duration: 2
      Name: !Sub "${Prefix}-MaintenanceWindow"
      Schedule: rate(15 minutes)
      ScheduleTimezone: Asia/Tokyo

  MaintenanceWindowTarget:
    Type: AWS::SSM::MaintenanceWindowTarget
    Properties: 
      Name: !Sub "${Prefix}-MaintenanceWindowTarget"
      ResourceType: INSTANCE
      Targets: 
        - Key: !Sub "tag:${TagKey}"
          Values:
            - !Ref TagValue2
      WindowId: !Ref MaintenanceWindow

  MaintenanceWindowTask:
    Type: AWS::SSM::MaintenanceWindowTask
    Properties: 
      MaxConcurrency: 1
      MaxErrors: 1
      Name: !Sub "${Prefix}-MaintenanceWindowTask"
      Priority: 10
      Targets: 
        - Key: WindowTargetIds
          Values:
            - !Ref MaintenanceWindowTarget
      TaskArn: AWS-CreateImage
      TaskInvocationParameters: 
        MaintenanceWindowAutomationParameters:
          Parameters:
            AutomationAssumeRole:
              - !Ref CreateImageRoleArn
            InstanceId:
              - "{{RESOURCE_ID}}"
      TaskType: AUTOMATION
      WindowId: !Ref MaintenanceWindow
Code language: YAML (yaml)

To set up a maintenance window, three resources (maintenance window, target, and task) are defined.
For more information, please refer to the following pages.

The key to the maintenance window body is the Schedule property.
Use the rate expression to specify that it should run once every 15 minutes.

The target points to the Targets property.
Specify the instances to be targeted by the maintenance window.
Instances can be specified based on tag information.
In this case, instances with the following tags are targeted for association.

  • Tag Key: CreateImage
  • Tag Value: Group2

The key point is the TaskInvocationParameters property of the task.
It is set in the same way as the aforementioned associations.
Specifically, specify the IAM role for image creation and the instance ID as a pseudo-resource.

Architecting

Use CloudFormation to build this environment and check its actual behavior.

Create CloudFormation stacks and check the resources in the stacks

Create CloudFormation stacks.
For information on how to create stacks and check each stack, please refer to the following pages.

After reviewing the resources in each stack, information on the main resources created in this case is as follows

  • Instance 1: i-0bdf9464a3d6c1f90
  • Instance 2: i-03ccfb5347cd623d5
  • SSM association with instance 1: 657587dd-a930-4ac8-8d38-49effcab7dc5
  • Maintenance window for instance 2: fa-118-MaintenanceWindow

Action Check

Now that you are ready, check each resource from the AWS Management Console.

SSM Associations

Check SSM associations.

Detail of SSM 1.
Detail of SSM 2.

You can see that an association has been created regarding the SSM Automation runbook AWS-CreateImage.

Looking at the target of this association, we can see that the target is the instance whose tag name CreateImage has the value “Group1”.
In other words, instance 1 is the target of this association.

Check the runbook execution log.

Detail of SSM 3.

It reads that the runbook was successfully executed and an AMI (ami-0f36d15af67832dfa) was created.

Detailed logs of each step in the execution can also be viewed.

Detail of SSM 4.

Indeed, we can see that the action (aws:createImage) has been executed on instance 1 and an AMI has been created.

Confirm the created AMI.

Detail of AMI 1.

Indeed, an AMI is created from instance 1.

By creating the SSM association in this way and running the SSM Automation runbook AWS-CreateImage on the EC2 instance, we were able to create an AMI in a single run.

Maintenance Window

Check the maintenance window.

Detail of SSM 5.
Detail of SSM 6.
Detail of SSM 7.

You can see that a maintenance window is created that executes a process once every 15 minutes.

Looking at the tasks in the maintenance window, we can read that the content is to execute the runbook AWS-CreateImage.

Looking at the target in the maintenance window, we can see that the target is the instance whose tag name CreateImage has the value “Group2”.
In other words, instance 2 is the target.

Check the execution log in the maintenance window.

Detail of SSM 8.

It reads that the runbook was executed twice.
Indeed, the execution interval is once every 15 minutes.

Check the history of the two runs.

Detail of SSM 9.
Detail of SSM 10.

Indeed, we can see that an AMI is created from instance 2 at each run.

Finally, check the AMI created.

Detail of AMI 2.

In addition to the AMI created from instance 1, you will also see two AMIs created from instance 2.

Thus, by creating a maintenance window and running the SSM Automation runbook AWS-CreateImage on the EC2 instance, an AMI could be created periodically.

Summary

By creating an SSM association or maintenance window, we have identified a way to create AMIs from EC2 instances on a one-time/periodic basis by running the SSM Automation runbook AWS-CreateImage.

タイトルとURLをコピーしました