오토 스케일링을 위해 AMIs 업데이트 - AWS Systems Manager

기계 번역으로 제공되는 번역입니다. 제공된 번역과 원본 영어의 내용이 상충하는 경우에는 영어 버전이 우선합니다.

오토 스케일링을 위해 AMIs 업데이트

다음 예시는 Auto Scaling 그룹을 새로 패치된 AMI로 업데이트합니다. 이 접근 방법을 통해 Auto Scaling 그룹을 사용하는 다양한 컴퓨팅 환경에서 새로운 이미지를 자동으로 사용할 수 있습니다.

이 예시에서는 자동화의 최종 단계에서 새로 패치된 AMI를 사용하는 새로운 시작 템플릿을 Python 함수를 사용하여 생성합니다. 그런 다음 새 시작 템플릿을 사용하여 새 Auto Scaling 그룹을 생성합니다. 이 유형의 Auto Scaling 시나리오에서 사용자는 Auto Scaling 그룹의 기존 인스턴스를 종료하여 새로운 이미지를 사용하는 새로운 인스턴스를 강제로 시작할 수 있습니다. 또는 사용자는 기다렸다가 축소 또는 확장 이벤트를 통해 더 새로운 인스턴스를 자연스럽게 시작할 수 있습니다.

시작하기 전에

이 예제를 시작하기 전에 다음 작업을 완료합니다.

  • AWS Systems Manager의 기능인 Automation을 위한 IAM 역할을 구성합니다. 자동화 처리를 위해 Systems Manager에 인스턴스 프로파일 역할과 서비스 역할 ARN이 필요합니다. 자세한 내용은 Automation 설정 섹션을 참조하세요.

PatchAMIAndUpdateASG 런북 생성

다음 절차를 사용하여 SourceAMI 파라미터에 대해 지정한 AMI를 패치하는 PatchAMIAndUpdateASG 런북을 생성합니다. 런북은 또한 패치된 최신 AMI를 사용하도록 Auto Scaling 그룹을 업데이트합니다.

실행서를 생성하고 실행하려면
  1. AWS Systems Manager 콘솔(https://console.aws.amazon.com/systems-manager/)을 엽니다.

  2. 탐색 창에서 Documents를 선택합니다.

    -또는-

    AWS Systems Manager 홈 페이지가 처음 열리면 메뉴 아이콘( 
    The menu icon
  )을 선택하여 탐색 창을 연 다음 탐색 창에서 [Documents]를 선택합니다.

  3. [문서 생성(Create document)] 드롭다운에서 [Automation]을 선택합니다.

  4. 이름 필드에 PatchAMIAndUpdateASG을 입력합니다.

  5. 편집기(Editor) 탭을 선택하고 편집(Edit)을 선택합니다.

  6. 대화 상자가 표시되면 확인(OK)을 선택하고 문서 편집기(Document editor) 필드에서 콘텐츠를 삭제합니다.

  7. 문서 편집기(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.8 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
  8. Create automation(자동화 생성)을 선택합니다.

  9. 탐색 창에서 Automation(자동화)을 선택한 후 Execute automation(자동화 실행)을 선택합니다.

  10. 문서 선택(Choose document) 페이지에서 내 소유(Owned by me) 탭을 선택합니다.

  11. PatchAMIAndUpdateASG 런북을 찾고 PatchAMIAndUpdateASG 카드에서 버튼을 선택합니다.

  12. 다음(Next)을 선택합니다.

  13. Simple execution(단순 실행)을 선택합니다.

  14. 입력 파라미터에 대한 값을 지정합니다. 지정한 SubnetIdSecurityGroupIds가 퍼블릭 Systems Manager 엔드포인트 또는 Systems Manager용 인터페이스 엔드포인트에 대한 액세스를 허용하도록 해야 합니다.

  15. Execute(실행)를 선택합니다.

  16. 자동화가 완료된 후 Amazon EC2 콘솔에서 Auto Scaling을 선택한 다음 시작 템플릿(Launch Templates)을 선택합니다. 새로운 시작 템플릿이 표시되고 새로운 AMI가 사용되는지 확인합니다.

  17. [Auto Scaling]을 선택한 다음 [Auto Scaling 그룹(Auto Scaling Groups)]을 선택합니다. Auto Scaling 그룹에서 새로운 시작 템플릿이 사용되는지 확인합니다.

  18. Auto Scaling 그룹에서 하나 이상의 인스턴스를 종료합니다. 대체 인스턴스가 새로운 AMI를 사용하여 시작됩니다.