

• AWS Systems Manager CloudWatch ダッシュボードは、2026 年 4 月 30 日以降は利用できなくなります。お客様は、これまでと同様に Amazon CloudWatch コンソールを使用して、Amazon CloudWatch ダッシュボードの表示、作成、管理を継続できます。詳細については、「[Amazon CloudWatch ダッシュボードのドキュメント](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch_Dashboards.html)」を参照してください。

# Auto Scaling グループ用の AMIs の更新
<a name="automation-tutorial-update-patch-windows-ami-autoscaling"></a>

次の例では、新しくパッチが適用された AMI で Auto Scaling グループを更新します。このアプローチにより、Auto Scaling グループを使用するさまざまなコンピューティング環境で、新しいイメージが自動的に利用可能になります。

この例のオートメーションの最後のステップでは、Python 関数を使用して、新しくパッチが適用された AMI を使用する新しい起動テンプレートを作成します。その後、Auto Scaling グループが更新され、新しい起動テンプレートが使用されます。このタイプの Auto Scaling シナリオでは、ユーザーが Auto Scaling グループ内の既存のインスタンスを終了して、新しいイメージを使用する新しいインスタンスを強制的に起動できます。ユーザーは、スケールインまたはスケールアウトイベントが新しいインスタンスを自然に起動させるのを待つこともできます。

**開始する前に**  
この例を開始する前に、次のタスクを完了してください。
+ AWS Systems Manager のツールである Automation の IAM ロールを設定します。Systems Manager には、オートメーションを処理するためのインスタンスプロファイルのロールおよびサービスロールの ARN が必要です。詳しくは、「[オートメーションの設定](automation-setup.md)」を参照してください。

## **PatchAMIAndUpdateASG** ランブックを作成する
<a name="create-autoscaling-update-runbook"></a>

次の手順を使用して、**SourceAMI** パラメータ向けに指定した AMI にパッチを適用する **PatchAMIAndUpdateASG** ランブックを作成します。ランブックは、Auto Scaling グループも更新して、パッチが適用された最新の AMI を使用するようにします。

**ランブックを作成して実行するには**

1. AWS Systems Manager コンソール ([https://console.aws.amazon.com/systems-manager/](https://console.aws.amazon.com/systems-manager/)) を開きます。

1. ナビゲーションペインで、**[ドキュメント]** を選択します。

1. [**Create document** (ドキュメントの作成)] ドロップダウンで [**Automation** (オートメーション)] を選択します。

1. [**名前**] フィールドに **PatchAMIAndUpdateASG** を入力してください。

1. **[Editor]** (エディタ) タブを選択し、次に **[Edit]** (編集) を選択します。

1. プロンプトが表示されたら **[OK]** を選択し、**[Document editor]** (ドキュメントエディタ) フィールドのコンテンツを削除します。

1. **[Document editor]** (ドキュメントエディタ) フィールドに、以下の YAML サンプルランブックコンテンツを貼り付けます。

   ```
   ---
   description: Systems Manager Automation Demo - Patch AMI and Update ASG
   schemaVersion: '0.3'
   assumeRole: '{{ AutomationAssumeRole }}'
   parameters:
     AutomationAssumeRole:
       type: String
       description: '(Required) The ARN of the role that allows Automation to perform the actions on your behalf. If no role is specified, Systems Manager Automation uses your IAM permissions to execute this document.'
       default: ''
     SourceAMI:
       type: String
       description: '(Required) The ID of the AMI you want to patch.'
     SubnetId:
       type: String
       description: '(Required) The ID of the subnet where the instance from the SourceAMI parameter is launched.'
     SecurityGroupIds:
       type: StringList
       description: '(Required) The IDs of the security groups to associate with the instance launched from the SourceAMI parameter.'
     NewAMI:
       type: String
       description: '(Optional) The name of of newly patched AMI.'
       default: 'patchedAMI-{{global:DATE_TIME}}'
     TargetASG:
       type: String
       description: '(Required) The name of the Auto Scaling group you want to update.'
     InstanceProfile:
       type: String
       description: '(Required) The name of the IAM instance profile you want the source instance to use.'
     SnapshotId:
       type: String
       description: (Optional) The snapshot ID to use to retrieve a patch baseline snapshot.
       default: ''
     RebootOption:
       type: String
       description: '(Optional) Reboot behavior after a patch Install operation. If you choose NoReboot and patches are installed, the instance is marked as non-compliant until a subsequent reboot and scan.'
       allowedValues:
         - NoReboot
         - RebootIfNeeded
       default: RebootIfNeeded
     Operation:
       type: String
       description: (Optional) The update or configuration to perform on the instance. The system checks if patches specified in the patch baseline are installed on the instance. The install operation installs patches missing from the baseline.
       allowedValues:
         - Install
         - Scan
       default: Install
   mainSteps:
     - name: startInstances
       action: 'aws:runInstances'
       timeoutSeconds: 1200
       maxAttempts: 1
       onFailure: Abort
       inputs:
         ImageId: '{{ SourceAMI }}'
         InstanceType: m5.large
         MinInstanceCount: 1
         MaxInstanceCount: 1
         IamInstanceProfileName: '{{ InstanceProfile }}'
         SubnetId: '{{ SubnetId }}'
         SecurityGroupIds: '{{ SecurityGroupIds }}'
     - name: verifyInstanceManaged
       action: 'aws:waitForAwsResourceProperty'
       timeoutSeconds: 600
       inputs:
         Service: ssm
         Api: DescribeInstanceInformation
         InstanceInformationFilterList:
           - key: InstanceIds
             valueSet:
               - '{{ startInstances.InstanceIds }}'
         PropertySelector: '$.InstanceInformationList[0].PingStatus'
         DesiredValues:
           - Online
       onFailure: 'step:terminateInstance'
     - name: installPatches
       action: 'aws:runCommand'
       timeoutSeconds: 7200
       onFailure: Abort
       inputs:
         DocumentName: AWS-RunPatchBaseline
         Parameters:
           SnapshotId: '{{SnapshotId}}'
           RebootOption: '{{RebootOption}}'
           Operation: '{{Operation}}'
         InstanceIds:
           - '{{ startInstances.InstanceIds }}'
     - name: stopInstance
       action: 'aws:changeInstanceState'
       maxAttempts: 1
       onFailure: Continue
       inputs:
         InstanceIds:
           - '{{ startInstances.InstanceIds }}'
         DesiredState: stopped
     - name: createImage
       action: 'aws:createImage'
       maxAttempts: 1
       onFailure: Continue
       inputs:
         InstanceId: '{{ startInstances.InstanceIds }}'
         ImageName: '{{ NewAMI }}'
         NoReboot: false
         ImageDescription: Patched AMI created by Automation
     - name: terminateInstance
       action: 'aws:changeInstanceState'
       maxAttempts: 1
       onFailure: Continue
       inputs:
         InstanceIds:
           - '{{ startInstances.InstanceIds }}'
         DesiredState: terminated
     - name: updateASG
       action: 'aws:executeScript'
       timeoutSeconds: 300
       maxAttempts: 1
       onFailure: Abort
       inputs:
         Runtime: python3.11
         Handler: update_asg
         InputPayload:
           TargetASG: '{{TargetASG}}'
           NewAMI: '{{createImage.ImageId}}'
         Script: |-
           from __future__ import print_function
           import datetime
           import json
           import time
           import boto3
   
           # create auto scaling and ec2 client
           asg = boto3.client('autoscaling')
           ec2 = boto3.client('ec2')
   
           def update_asg(event, context):
               print("Received event: " + json.dumps(event, indent=2))
   
               target_asg = event['TargetASG']
               new_ami = event['NewAMI']
   
               # get object for the ASG we're going to update, filter by name of target ASG
               asg_query = asg.describe_auto_scaling_groups(AutoScalingGroupNames=[target_asg])
               if 'AutoScalingGroups' not in asg_query or not asg_query['AutoScalingGroups']:
                   return 'No ASG found matching the value you specified.'
   
               # gets details of an instance from the ASG that we'll use to model the new launch template after
               source_instance_id = asg_query.get('AutoScalingGroups')[0]['Instances'][0]['InstanceId']
               instance_properties = ec2.describe_instances(
                   InstanceIds=[source_instance_id]
               )
               source_instance = instance_properties['Reservations'][0]['Instances'][0]
   
               # create list of security group IDs
               security_groups = []
               for group in source_instance['SecurityGroups']:
                   security_groups.append(group['GroupId'])
   
               # create a list of dictionary objects for block device mappings
               mappings = []
               for block in source_instance['BlockDeviceMappings']:
                   volume_query = ec2.describe_volumes(
                       VolumeIds=[block['Ebs']['VolumeId']]
                   )
                   volume_details = volume_query['Volumes']
                   device_name = block['DeviceName']
                   volume_size = volume_details[0]['Size']
                   volume_type = volume_details[0]['VolumeType']
                   device = {'DeviceName': device_name, 'Ebs': {'VolumeSize': volume_size, 'VolumeType': volume_type}}
                   mappings.append(device)
   
               # create new launch template using details returned from instance in the ASG and specify the newly patched AMI
               time_stamp = time.time()
               time_stamp_string = datetime.datetime.fromtimestamp(time_stamp).strftime('%m-%d-%Y_%H-%M-%S')
               new_template_name = f'{new_ami}_{time_stamp_string}'
               try:
                   ec2.create_launch_template(
                       LaunchTemplateName=new_template_name,
                       LaunchTemplateData={
                           'BlockDeviceMappings': mappings,
                           'ImageId': new_ami,
                           'InstanceType': source_instance['InstanceType'],
                           'IamInstanceProfile': {
                               'Arn': source_instance['IamInstanceProfile']['Arn']
                           },
                           'KeyName': source_instance['KeyName'],
                           'SecurityGroupIds': security_groups
                       }
                   )
               except Exception as e:
                   return f'Exception caught: {str(e)}'
               else:
                   # update ASG to use new launch template
                   asg.update_auto_scaling_group(
                       AutoScalingGroupName=target_asg,
                       LaunchTemplate={
                           'LaunchTemplateName': new_template_name
                       }
                   )
                   return f'Updated ASG {target_asg} with new launch template {new_template_name} which uses AMI {new_ami}.'
   outputs:
   - createImage.ImageId
   ```

1. [**Create automation (オートメーションを作成)**] を選択します。

1. ナビゲーションペインで、[**オートメーション**]、[**オートメーションの実行**] の順に選択します。

1. **[Choose document]** (ドキュメントを選択) ページで、**[Owned by me]** (自分が所有) タブを選択します。

1. **PatchAMIAndUpdateASG** ランブックを検索し、**PatchAMIAndUpdateASG** カードのボタンを選択します。

1. [**次へ**] を選択します。

1. [ **Simple execution (シンプルな実行)**] を選択します。

1. 入力パラメータの値を指定します。指定する `SubnetId` と `SecurityGroupIds` が、パブリック Systems Manager エンドポイント、または Systems Manager のインターフェイスエンドポイントへのアクセスを許可していることを確認してください。

1. **[実行]** を選択してください。

1. オートメーションが完了したら、Amazon EC2 コンソールで **[Auto Scaling]**、**[Launch Templates]** (テンプレートを起動) の順に選択します。新しい起動テンプレートが表示され、新しい AMI を使用していることを確認します。

1. [**Auto Scaling**]、[**Auto Scaling グループ**] の順に選択します。Auto Scaling グループで新しい起動テンプレートが使用されていることを確認します。

1. Auto Scaling グループ内の 1 つ以上のインスタンスを終了します。代替インスタンスは、新しい AMI を使用して起動されます。