

• Das AWS Systems Manager CloudWatch Dashboard wird nach dem 30. April 2026 nicht mehr verfügbar sein. Kunden können weiterhin die CloudWatch Amazon-Konsole verwenden, um ihre CloudWatch Amazon-Dashboards anzusehen, zu erstellen und zu verwalten, so wie sie es heute tun. Weitere Informationen finden Sie in der [Amazon CloudWatch Dashboard-Dokumentation](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch_Dashboards.html). 

Die vorliegende Übersetzung wurde maschinell erstellt. Im Falle eines Konflikts oder eines Widerspruchs zwischen dieser übersetzten Fassung und der englischen Fassung (einschließlich infolge von Verzögerungen bei der Übersetzung) ist die englische Fassung maßgeblich.

# Aktualisieren von AMIs für Auto-Scaling-Gruppen
<a name="automation-tutorial-update-patch-windows-ami-autoscaling"></a>

Im folgenden Beispiel wird eine Auto-Scaling-Gruppe mit einem neu gepatchten AMI aktualisiert. Dieser Ansatz gewährleistet, dass neue Images automatisch den verschiedenen Computing-Umgebungen zur Verfügung gestellt werden, die Auto–Scaling-Gruppen verwenden.

Der letzte Schritt der Automatisierung in diesem Beispiel verwendet eine Python-Funktion, um eine neue Startvorlage zu erstellen, die das neu gepatchte AMI verwendet. Anschließend wird die Auto-Scaling-Gruppe aktualisiert, um die neue Startvorlage zu verwenden. In diesem Auto–Scaling-Szenariotyp können Benutzer vorhandene Instances in der Auto–Scaling-Gruppe beenden, um den Start einer neuen Instance zu erzwingen, die das neue Image verwendet. Andernfalls konnten Benutzer warten und das Skalieren der Ereignisse nach oben oder unten zulassen, um auf natürliche Weise neuere Instances zu starten.

**Bevor Sie beginnen**  
Bevor Sie mit diesem Beispiel beginnen, führen Sie die folgenden Aufgaben aus.
+ Konfigurieren Sie IAM-Rollen für Automation, ein Tool in AWS Systems Manager. Systems Manager benötigt eine Instance-Profilrolle und einen Servicerollen-ARN zur Verarbeitung von Automatisierungen. Weitere Informationen finden Sie unter [Einrichten der Automatisierung](automation-setup.md).

## Erstellen Sie das **Patch AMIAnd UpdateASG-Runbook**
<a name="create-autoscaling-update-runbook"></a>

**Gehen Sie wie folgt vor, um das **Patch AMIAnd UpdateAsg-Runbook zu erstellen, das die Patches** durchführt, die AMI Sie für den SourceAMI-Parameter angeben.** Das Runbook aktualisiert auch eine Auto-Scaling-Gruppe, um das neueste, gepatchte AMI zu verwenden.

**Erstellen und Ausführen des Runbooks**

1. Öffnen Sie die Konsole unter. AWS Systems Manager [https://console.aws.amazon.com/systems-manager/](https://console.aws.amazon.com/systems-manager/)

1. Wählen Sie im Navigationsbereich die Option **Dokumente** aus.

1. Wählen Sie **Automation** im Dropdown-Menü **Erstellen eines Dokuments**.

1. Geben Sie im Feld **Name** **PatchAMIAndUpdateASG** ein.

1. Wählen Sie die Registerkarte **Editor** und wählen Sie **Edit** (Bearbeiten) aus.

1. Wählen Sie **OK** aus, wenn Sie dazu aufgefordert werden, und löschen Sie den Inhalt im Feld **Document editor** (Dokumenteditor).

1. Fügen Sie im Feld **Document editor** (Dokumenteditor) den folgenden Inhalt des YAML-Beispiel-Runbooks ein.

   ```
   ---
   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. Wählen Sie **Create automation (Automation erstellen)**.

1. Wählen Sie im Navigationsbereich **Automatisierung** und **Automatisierung ausführen** aus.

1. Wählen Sie auf der Seite **Choose document** (Dokument wählen), die Registerkarte **Owned by me** (In meinem Besitz).

1. Suchen Sie nach dem Runbook **Patch AMIAnd UpdateAsg** und wählen Sie die Schaltfläche auf der Karte **Patch AMIAnd** UpdateAsg aus.

1. Wählen Sie **Weiter** aus.

1. Wählen Sie **Simple execution (Einfache Ausführung)** aus.

1. Geben Sie Werte für die Eingabeparameter an. Stellen Sie sicher, dass die von Ihnen angegebenen `SubnetId` und `SecurityGroupIds` den Zugriff auf die öffentlichen Systems-Manager-Endpunkte oder Ihre Schnittstellenendpunkte für Systems Manager zulassen.

1. Wählen Sie **Ausführen**.

1. Wählen Sie nach Abschluss der Automatisierung in der Amazon-EC2-Konsole **Auto Scaling** und dann **Launch Templates** (Startvorlagen) aus. Stellen Sie sicher, dass die neue Startvorlage angezeigt wird und dass sie das neue AMI verwendet.

1. Klicken Sie auf **Auto Scaling** und wählen Sie dann **Auto-Scaling-Gruppen**. Stellen Sie sicher, dass die Auto-Scaling-Gruppe die neue Startkonfiguration verwendet.

1. Beenden Sie mindestens eine Instance in Ihrer Auto–Scaling-Gruppe. Ersatz-Instances werden unter Verwendung der neuen AMI gestartet.