

• AWS Systems Manager CloudWatch 대시보드는 2026년 4월 30일 이후에는 더 이상 사용할 수 없습니다. 고객은 Amazon CloudWatch 콘솔을 계속 사용하여 현재와 마찬가지로 Amazon CloudWatch 대시보드를 보고, 생성하고, 관리할 수 있습니다. 자세한 내용은 [Amazon CloudWatch 대시보드 설명서](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch_Dashboards.html)를 참조하세요.

# AWS Systems Manager 자동화
<a name="systems-manager-automation"></a>

AWS Systems Manager의 도구인 Automation은 Amazon Elastic Compute Cloud(Amazon EC2), Amazon Relational Database Service(Amazon RDS), Amazon Redshift, Amazon Simple Storage Service(Amazon S3) 등의 AWS 서비스에 대한 일반적인 유지 관리, 배포 및 수정 태스크를 단순화합니다. 자동화를 시작하려면 [Systems Manager 콘솔](https://console.aws.amazon.com/systems-manager/automation)을 엽니다. 왼쪽 탐색 창에서 **자동화**를 선택합니다.

Automation은 AWS 리소스를 대규모로 배포, 구성 및 관리하는 자동화된 솔루션을 구축하는 데 도움이 됩니다. Automation을 사용하면 자동화의 동시성을 세부적으로 제어할 수 있습니다 즉, 동시에 대상으로 지정할 리소스 수와 자동화가 중지되기 전에 발생할 수 있는 오류 수를 지정할 수 있습니다.

Automation을 시작하는 데 도움이 되도록 AWS는 미리 정의된 몇 가지 실행서를 개발하고 유지 관리합니다. 사용 사례에 따라 다양한 태스크를 수행하는 이러한 미리 정의된 실행서를 사용하거나 요구 사항에 더 잘 맞는 사용자 정의 실행서를 직접 생성할 수 있습니다. 자동화의 진행률과 상태를 모니터링하기 위해 Systems Manager Automation 콘솔 또는 선호하는 명령줄 도구를 사용할 수 있습니다. 또한 Automation은 Amazon EventBridge와 통합되어 대규모 이벤트 기반 아키텍처를 구축하는 데 도움이 됩니다.

**참고**  
2025년 8월 14일부터 Systems Manager Automation을 처음 사용하는 고객의 경우 Automation 프리 티어를 사용할 수 없습니다. 이미 Automation을 사용하고 있는 고객의 경우 프리 티어 서비스는 2025년 12월 31일에 종료됩니다. 현재 서비스 비용에 대한 자세한 내용은 [AWS Systems Manager 요금](https://aws.amazon.com/systems-manager/pricing/)을 참조하세요.

## Automation이 조직에 주는 이점은 무엇인가요?
<a name="automation-benefits"></a>

Automation은 다음과 같은 이점을 제공합니다.
+ **실행서 콘텐츠의 스크립팅 지원**

  `aws:executeScript` 작업을 사용하면 실행서에서 직접 사용자 정의 Python 및 PowerShell 함수를 실행할 수 있습니다. 이렇게 하면 다른 Automation 작업이 지원하지 않는 다양한 태스크를 완료할 수 있으므로 더 유연하게 사용자 정의 실행서를 생성할 수 있습니다. 또한 실행서의 논리를 더 잘 제어할 수 있습니다. 이 작업을 사용하는 방법과 기존 자동화 솔루션을 개선하는 데 도움이 되는 방법의 예는 [Automation 실행서 작성](automation-authoring-runbooks.md) 섹션을 참조하세요.
+  **중앙 위치에서 여러 AWS 계정 및 AWS 리전에 걸쳐 자동화 실행** 

  관리자는 Systems Manager 콘솔에서 여러 계정 및 리전에 걸쳐 리소스에 대한 자동화를 실행할 수 있습니다.
+  **강화된 작업 보안** 

  관리자가 중앙 위치에서 실행서에 대한 액세스 권한을 부여하고 취소할 수 있습니다. AWS Identity and Access Management(IAM) 정책만 사용하는 경우에는 Automation을 사용할 수 있는 조직 내 개별 사용자 또는 그룹과 이들이 액세스할 수 있는 실행서를 제어할 수 있습니다.
+  **일반 IT 태스크 자동화** 

  일반 태스크를 자동화하면 운영 효율성을 개선하고 조직 표준을 시행하고 운영자 오류를 줄이는 데 도움이 될 수 있습니다. 예를 들어 `AWS-UpdateCloudFormationStackWithApproval` 실행서를 사용하여 AWS CloudFormation 템플릿으로 배포된 리소스를 업데이트할 수 있습니다. 이 업데이트는 새 템플릿에 적용됩니다. 업데이트가 시작되기 전에 사용자 한 명 이상의 승인을 요청하도록 자동화를 구성할 수 있습니다.
+  **중단 작업을 일괄적으로 안전하게 수행** 

  자동화에는 동시성 값과 오류 임계값을 지정하여 플릿에서 자동화 배포를 제어할 수 있는 속도 제어와 같은 기능이 포함됩니다. 속도 제어 작업에 대한 자세한 내용은 [대규모로 자동화된 작업 실행](running-automations-scale.md) 섹션을 참조하세요.
+ **복잡한 태스크 간소화**

  Automation은 골든 Amazon Machine Images(AMIs) 생성과 같이 복잡하고 시간 소모적인 태스크를 간소화하는 사전 정의된 실행서를 제공합니다. 예를 들어 `AWS-UpdateLinuxAmi` 및 `AWS-UpdateWindowsAmi` 실행서를 사용하여 소스 AMI에서 골든 AMIs를 생성할 수 있습니다. 이러한 실행서를 사용하여 업데이트가 적용되기 전과 후에 사용자 정의 스크립트를 실행할 수 있습니다. 또한 특정 소프트웨어 패키지를 포함하거나 설치에서 제외할 수 있습니다. 이러한 실행서를 사용하는 방법의 예제는 [자습서](automation-tutorials.md) 섹션을 참조하세요.
+ **입력에 대한 제약 조건 정의**

  사용자 정의 실행서에 제약 조건을 정의하여 Automation이 특정 입력 파라미터에 대해 허용하는 값을 제한할 수 있습니다. 예를 들어, `allowedPattern`은 정의하는 정규식과 일치하는 입력 파라미터의 값만 허용합니다. 입력 파라미터에 대해 `allowedValues`를 지정하면 실행서에 지정한 값만 허용됩니다.
+  **Amazon CloudWatch Logs에 자동화 작업 출력 로그** 

  조직의 운영 또는 보안 요구 사항을 충족하기 위해 실행서 중 실행된 스크립트의 레코드를 제공해야 할 수 있습니다. CloudWatch Logs를 사용하면 다양한 AWS 서비스의 로그 파일을 모니터링, 저장 및 액세스할 수 있습니다. 디버깅 및 문제 해결을 위해 `aws:executeScript` 작업의 출력을 CloudWatch Logs 로그 그룹으로 전송할 수 있습니다. 로그 데이터는 KMS 키를 사용하여 AWS KMS 암호화를 적용하거나 적용하지 않은 상태로 로그 그룹으로 스트리밍할 수 있습니다. 자세한 내용은 [CloudWatch Logs로 Automation 작업 출력 로깅](automation-action-logging.md) 섹션을 참조하세요.
+  **Amazon EventBridge 통합** 

  Automation은 Amazon EventBridge 규칙의 *대상* 유형으로 지원됩니다. 즉, 이벤트를 사용하여 실행서를 트리거할 수 있습니다. 자세한 내용은 [Amazon EventBridge로 Systems Manager 이벤트 모니터링](monitoring-eventbridge-events.md) 및 [참조: Systems Manager용 Amazon EventBridge 이벤트 패턴 및 유형](reference-eventbridge-events.md) 단원을 참조하세요.
+ **조직의 모범 사례 공유**

  계정 및 리전 간에 공유하는 실행서에서 리소스 관리, 운영 태스크 등에 대한 모범 사례를 정의할 수 있습니다.

## Automation은 누가 사용해야 하나요?
<a name="automation-who"></a>
+ 규모에 맞게 운영 효율성을 개선하고, 수동 개입과 관련된 오류를 줄이고, 일반적인 문제 해결 시간을 단축하고자 하는 AWS 고객
+ 배포 및 구성 태스크를 자동화하려는 인프라 전문가
+ 일반적인 문제를 안정적으로 해결하고, 문제 해결 효율성을 높이고, 반복 작업을 줄이려는 관리자
+ 일반적으로 수동으로 수행하는 태스크를 자동화하려는 사용자

## 자동화란 무엇인가요?
<a name="what-is-an-automation"></a>

*자동화*는 실행서에 정의되고 Automation 서비스에서 수행되는 모든 태스크로 구성됩니다. Automation은 다음 구성 요소를 사용하여 자동화를 실행합니다.


****  

| 개념 | 세부 정보 | 
| --- | --- | 
|  Automation 실행서  |  Systems Manager Automation 런북은 자동화(Systems Manager가 관리형 노드 및 AWS 리소스에 대해 수행하는 작업)를 정의합니다. Automation에는 사전 정의된 실행서가 몇 가지 포함되며, 이들 실행서를 사용하여 Amazon EC2 인스턴스를 하나 이상 다시 시작하거나 Amazon Machine Image(AMI)를 생성하는 등 일반적인 태스크를 수행할 수 있습니다. 사용자 고유의 실행서를 생성할 수도 있습니다. 실행서는 YAML 또는 JSON을 사용하며, 사용자가 지정하는 단계와 파라미터를 포함합니다. 단계는 순차적으로 실행됩니다. 자세한 내용은 [사용자 런북 생성](automation-documents.md) 섹션을 참조하세요. 실행서는 `Command`, `Policy`, `Session` 문서와 다른 `Automation` 유형의 Systems Manager 문서입니다. 실행서는 스키마 버전 0.3을 지원합니다. 명령 문서에는 스키마 버전 1.2, 2.0 또는 2.2가 사용됩니다. 정책 문서에는 스키마 버전 2.0 이상이 사용됩니다.  | 
|  자동화 작업  |  실행서에 정의된 자동화에는 하나 이상의 단계가 포함됩니다. 각 단계는 특정 작업과 관련되어 있습니다. 작업은 해당 단계의 입력, 동작 및 출력을 결정합니다. 단계는 실행서의 `mainSteps` 섹션에 정의됩니다. 자동화는 20개의 고유한 작업 유형을 지원합니다. 자세한 내용은 [Systems Manager Automation 작업 참조](automation-actions.md)을 참조하세요.  | 
|  Automation 할당량  |  각 AWS 계정는 100개의 자동화를 동시에 실행할 수 있습니다. 여기에는 하위 자동화(다른 자동화에 의해 시작된 자동화) 및 속도 제어 자동화가 포함됩니다. 이보다 많은 자동화를 실행하려고 하면 Systems Manager가 대기열에 추가 자동화를 추가하고 보류 중(Pending) 상태를 표시합니다. 적응형 동시성을 사용하여 이 할당량을 조정할 수 있습니다. 자세한 내용은 [Automation이 동시성 요구 사항에 따라 조정되도록 허용](adaptive-concurrency.md) 섹션을 참조하세요. 자동화 실행에 대한 자세한 내용은 [Systems Manager Automation을 기반으로 자동화된 작업 실행](running-simple-automations.md) 섹션을 참조하세요.  | 
|  Automation 대기열 할당량  |  동시 자동화 제한보다 많은 자동화를 실행하려고 하면 후속 자동화가 대기열에 추가됩니다. AWS 계정마다 5,000개의 자동화를 대기열에 넣을 수 있습니다. 자동화가 완료되거나 종료 상태에 도달하면 대기열의 첫 번째 자동화가 시작됩니다.  | 
|  속도 제어 자동화 할당량  |  각 AWS 계정는 25개의 속도 제어 자동화를 동시에 실행할 수 있습니다. 동시 속도 제어 자동화 제한보다 더 많은 속도 제어 자동화를 실행하려고 하면 Systems Manager가 후속 속도 제어 자동화를 대기열에 추가하고 보류 중(Pending) 상태를 표시합니다. 속도 제어 자동화 실행에 대한 자세한 내용은 [대규모로 자동화된 작업 실행](running-automations-scale.md) 섹션을 참조하세요.  | 
|  속도 제어 자동화 대기열 할당량  |  동시 속도 제어 자동화 제한보다 많은 자동화를 실행하려고 하면 후속 자동화가 대기열에 추가됩니다. AWS 계정마다 1,000개의 속도 제어 자동화를 대기열에 넣을 수 있습니다. 자동화가 완료되거나 종료 상태에 도달하면 대기열의 첫 번째 자동화가 시작됩니다.  | 

**Topics**
+ [

## Automation이 조직에 주는 이점은 무엇인가요?
](#automation-benefits)
+ [

## Automation은 누가 사용해야 하나요?
](#automation-who)
+ [

## 자동화란 무엇인가요?
](#what-is-an-automation)
+ [

# Automation 설정
](automation-setup.md)
+ [

# Systems Manager Automation을 기반으로 자동화된 작업 실행
](running-simple-automations.md)
+ [

# 자동화 실행 재실행
](automation-rerun-executions.md)
+ [

# 승인이 필요한 자동화 실행
](running-automations-require-approvals.md)
+ [

# 대규모로 자동화된 작업 실행
](running-automations-scale.md)
+ [

# 여러 AWS 리전 및 계정에서 자동화 실행
](running-automations-multiple-accounts-regions.md)
+ [

# EventBridge 이벤트를 기반으로 자동화 실행
](running-automations-event-bridge.md)
+ [

# 단계별 자동화 실행
](automation-working-executing-manually.md)
+ [

# State Manager 연결을 사용하여 자동화 예약
](scheduling-automations-state-manager-associations.md)
+ [

# 유지 관리 기간으로 자동화 예약
](scheduling-automations-maintenance-windows.md)
+ [

# Systems Manager Automation 작업 참조
](automation-actions.md)
+ [

# 사용자 런북 생성
](automation-documents.md)
+ [

# Systems Manager Automation 런북 참조
](automation-documents-reference.md)
+ [

# 자습서
](automation-tutorials.md)
+ [

# Systems Manager Automation에서 반환된 상태에 대해 알아보기
](automation-statuses.md)
+ [

# Systems Manager Automation 문제 해결
](automation-troubleshooting.md)

# Automation 설정
<a name="automation-setup"></a>

AWS Systems Manager의 도구인 Automation을 설정하려면 Automation 서비스에 대한 사용자 액세스 권한을 확인하고 역할을 구성하여 서비스에서 해당 리소스를 대신하여 작업을 수행할 수 있도록 해야 합니다. 또한 Automation 기본 설정에서 적응형 동시성 모드를 선택하는 것이 좋습니다. 적응형 동시성은 사용자의 필요에 맞게 자동화 할당량을 자동으로 조정합니다. 자세한 내용은 [Automation이 동시성 요구 사항에 따라 조정되도록 허용](adaptive-concurrency.md) 섹션을 참조하세요.

AWS Systems Manager 자동화에 대한 액세스 권한이 적절한지 확인하려면 다음 사용자 및 서비스 역할 요구 사항을 검토하십시오.

## 실행서에 대한 사용자 액세스 확인
<a name="automation-setup-user-access"></a>

실행서를 사용할 권한이 있는지 확인합니다. 사용자, 그룹 또는 역할에 관리자 권한이 할당되어 있는 경우 Systems Manager Automation에 액세스할 수 있습니다. 관리자 권한이 없는 경우 관리자가 `AmazonSSMFullAccess` 관리형 정책 또는 비교 가능한 권한을 제공하는 정책을 해당 사용자, 그룹 또는 역할에 할당하여 사용자에게 권한을 부여해야 합니다.

**중요**  
IAM 정책 `AmazonSSMFullAccess`는 Systems Manager 작업에 대해 권한을 부여합니다. 하지만 실행서 중에는 `ec2:ReleaseAddress`에 대한 IAM 권한이 필요한 실행서 `AWS-ReleaseElasticIP`와 같이, 다른 서비스에 대한 권한이 필요한 경우가 있습니다. 따라서 런북에서 수행할 작업을 검토하여 사용자, 그룹 또는 역할에 런북에 포함된 작업을 수행할 수 있는 필수 권한이 할당되어 있는지 확인해야 합니다.

## 자동화에 대한 서비스 역할(수임 역할) 액세스 구성
<a name="automation-setup-configure-role"></a>

자동화는 서비스 역할(또는 *수임 역할*) 컨텍스트에 따라 시작할 수 있습니다. 그러면 서비스가 사용자 대신 작업을 수행할 수 있습니다. 수임 역할이 지정되어 있지 않으면 Automation은 자동화를 호출한 사용자 컨텍스트를 사용합니다.

하지만 다음과 같은 경우에는 자동화에 대한 서비스 역할을 지정해야 합니다.
+ 리소스에 대한 사용자의 권한을 제한하려고 하지만 사용자가 더 높은 권한이 필요한 자동화를 실행하도록 하려는 경우입니다. 이 시나리오에서는 더 높은 권한이 있는 서비스 역할을 생성하고 사용자에게 자동화를 실행하도록 허용할 수 있습니다.
+ 실행서를 실행하는 Systems Manager State Manager 연결을 만들 때.
+ 작업을 12시간 이상 실행해야 하는 작업이 있는 경우
+ `aws:executeScript` 작업을 사용하여 AWS API 작업을 호출하거나 AWS 리소스에 대한 작업을 수행하는 Amazon이 소유하지 않은 실행서를 실행하고 있는 경우. 자세한 내용은 [실행서 사용 권한](automation-document-script-considerations.md#script-permissions) 섹션을 참조하세요.

자동화를 위한 서비스 역할을 생성해야 하는 경우 다음 방법 중 하나를 사용할 수 있습니다.

**Topics**
+ [

## 실행서에 대한 사용자 액세스 확인
](#automation-setup-user-access)
+ [

## 자동화에 대한 서비스 역할(수임 역할) 액세스 구성
](#automation-setup-configure-role)
+ [

# CloudFormation을 사용하여 Automation을 위한 서비스 역할 생성
](automation-setup-cloudformation.md)
+ [

# 콘솔을 사용하여 Automation을 위한 서비스 역할 생성
](automation-setup-iam.md)
+ [

# 자격 증명 기반 정책 설정 예제
](automation-setup-identity-based-policies.md)
+ [

# Automation이 동시성 요구 사항에 따라 조정되도록 허용
](adaptive-concurrency.md)
+ [

# 스로틀링된 작업에 대한 자동 재시도 구성
](automation-throttling-retry.md)
+ [

# Automation을 위한 변경 제어 구현
](automation-change-calendar-integration.md)

# CloudFormation을 사용하여 Automation을 위한 서비스 역할 생성
<a name="automation-setup-cloudformation"></a>

AWS CloudFormation 템플릿에서 AWS Systems Manager의 도구인 Automation에 대한 서비스 역할을 생성할 수 있습니다. 서비스 역할을 생성한 후에는 파라미터 `AutomationAssumeRole`을 사용하여 실행서에 서비스 역할을 지정할 수 있습니다.

## CloudFormation을 사용하여 서비스 역할 생성
<a name="create-iam-service-role"></a>

다음 절차를 따라 CloudFormation을 사용하여 Systems Manager Automation에 필요한 AWS Identity and Access Management(IAM) 역할을 생성합니다.

**필요한 IAM 역할을 생성하려면**

1. [https://docs.aws.amazon.com/systems-manager/latest/userguide/samples/AWS-SystemsManager-AutomationServiceRole.zip](https://docs.aws.amazon.com/systems-manager/latest/userguide/samples/AWS-SystemsManager-AutomationServiceRole.zip) 파일을 다운로드하고 압축을 해제합니다. 이 파일에는 `AWS-SystemsManager-AutomationServiceRole.yaml` CloudFormation 템플릿 파일이 들어 있습니다.

1. CloudFormation 콘솔([https://console.aws.amazon.com/cloudformation](https://console.aws.amazon.com/cloudformation/))을 엽니다.

1. **스택 생성**을 선택합니다.

1. **템플릿 지정(Specify template)** 섹션에서 **템플릿 파일 업로드**를 선택합니다.

1. **찾아보기**를 선택한 다음 `AWS-SystemsManager-AutomationServiceRole.yaml` CloudFormation 템플릿 파일을 선택합니다.

1. **다음**을 선택합니다.

1. **스택 세부 정보 지정(Specify stack details)** 페이지의 **스택 이름** 필드에 이름을 입력합니다.

1. **스택 옵션 구성(Configure stack options)** 페이지에서는 아무 것도 선택할 필요가 없습니다. **다음**을 선택합니다.

1. **검토** 페이지에서 아래로 스크롤하여 **CloudFormation이 IAM 리소스를 생성할 수 있다는 것을 알고 있음** 옵션을 선택합니다.

1. **생성(Create)**을 선택합니다.

CloudFormation에 약 3분간 **CREATE\$1IN\$1PROGRESS** 상태가 표시됩니다. 스택이 생성되어 역할을 사용할 준비가 되면 상태가 **CREATE\$1COMPLETE**로 바뀝니다.

**중요**  
AWS Identity and Access Management(IAM) 서비스 역할을 사용하여 다른 서비스를 호출하는 자동화 워크플로를 실행하는 경우 해당 서비스 역할이 다른 서비스를 호출할 권한이 있도록 구성되어야 합니다. 이 요구 사항은 `AWS-ConfigureS3BucketLogging`, `AWS-CreateDynamoDBBackup`, `AWS-RestartEC2Instance` 실행서 등의 모든 AWS Automation 실행서(`AWS-*` 실행서)에 적용됩니다. 또한 다른 서비스를 호출하는 작업을 사용하여 다른 AWS 서비스을(를) 호출하는 사용자 정의 Automation 실행서를 생성하는 경우에도 이 요구 사항이 항상 적용됩니다. 예를 들어 `aws:executeAwsApi`, `aws:createStack` 또는 `aws:copyImage` 작업을 사용하는 경우 이러한 서비스를 호출할 수 있는 권한을 포함하여 서비스 역할을 구성합니다. 역할에 IAM 인라인 정책을 추가하여 다른 AWS 서비스에 대한 권한을 부여할 수 있습니다. 자세한 내용은 [(선택 사항) 다른 AWS 서비스를 간접적으로 호출할 Automation 인라인 정책과 고객 관리형 정책 추가](automation-setup-iam.md#add-inline-policy) 섹션을 참조하세요.

## Automation을 위한 역할 정보 복사
<a name="copy-iam-role-info"></a>

다음 절차를 따라 CloudFormation 콘솔에서 자동화 서비스 역할에 대한 정보를 복사합니다. 실행서를 사용할 때 이러한 역할을 지정해야 합니다.

**참고**  
`AWS-UpdateLinuxAmi` 또는 `AWS-UpdateWindowsAmi` 실행서를 실행하는 경우 이 절차를 사용하여 역할 정보를 복사할 필요가 없습니다. 이러한 실행서에는 이미 기본값으로 지정된 필수 역할이 있습니다. 이 실행서에 지정된 역할은 IAM 관리형 정책을 사용합니다.

**역할 이름을 복사하려면**

1. CloudFormation 콘솔([https://console.aws.amazon.com/cloudformation](https://console.aws.amazon.com/cloudformation/))을 엽니다.

1. 이전 절차에서 생성한 자동화 **스택 이름**을 선택합니다.

1. **리소스** 탭을 선택합니다.

1. **AutomationServiceRole**에 대한 **물리적 ID(Physical ID)**를 선택합니다. IAM 콘솔이 열리고 Automation 서비스 역할의 요약 정보가 표시됩니다.

1. **역할 ARN** 옆에 있는 Amazon 리소스 이름(ARN)을 복사합니다. ARN은 `arn:aws:iam::12345678:role/AutomationServiceRole`과 비슷합니다.

1. 나중에 사용할 수 있도록 ARN을 텍스트 파일에 붙여 넣습니다.

이렇게 해서 자동화에 필요한 서비스 역할 구성을 마쳤습니다. 이제 실행서에 Automation 서비스 역할의 ARN을 사용할 수 있습니다.

# 콘솔을 사용하여 Automation을 위한 서비스 역할 생성
<a name="automation-setup-iam"></a>

AWS Systems Manager의 도구인 Automation용 서비스 역할을 생성해야 하는 경우 다음 태스크를 완료합니다. Automation을 위해 서비스 역할이 필요한 상황에 대한 자세한 내용은 [Automation 설정](automation-setup.md) 섹션을 참조하세요.

**Topics**
+ [

## 작업 1: Automation을 위한 서비스 역할 생성
](#create-service-role)
+ [

## 작업 2: Automation 역할에 iam:PassRole 정책 연결하기
](#attach-passrole-policy)

## 작업 1: Automation을 위한 서비스 역할 생성
<a name="create-service-role"></a>

다음 절차를 사용하여 Systems Manager Automation에 대한 서비스 역할 또는 *수임 역할*을 생성합니다.

**참고**  
`AWS-CreateManagedLinuxInstance` 실행서와 같은 실행서에서도 이 역할을 사용할 수도 있습니다. 실행서에서 이 역할 또는 AWS Identity and Access Management(IAM) 역할의 Amazon 리소스 이름(ARN)을 사용하면 Automation을 통해 환경에서 새 인스턴스 시작 및 사용자 대신 작업 수행과 같은 작업을 수행할 수 있습니다.

**IAM 역할을 생성하고 Automation에서 이를 수임하도록 허용하려면**

1. [https://console.aws.amazon.com/iam/](https://console.aws.amazon.com/iam/)에서 IAM 콘솔을 엽니다.

1. 탐색 창에서 **역할**을 선택한 후 **역할 생성**을 선택합니다.

1. **신뢰할 수 있는 유형의 엔터티 선택(Select type of trusted entity)** 아래에서 **AWS 서비스**를 선택합니다.

1. **사용 사례 선택** 섹션에서 **Systems Manager**를 선택한 후 **다음: 권한**을 선택합니다.

1. **Attach permissions policy(권한 정책 연결)** 페이지에서 **AmazonSSMAutomationRole** 정책을 검색하여 선택한 후 **다음: 검토**를 선택합니다.

1. **검토** 페이지에서 **역할 이름** 상자에 이름을 입력한 후 설명을 입력합니다.

1. **역할 생성**을 선택합니다. 그러면 **역할** 페이지로 돌아갑니다.

1. **역할** 페이지에서 방금 만든 역할을 선택하여 **요약** 페이지를 엽니다. **역할 이름** 및 **역할 ARN**을 메모합니다. 다음 절차에서 IAM 계정에 **iam:PassRole** 정책을 연결할 때 역할 ARN을 지정합니다. 실행서에서 역할 이름과 ARN을 지정할 수도 있습니다.

**참고**  
`AmazonSSMAutomationRole` 정책은 계정 내 AWS Lambda 함수의 하위 집합에 Automation 역할 권한을 할당합니다. 이 함수는 "Automation"으로 시작합니다. Lambda 함수와 함께 Automation을 사용할 예정인 경우 Lambda ARN에서 다음 형식을 사용해야 합니다.  
`"arn:aws:lambda:*:*:function:Automation*"`  
ARN이 이 형식을 사용하지 않는 기존 Lambda 함수가 있는 경우 **AWSLambdaRole** 정책과 같은 추가 Lambda 정책도 자동화 역할에 연결해야 합니다. 추가 정책 또는 역할은 AWS 계정 내에서 Lambda 함수에 대한 보다 폭넓은 액세스를 제공해야 합니다.

서비스 역할을 생성한 후 교차 서비스 혼동된 대리자 문제를 방지하기 위해 신뢰 정책을 편집하는 것이 좋습니다. *혼동된 대리자 문제*는 작업을 수행할 권한이 없는 엔터티가 권한이 더 많은 엔터티에 작업을 수행하도록 강요할 수 있는 보안 문제입니다. AWS에서는 교차 서비스 가장으로 인해 혼동된 대리자 문제가 발생할 수 있습니다. 교차 서비스 가장은 한 서비스(*직접 호출하는 서비스*)가 다른 서비스(*직접 호출되는 서비스*)를 직접 호출할 때 발생할 수 있습니다. 직접 호출하는 서비스는 다른 고객의 리소스에 대해 액세스 권한이 없는 방식으로 작동하게 권한을 사용하도록 조작될 수 있습니다. 이를 방지하기 위해 AWS에서는 계정의 리소스에 대한 액세스 권한이 부여된 서비스 위탁자를 사용하여 모든 서비스에 대한 데이터를 보호하는 데 도움이 되는 도구를 제공합니다.

Automation이 리소스에 다른 서비스를 제공하는 권한을 제한하려면 리소스 정책에서 [https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_condition-keys.html#condition-keys-sourcearn](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_condition-keys.html#condition-keys-sourcearn) 및 [https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_condition-keys.html#condition-keys-sourceaccount](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_condition-keys.html#condition-keys-sourceaccount) 전역 조건 컨텍스트 키를 사용하는 것이 좋습니다. 만약 `aws:SourceArn` 값에 Amazon S3 버킷 ARN과 같은 계정 ID가 포함되어 있지 않은 경우 권한을 제한하려면 두 전역 조건 컨텍스트 키를 모두 사용해야 합니다. 두 전역 조건 컨텍스트 키와 계정을 포함한 `aws:SourceArn` 값을 모두 사용하는 경우, `aws:SourceAccount` 값 및 `aws:SourceArn` 값의 계정은 동일한 정책 명령문에서 사용할 경우 반드시 동일한 계정 ID를 사용해야 합니다. 하나의 리소스만 교차 서비스 액세스와 연결되도록 허용하려는 경우 `aws:SourceArn`을 사용하세요. 해당 계정의 모든 리소스가 교차 서비스 사용과 연결되도록 허용하려는 경우 `aws:SourceAccount`를 사용하세요. `aws:SourceArn`의 값은 자동화 실행을 위한 ARN이어야 합니다. 리소스의 전체 ARN을 모를 경우 또는 여러 리소스를 지정하는 경우, ARN의 알 수 없는 부분에 대해 와일드카드(`*`)를 포함한 `aws:SourceArn` 글로벌 조건 컨텍스트 키를 사용합니다. 예를 들어 `arn:aws:ssm:*:123456789012:automation-execution/*`입니다.

다음 예는 자동화시 `aws:SourceArn` 및 `aws:SourceAccount` 전역 조건 컨텍스트 키를 사용하여 혼동된 대리자 문제를 방지하는 방법을 보여줍니다.

------
#### [ JSON ]

****  

```
{
  "Version":"2012-10-17",		 	 	 
  "Statement": [
    {
      "Effect": "Allow",
      "Principal": {
        "Service": [
          "ssm.amazonaws.com"
        ]
      },
      "Action": "sts:AssumeRole",
      "Condition": {
        "StringEquals": {
          "aws:SourceAccount": "123456789012"
        },
        "ArnLike": {
          "aws:SourceArn": "arn:aws:ssm:*:123456789012:automation-execution/*"
        }
      }
    }
  ]
}
```

------

**역할의 신뢰 정책 수정**

1. IAM 콘솔([https://console.aws.amazon.com/iam/](https://console.aws.amazon.com/iam/))을 엽니다.

1. 탐색 창에서 **역할**을 선택합니다.

1. 계정의 역할 목록에서 Automation 서비스 역할의 이름을 선택합니다.

1. **신뢰 관계** 탭을 선택한 후 **신뢰 관계 편집**을 선택합니다.

1. 혼동된 대리자 문제를 방지하기 위해 Automation에 `aws:SourceArn` 및 `aws:SourceAccount` 전역 조건 컨텍스트 키를 사용하여 신뢰 정책을 편집합니다.

1. **신뢰 정책 업데이트(Update Trust Policy)**를 선택하여 변경 사항을 저장합니다.

### (선택 사항) 다른 AWS 서비스를 간접적으로 호출할 Automation 인라인 정책과 고객 관리형 정책 추가
<a name="add-inline-policy"></a>

IAM 서비스 역할을 사용하여 다른 AWS 서비스을(를) 호출하는 자동화를 실행하는 경우 해당 서비스 역할이 다른 서비스를 호출할 권한이 있도록 구성되어야 합니다. 이 요구 사항은 `AWS-ConfigureS3BucketLogging`, `AWS-CreateDynamoDBBackup`, `AWS-RestartEC2Instance` 실행서 등의 모든 AWS Automation 실행서(`AWS-*` 실행서)에 적용됩니다. 또한 다른 서비스를 호출하는 작업을 사용하여 다른 AWS 서비스을(를) 호출하는 사용자 정의 실행서를 생성하는 경우에도 이 요구 사항이 항상 적용됩니다. 예를 들어 `aws:executeAwsApi`, `aws:CreateStack` 또는 `aws:copyImage`를 사용하는 경우 이러한 서비스를 호출할 수 있는 권한을 포함하여 서비스 역할을 구성해야 합니다. 역할에 IAM 인라인 정책과 고객 관리형 정책을 추가하여 다른 AWS 서비스에 대한 권한을 부여할 수 있습니다.

**서비스 역할의 인라인 정책을 포함하려면(IAM 콘솔)**

1. AWS Management Console에 로그인하여 [https://console.aws.amazon.com/iam/](https://console.aws.amazon.com/iam/)에서 IAM 콘솔을 엽니다.

1. 탐색 창에서 **역할**을 선택합니다.

1. 목록에서 편집할 역할의 이름을 선택합니다.

1. **권한** 탭을 선택합니다.

1. **권한 추가** 드롭다운에서 **정책 연결** 또는 **인라인 정책 생성**을 선택합니다.

1. **정책 연결**을 선택하는 경우 추가할 정책 옆의 확인란을 선택하고 **권한 추가**를 선택합니다.

1. **인라인 정책 생성**을 선택하는 경우 **JSON** 탭을 선택합니다.

1. 호출하려는 AWS 서비스‬의 JSON 정책 문서를 입력합니다. 다음은 2개의 예제 JSON Policy 문서입니다.

   **Amazon S3 PutObject 및 GetObject 예**

------
#### [ JSON ]

****  

   ```
   {
       "Version":"2012-10-17",		 	 	 
       "Statement": [
           {
               "Effect": "Allow",
               "Action": [
                   "s3:PutObject",
                   "s3:GetObject"
               ],
               "Resource": "arn:aws:s3:::amzn-s3-demo-bucket/*"
           }
       ]
   }
   ```

------

   **Amazon EC2 CreateSnapshot 및 DescribeSnapShots 예**

------
#### [ JSON ]

****  

   ```
   {
      "Version":"2012-10-17",		 	 	 
      "Statement":[
         {
            "Effect":"Allow",
            "Action":"ec2:CreateSnapshot",
            "Resource":"*"
         },
         {
            "Effect":"Allow",
            "Action":"ec2:DescribeSnapshots",
            "Resource":"*"
         }
      ]
   }
   ```

------

   IAM 정책 언어에 대한 자세한 내용은 *IAM User Guide*의 [IAM JSON Policy Reference](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies.html)를 참조하세요.

1. 작업이 완료되면 **정책 검토(Review policy)**를 선택합니다. [정책 검사기](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_policy-validator.html)가 모든 구문 오류를 보고합니다.

1. **정책 검토(Review policy)** 페이지에서 생성 중인 정책의 **이름(Name)**을 입력합니다. 정책 **요약**을 검토하여 정책이 부여한 권한을 확인합니다. 그런 다음 **정책 생성**을 선택하여 작업을 저장합니다.

1. 인라인 정책을 생성하면 이 정책이 역할에 자동으로 포함됩니다.

## 작업 2: Automation 역할에 iam:PassRole 정책 연결하기
<a name="attach-passrole-policy"></a>

다음 절차에 따라 자동화 서비스 역할에 `iam:PassRole` 정책을 연결합니다. 이렇게 하면 Automation 서비스가 자동화를 실행할 때 이 역할을 다른 서비스 또는 Systems Manager 도구에 전달할 수 있습니다.

**iam:PassRole 정책을 자동화 역할에 연결하려면,**

1. 방금 만든 역할에 대한 **요약** 페이지에서 **권한** 탭을 선택합니다.

1. **인라인 정책 추가(Add inline policy)**를 선택합니다.

1. **정책 생성(Create policy)** 페이지에서 **시각적 편집기(Visual editor)** 탭을 선택합니다.

1. **서비스(Service)**와 **IAM**을 차례대로 선택합니다.

1. **작업 선택**을 선택합니다.

1. **작업 필터링** 텍스트 상자에 **PassRole**을 입력하고 **PassRole** 옵션을 선택합니다.

1. **리소스**를 선택합니다. **Specific(특정)**이 선택되었는지 확인한 다음, **ARN 추가(Add ARN)**를 선택합니다.

1. **Specify ARN for role(역할 ARN 지정)** 필드에 작업 1의 마지막에 복사한 자동화 역할 ARN을 붙여 넣습니다. **계정(Account)** 및 **역할 이름 및 경로(Role name with path)** 필드에 값이 채워집니다.
**참고**  
Automation 서비스 역할에서 EC2 인스턴스에 IAM 인스턴스 프로파일 역할을 연결하려면 IAM 인스턴스 프로파일 역할의 ARN을 추가해야 합니다. 이렇게 하면 Automation 서비스 역할이 IAM 인스턴스 프로파일 역할을 대상 EC2 인스턴스로 전달할 수 있습니다.

1. **추가(Add)**를 선택합니다.

1. **정책 검토(Review policy)**를 선택합니다.

1. **정책 검토(Review Policy)** 페이지에 이름을 입력한 다음 **정책 생성(Create Policy)**을 선택합니다.

# 자격 증명 기반 정책 설정 예제
<a name="automation-setup-identity-based-policies"></a>

다음 섹션에서는 AWS Systems Manager 자동화 서비스에 대한 IAM 자격 증명 기반 정책의 예를 제공합니다. 이러한 예제 JSON 정책 문서를 사용하여 IAM 자격 증명 기반 정책을 생성하는 방법에 대한 자세한 내용은 *IAM 사용 설명서*에서 [IAM 정책 생성](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_create.html#access_policies_create-json-editor)을 참조하세요.

**참고**  
모든 예제는 가상의 계정 ID를 포함합니다. AWS 소유 퍼블릭 문서의 경우 Amazon 리소스 이름(ARN)에 계정 ID를 지정해서는 안 됩니다.

 **예제** 
+  [예제 1: 사용자가 자동화 문서를 실행하고 자동화 실행을 확인할 수 있도록 허용](#automation-setup-identity-based-policies-example-1) 
+  [예제 2: 사용자가 자동화 문서의 특정 버전을 실행하도록 허용](#automation-setup-identity-based-policies-example-2) 
+  [예제 3: 사용자가 특정 태그를 포함하는 자동화 문서를 실행하도록 허용](#automation-setup-identity-based-policies-example-3) 
+  [예제 4: 자동화 실행에 특정 태그 파라미터가 제공된 경우 사용자가 자동화 문서를 실행하도록 허용](#automation-setup-identity-based-policies-example-4) 

## 예제 1: 사용자가 자동화 문서를 실행하고 자동화 실행을 확인할 수 있도록 허용
<a name="automation-setup-identity-based-policies-example-1"></a>

다음 예제 IAM 정책에서는 사용자가 다음을 할 수 있도록 허용합니다.
+ 정책에 지정된 자동화 문서를 실행합니다. 문서 이름은 다음 항목에 의해 결정됩니다.

  ```
  arn:aws:ssm:*:111122223333:document/{{DocumentName}}
  ```
+ 자동화 실행을 중지하고 신호를 보냅니다.
+ 자동화 실행이 시작된 후 자동화 실행에 대한 세부 정보를 봅니다.

------
#### [ JSON ]

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Action": "ssm:StartAutomationExecution",
            "Effect": "Allow",
            "Resource": [
                "arn:aws:ssm:*:111122223333:document/{{DocumentName}}",
                "arn:aws:ssm:*:111122223333:automation-execution/*"
            ]
        },
        {
            "Action": [
                "ssm:StopAutomationExecution",
                "ssm:GetAutomationExecution",
                "ssm:DescribeAutomationExecutions",
                "ssm:DescribeAutomationStepExecutions",
                "ssm:SendAutomationSignal"
            ],
            "Resource": [
                "arn:aws:ssm:*:111122223333:automation-execution/*"
            ],
            "Effect": "Allow"
        }
    ]
}
```

------

## 예제 2: 사용자가 자동화 문서의 특정 버전을 실행하도록 허용
<a name="automation-setup-identity-based-policies-example-2"></a>

다음 예제 IAM 정책에서는 사용자가 자동화 문서의 특정 버전을 실행하도록 허용합니다.
+ 자동화 문서 이름은 다음 항목에 의해 결정됩니다.

  ```
  arn:aws:ssm:*:111122223333:document/{{DocumentName}}
  ```
+ 자동화 문서 버전은 다음 항목에 의해 결정됩니다.

  ```
  "ssm:DocumentVersion": "5"
  ```

------
#### [ JSON ]

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Action": "ssm:StartAutomationExecution",
            "Effect": "Allow",
            "Resource": [
                "arn:aws:ssm:*:111122223333:document/{{DocumentName}}"
            ],
            "Condition": {
                "ForAnyValue:StringEquals": {
                   "ssm:DocumentVersion": ["5"]
                }
            }
        },
        {
            "Action": [
                "ssm:StartAutomationExecution"
            ],
            "Resource": [
                "arn:aws:ssm:*:111122223333:automation-execution/*"
            ],
            "Effect": "Allow"
        },
        {
            "Action": [
                "ssm:StopAutomationExecution",
                "ssm:GetAutomationExecution",
                "ssm:DescribeAutomationExecutions",
                "ssm:DescribeAutomationStepExecutions",
                "ssm:SendAutomationSignal"
            ],
            "Resource": [
                "arn:aws:ssm:*:111122223333:automation-execution/*"
            ],
            "Effect": "Allow"
        }
    ]
}
```

------

## 예제 3: 사용자가 특정 태그를 포함하는 자동화 문서를 실행하도록 허용
<a name="automation-setup-identity-based-policies-example-3"></a>

다음 예제 IAM 정책에서는 사용자가 특정 태그가 있는 자동화 문서를 실행하도록 허용합니다.
+ 자동화 문서 이름은 다음 항목에 의해 결정됩니다.

  ```
  arn:aws:ssm:*:111122223333:document/{{DocumentName}}
  ```
+ 자동화 문서 태그는 다음 항목에 의해 결정됩니다.

  ```
  "ssm:DocumentVersion": "5"
  ```

------
#### [ JSON ]

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Action": "ssm:StartAutomationExecution",
            "Effect": "Allow",
            "Resource": [
                "arn:aws:ssm:*:111122223333:document/*"
            ],
            "Condition": {
                "StringEquals": {
                    "aws:ResourceTag/stage": "production"
                }
            }
        },
        {
            "Action": [
                "ssm:StartAutomationExecution"
            ],
            "Resource": [
                "arn:aws:ssm:*:111122223333:automation-execution/*"
            ],
            "Effect": "Allow"
        },
        {
            "Action": [
                "ssm:StopAutomationExecution",
                "ssm:GetAutomationExecution",
                "ssm:DescribeAutomationExecutions",
                "ssm:DescribeAutomationStepExecutions",
                "ssm:SendAutomationSignal"
            ],
            "Resource": [
                "arn:aws:ssm:*:111122223333:automation-execution/*"
            ],
            "Effect": "Allow"
        }
    ]
}
```

------

## 예제 4: 자동화 실행에 특정 태그 파라미터가 제공된 경우 사용자가 자동화 문서를 실행하도록 허용
<a name="automation-setup-identity-based-policies-example-4"></a>

다음 예제 IAM 정책에서는 자동화 실행에 특정 태그 파라미터가 제공된 경우 사용자에게 자동화 문서를 실행할 수 있는 권한을 부여합니다.
+ 정책에 지정된 자동화 문서를 실행합니다. 문서 이름은 다음 항목에 의해 결정됩니다.

  ```
  arn:aws:ssm:*:111122223333:document/{{DocumentName}}
  ```
+ 자동화 실행에 특정 태그 파라미터를 제공해야 합니다. 자동화 실행 리소스의 태그 파라미터는 다음 항목에 의해 결정됩니다.

  ```
  "aws:ResourceTag/stage": "production"
  ```
+ 지정된 태그가 있는 자동화 실행을 중지하고 신호를 보냅니다.
+ 지정된 태그가 있는 자동화 실행에 대한 세부 정보를 확인합니다.
+ SSM 리소스에 지정된 태그를 추가합니다.

------
#### [ JSON ]

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Action": "ssm:StartAutomationExecution",
            "Effect": "Allow",
            "Resource": [
                "arn:aws:ssm:*:111122223333:document/{{DocumentName}}"
            ]
        },
        {
            "Action": [
                "ssm:StartAutomationExecution",
                "ssm:StopAutomationExecution",
                "ssm:GetAutomationExecution",
                "ssm:DescribeAutomationExecutions",
                "ssm:DescribeAutomationStepExecutions",
                "ssm:SendAutomationSignal"
            ],
            "Resource": [
                "arn:aws:ssm:*:111122223333:automation-execution/*"
            ],
            "Effect": "Allow",
            "Condition": {
                "StringEquals": {
                    "aws:ResourceTag/environment": "beta"
                }
            }
        },
        {
            "Action": "ssm:AddTagsToResource",
            "Effect": "Allow",
            "Resource": [
                "arn:aws:ssm:*:111122223333:automation-execution/*"
            ]
        }
    ]
}
```

------

# Automation이 동시성 요구 사항에 따라 조정되도록 허용
<a name="adaptive-concurrency"></a>

기본적으로 Automation을 사용하면 한 번에 최대 100개의 동시 자동화를 실행할 수 있습니다. Automation은 동시성 자동화 할당량을 자동으로 조정하는 데 사용할 수 있는 선택적 설정도 제공합니다. 이 설정을 사용하면 사용 가능한 리소스에 따라 동시성 자동화 할당량이 최대 500개의 동시 자동화를 수용할 수 있습니다.

**참고**  
자동화가 API 작업을 호출하는 경우 대상에 맞게 조정하면 제한 예외가 발생할 수 있습니다. 적응형 동시성이 설정된 상태에서 자동화를 실행할 때 반복 제한 예외가 발생하면 사용 가능한 경우 API 작업에 대한 할당량 증가를 요청해야 할 수 있습니다.

**AWS Management Console을 사용하여 적응형 동시성 설정**

1. [https://console.aws.amazon.com/systems-manager/](https://console.aws.amazon.com/systems-manager/)에서 AWS Systems Manager 콘솔을 엽니다.

1. 왼쪽 탐색 창에서 **Automation**을 선택합니다.

1. **기본 설정** 탭을 선택하고 **편집**을 선택합니다.

1. **적응형 동시성 사용(Enable adaptive concurrency)** 옆에 있는 확인란을 선택합니다.

1. **저장**을 선택합니다.

**명령줄을 사용하여 적응형 동시성 설정**
+ AWS CLI 또는 Tools for Windows PowerShell을 열고 다음 명령을 실행하여 요청 리전의 계정에 적응형 동시성을 설정합니다.

------
#### [ Linux & macOS ]

  ```
  aws ssm update-service-setting \
      --setting-id /ssm/automation/enable-adaptive-concurrency \
      --setting-value True
  ```

------
#### [ Windows ]

  ```
  aws ssm update-service-setting ^
      --setting-id /ssm/automation/enable-adaptive-concurrency ^
      --setting-value True
  ```

------
#### [ PowerShell ]

  ```
  Update-SSMServiceSetting `
      -SettingId "/ssm/automation/enable-adaptive-concurrency" `
      -SettingValue "True"
  ```

------

# 스로틀링된 작업에 대한 자동 재시도 구성
<a name="automation-throttling-retry"></a>

각 계정에서 실행할 수 있는 동시 자동화 실행 수에는 제한이 있습니다. 계정에서 여러 자동화를 동시에 실행하려고 하면 스로틀링 문제가 발생할 수 있습니다. 자동 스로틀링 재시도 기능을 사용하여 스로틀링된 자동화 단계에 대한 재시도 동작을 구성할 수 있습니다.

자동화 작업에 대한 자동 스로틀링 재시도는 대규모 작업을 위한 보다 탄력적인 실행 환경을 제공합니다. 스로틀링 재시도 기능은 `aws:executeScript`를 제외한 모든 [자동화 작업](automation-actions.md)을 지원합니다.

스로틀링 재시도 설정은 기존 `maxAttempts` 단계 속성 외에도 작동합니다. 둘 다 구성되면 시스템은 먼저 지정된 제한 시간 내에 스로틀링 재시도를 시도한 다음, 단계가 계속 실패할 경우 `maxAttempts` 설정을 적용합니다.

**AWS Management Console을 사용하여 스로틀링 재시도를 구성하는 방법**

1. [https://console.aws.amazon.com/systems-manager/](https://console.aws.amazon.com/systems-manager/)에서 AWS Systems Manager 콘솔을 엽니다.

1. 왼쪽 탐색 창에서 **Automation**을 선택합니다.

1. **기본 설정** 탭을 선택하고 **편집**을 선택합니다.

1. **스로틀링 재시도 시간 제한** 필드에 0\$13,600초 사이의 값을 입력합니다. 이는 시스템이 병목 현상이 발생한 단계를 재시도하는 최대 시간을 지정합니다.

1. **저장**을 선택합니다.

**명령줄을 사용하여 스로틀링 재시도를 구성하는 방법**
+ AWS CLI 또는 Tools for Windows PowerShell을 열고 다음 명령을 실행하여 요청 리전의 계정에 스로틀링 재시도를 구성합니다.

------
#### [ Linux & macOS ]

  ```
  aws ssm update-service-setting \
      --setting-id /ssm/automation/throttling-retry-time-limit \
      --setting-value 3600
  ```

------
#### [ Windows ]

  ```
  aws ssm update-service-setting ^
      --setting-id /ssm/automation/throttling-retry-time-limit ^
      --setting-value 3600
  ```

------
#### [ PowerShell ]

  ```
  Update-SSMServiceSetting `
      -SettingId "/ssm/automation/throttling-retry-time-limit" `
      -SettingValue "3600"
  ```

------

# Automation을 위한 변경 제어 구현
<a name="automation-change-calendar-integration"></a>

기본적으로 Automation을 사용하면 날짜 및 시간 제한 없이 런북을 사용할 수 있습니다. Automation과 Change Calendar를 통합하여 AWS 계정의 모든 자동화에 대한 변경 제어를 구현할 수 있습니다. 이 설정을 사용하면 계정의 AWS Identity and Access Management(IAM) 보안 주체가 변경 일정에서 허용하는 기간 동안에만 자동화를 실행할 수 있습니다. Change Calendar 사용에 대한 자세한 내용은 [Change Calendar 작업](systems-manager-change-calendar-working.md) 섹션을 참조하세요.

**변경 제어 켜기(콘솔)**

1. [https://console.aws.amazon.com/systems-manager/](https://console.aws.amazon.com/systems-manager/)에서 AWS Systems Manager 콘솔을 엽니다.

1. 왼쪽 탐색 창에서 **Automation**을 선택합니다.

1. **기본 설정** 탭을 선택하고 **편집**을 선택합니다.

1. **Change Calendar 통합 켜기** 옆의 확인란을 선택합니다.

1. **변경 캘린더 선택** 드롭다운 목록에서 Automation이 따를 변경 캘린더를 선택합니다.

1. **저장**을 선택합니다.

# Systems Manager Automation을 기반으로 자동화된 작업 실행
<a name="running-simple-automations"></a>

자동화를 실행하면 기본적으로 자동화를 시작한 사용자의 컨텍스트에서 자동화가 실행됩니다. 따라서 사용자가 관리자 권한을 가지고 있는 경우에는 관리자 권한과 자동화를 통해 구성 중인 리소스에 대한 모든 액세스 권한을 가지고 자동화가 실행됩니다. 보안 모범 사례에 따라 이 경우 AmazonSSMAutomationRole 관리형 정책으로 구성된 수임 역할로 알려진 IAM 서비스 역할을 사용하여 자동화를 실행하는 것이 좋습니다. 다양한 런북을 사용하려면 수임 역할에 IAM 정책을 추가해야 할 수 있습니다. IAM 서비스 역할을 사용하여 자동화를 실행하는 것을 *위임된 관리*라고 합니다.

서비스 역할을 사용하면 AWS 리소스에 대한 자동화 실행이 허용되지만, 자동화를 실행한 사용자는 해당 리소스에 대한 액세스 권한이 제한되거나 액세스 권한이 없습니다. 예를 들어 서비스 역할을 구성하고 Automation에서 이를 사용하여 Amazon Elastic Compute Cloud(Amazon EC2) 인스턴스를 하나 이상 다시 시작할 수 있습니다. Automation은 AWS Systems Manager의 도구입니다. 자동화는 인스턴스를 다시 시작하지만, 서비스 역할은 사용자에게 이들 인스턴스에 액세스할 수 있는 권한을 부여하지 않습니다.

자동화를 실행할 때 런타임 시 서비스 역할을 지정하거나, 사용자 정의 실행서를 생성하고 실행서에서 서비스 역할을 직접 지정할 수 있습니다. 런타임 시 또는 실행서에서 서비스 역할을 지정하면 지정된 서비스 역할의 컨텍스트에서 서비스가 실행됩니다. 서비스 역할을 지정하지 않으면 시스템이 사용자의 컨텍스트에서 임시 세션을 생성하고 자동화를 실행합니다.

**참고**  
자동화를 12시간 이상 실행해야 하는 경우에는 자동화를 위한 서비스 역할을 반드시 지정해야 합니다. 사용자의 컨텍스트에서 장기 실행 자동화를 시작하면 12시간 후에 사용자의 임시 세션이 만료됩니다.

위임된 관리를 통해 AWS 리소스에 대한 보안과 제어를 강화할 수 있습니다. 또한 여러 IAM 계정 대신 중앙의 서비스 역할이 리소스에 대한 작업을 수행하기 때문에 감사 기능을 강화할 수 있습니다.

**시작하기 전 준비 사항**  
다음 절차를 완료하기 전에 먼저 IAM 서비스 역할을 생성하고 AWS Systems Manager의 도구인 Automation에 대해 신뢰 관계를 구성해야 합니다. 자세한 내용은 [작업 1: Automation을 위한 서비스 역할 생성](automation-setup-iam.md#create-service-role) 섹션을 참조하세요.

다음 절차에서는 Systems Manager 콘솔 또는 원하는 명령줄 도구를 사용하여 간단한 자동화를 실행하는 방법을 설명합니다.

## 단순한 자동화 실행(콘솔)
<a name="simple-console"></a>

다음 절차에서는 Systems Manager 콘솔을 사용하여 단순한 자동화를 실행하는 방법을 설명합니다.

**단순한 자동화를 실행하려면**

1. AWS Systems Manager 콘솔[https://console.aws.amazon.com/systems-manager/](https://console.aws.amazon.com/systems-manager/)을 엽니다.

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

1. [**Automation 문서(Automation document)**] 목록에서 실행서를 선택합니다. **문서 카테고리** 창에서 옵션을 1개 이상 선택하여 SSM 문서를 목적에 따라 필터링합니다. 자신이 소유한 실행서를 보려면 [**내 소유(Owned by me)**] 탭을 선택합니다. 자신의 계정과 공유하고 있는 실행서를 보려면 [**나와 공유됨(Shared with me)**] 탭을 선택합니다. 모든 실행서를 보려면 [**모든 문서(All documents)**] 탭을 선택합니다.
**참고**  
실행서 이름을 선택하여 실행서에 대한 정보를 볼 수 있습니다.

1. **문서 세부 정보** 섹션에서 **문서 버전**이 실행할 버전으로 설정되었는지 확인합니다. 이 시스템에는 다음 버전 옵션이 포함되어 있습니다.
   + **런타임 시 기본 버전** - Automation 런북이 정기적으로 업데이트되며 새 기본 버전이 할당된 경우 이 옵션을 선택합니다.
   + **런타임 시 최신 버전** - Automation 런북이 정기적으로 업데이트되며 최근에 업데이트된 버전을 실행하려는 경우 이 옵션을 선택합니다.
   + **1(기본값)** - 문서의 최초 버전을 실행하려면 이 옵션을 선택합니다(기본값).

1. **다음**을 선택합니다.

1. **실행 모드** 섹션에서 **Simple execution(단순 실행)**을 선택합니다.

1. **입력 파라미터** 섹션에서 필수 입력을 지정합니다. 필요에 따라 **AutomationAssumeRole** 목록에서 IAM 서비스 역할을 선택합니다.

1. (선택 사항) 모니터링을 위해 자동화에 적용할 CloudWatch 경보를 선택합니다. CloudWatch 경보를 자동화에 연결하려면 자동화를 시작하는 IAM 보안 주체에 `iam:createServiceLinkedRole` 작업에 대한 권한이 있어야 합니다. CloudWatch 경보에 대한 자세한 내용은 [Amazon CloudWatch 경보 사용](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/AlarmThatSendsEmail.html)을 참조하세요. 경보가 활성화되면 자동화가 중지됩니다. AWS CloudTrail을 사용하면 추적에 API 호출이 표시됩니다.

1. **실행**을 선택합니다.

콘솔에 자동화 상태가 표시됩니다. 자동화가 실행되지 않는 경우 [Systems Manager Automation 문제 해결](automation-troubleshooting.md) 섹션을 참조하세요.

자동화 실행이 완료되면 동일하거나 수정된 파라미터로 실행을 다시 실행할 수 있습니다. 자세한 내용은 [자동화 실행 재실행](automation-rerun-executions.md) 섹션을 참조하세요.

## 단순한 자동화 실행(명령줄)
<a name="simple-cli"></a>

다음 절차에서는 AWS CLI(Linux 또는 Windows) 또는 AWS Tools for PowerShell을 사용하여 단순한 자동화를 실행하는 방법을 설명합니다.

**단순한 자동화를 실행하려면**

1. 아직 하지 않은 경우 AWS CLI 또는 AWS Tools for PowerShell을 설치하고 구성합니다.

   자세한 내용은 [최신 버전의 AWS CLI 설치 또는 업데이트](https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html) 및 [AWS Tools for PowerShell 설치](https://docs.aws.amazon.com/powershell/latest/userguide/pstools-getting-set-up.html)를 참조하세요.

1. 단순한 자동화를 시작하려면 다음 명령을 실행합니다. 각 *example resource placeholder*를 사용자의 정보로 바꿉니다.

------
#### [ Linux & macOS ]

   ```
   aws ssm start-automation-execution \
       --document-name runbook name \
       --parameters runbook parameters
   ```

------
#### [ Windows ]

   ```
   aws ssm start-automation-execution ^
       --document-name runbook name ^
       --parameters runbook parameters
   ```

------
#### [ PowerShell ]

   ```
   Start-SSMAutomationExecution `
     -DocumentName runbook name `
     -Parameter runbook parameters
   ```

------

   여기에 실행서 `AWS-RestartEC2Instance`를 사용하여 지정된 EC2 인스턴스를 다시 시작하는 예가 있습니다.

------
#### [ Linux & macOS ]

   ```
   aws ssm start-automation-execution \
       --document-name "AWS-RestartEC2Instance" \
       --parameters "InstanceId=i-02573cafcfEXAMPLE"
   ```

------
#### [ Windows ]

   ```
   aws ssm start-automation-execution ^
       --document-name "AWS-RestartEC2Instance" ^
       --parameters "InstanceId=i-02573cafcfEXAMPLE"
   ```

------
#### [ PowerShell ]

   ```
   Start-SSMAutomationExecution `
     -DocumentName AWS-RestartEC2Instance `
     -Parameter @{"InstanceId"="i-02573cafcfEXAMPLE"}
   ```

------

   시스템은 다음과 같은 정보를 반환합니다.

------
#### [ Linux & macOS ]

   ```
   {
       "AutomationExecutionId": "4105a4fc-f944-11e6-9d32-0123456789ab"
   }
   ```

------
#### [ Windows ]

   ```
   {
       "AutomationExecutionId": "4105a4fc-f944-11e6-9d32-0123456789ab"
   }
   ```

------
#### [ PowerShell ]

   ```
   4105a4fc-f944-11e6-9d32-0123456789ab
   ```

------

1. 다음 명령을 실행하여 자동화 상태를 검색합니다.

------
#### [ Linux & macOS ]

   ```
   aws ssm describe-automation-executions \
       --filter "Key=ExecutionId,Values=4105a4fc-f944-11e6-9d32-0123456789ab"
   ```

------
#### [ Windows ]

   ```
   aws ssm describe-automation-executions ^
       --filter "Key=ExecutionId,Values=4105a4fc-f944-11e6-9d32-0123456789ab"
   ```

------
#### [ PowerShell ]

   ```
   Get-SSMAutomationExecutionList | `
     Where {$_.AutomationExecutionId -eq "4105a4fc-f944-11e6-9d32-0123456789ab"}
   ```

------

   시스템은 다음과 같은 정보를 반환합니다.

------
#### [ Linux & macOS ]

   ```
   {
       "AutomationExecutionMetadataList": [
           {
               "AutomationExecutionStatus": "InProgress",
               "CurrentStepName": "stopInstances",
               "Outputs": {},
               "DocumentName": "AWS-RestartEC2Instance",
               "AutomationExecutionId": "4105a4fc-f944-11e6-9d32-0123456789ab",
               "DocumentVersion": "1",
               "ResolvedTargets": {
                   "ParameterValues": [],
                   "Truncated": false
               },
               "AutomationType": "Local",
               "Mode": "Auto",
               "ExecutionStartTime": 1564600648.159,
               "CurrentAction": "aws:changeInstanceState",
               "ExecutedBy": "arn:aws:sts::123456789012:assumed-role/Administrator/Admin",
               "LogFile": "",
               "Targets": []
           }
       ]
   }
   ```

------
#### [ Windows ]

   ```
   {
       "AutomationExecutionMetadataList": [
           {
               "AutomationExecutionStatus": "InProgress",
               "CurrentStepName": "stopInstances",
               "Outputs": {},
               "DocumentName": "AWS-RestartEC2Instance",
               "AutomationExecutionId": "4105a4fc-f944-11e6-9d32-0123456789ab",
               "DocumentVersion": "1",
               "ResolvedTargets": {
                   "ParameterValues": [],
                   "Truncated": false
               },
               "AutomationType": "Local",
               "Mode": "Auto",
               "ExecutionStartTime": 1564600648.159,
               "CurrentAction": "aws:changeInstanceState",
               "ExecutedBy": "arn:aws:sts::123456789012:assumed-role/Administrator/Admin",
               "LogFile": "",
               "Targets": []
           }
       ]
   }
   ```

------
#### [ PowerShell ]

   ```
   AutomationExecutionId       : 4105a4fc-f944-11e6-9d32-0123456789ab
   AutomationExecutionStatus   : InProgress
   AutomationType              : Local
   CurrentAction               : aws:changeInstanceState
   CurrentStepName             : startInstances
   DocumentName                : AWS-RestartEC2Instance
   DocumentVersion             : 1
   ExecutedBy                  : arn:aws:sts::123456789012:assumed-role/Administrator/Admin
   ExecutionEndTime            : 1/1/0001 12:00:00 AM
   ExecutionStartTime          : 7/31/2019 7:17:28 PM
   FailureMessage              : 
   LogFile                     : 
   MaxConcurrency              : 
   MaxErrors                   : 
   Mode                        : Auto
   Outputs                     : {}
   ParentAutomationExecutionId : 
   ResolvedTargets             : Amazon.SimpleSystemsManagement.Model.ResolvedTargets
   Target                      : 
   TargetMaps                  : {}
   TargetParameterName         : 
   Targets                     : {}
   ```

------

# 자동화 실행 재실행
<a name="automation-rerun-executions"></a>

AWS Systems Manager 자동화 실행을 다시 실행하여 동일하거나 수정된 파라미터로 작업을 반복할 수 있습니다. 재실행 기능을 사용하면 자동화 구성을 수동으로 다시 생성하지 않고도 자동화 실행을 효율적으로 복제하여 운영 오버헤드와 구성 오류가 발생할 가능성을 줄일 수 있습니다.

자동화 실행을 다시 실행하면 Systems Manager는 이전 실행의 원래 런북 파라미터, Amazon CloudWatch 경보 및 태그를 보존합니다. 시스템은 새 실행 ID와 업데이트된 타임스탬프를 사용하여 새 실행을 생성합니다. 간단한 실행, 속도 제어 실행, 계정 간 실행 및 리전 간 실행, 수동 실행을 포함하여 모든 유형의 자동화 실행을 다시 실행할 수 있습니다.

## 자동화 실행 재실행(콘솔)
<a name="rerun-console"></a>

다음 절차에서는 Systems Manager 콘솔을 사용하여 자동 실행을 재실행하는 방법을 설명합니다.

**자동화 홈 페이지에서 자동화 실행을 다시 실행하는 방법**

AWS Systems Manager 콘솔([https://console.aws.amazon.com/systems-manager/](https://console.aws.amazon.com/systems-manager/))을 엽니다.

1. 왼쪽 탐색 창에서 **자동화**를 선택합니다.

1. 실행 목록에서 다시 실행하려는 실행을 선택합니다.

1. **실행 재실행**을 선택합니다.

1. **자동화 문서 실행** 페이지에서 원래 실행에 미리 입력된 파라미터, 실행 모드 및 대상 구성을 검토합니다.

1. (선택 사항) 재실행에 필요한 파라미터, 대상 또는 기타 설정을 수정합니다.

1. **실행**을 선택하여 새 실행 ID로 재실행을 시작합니다.

**실행 세부 정보 페이지에서 자동화 실행을 다시 실행하는 방법**

AWS Systems Manager 콘솔([https://console.aws.amazon.com/systems-manager/](https://console.aws.amazon.com/systems-manager/))을 엽니다.

1. 왼쪽 탐색 창에서 **자동화**를 선택합니다.

1. 다시 실행할 자동화의 실행 ID를 선택합니다.

1. 실행 세부 정보 페이지에서 **실행 재실행**을 선택합니다.

1. **자동화 문서 실행** 페이지에서 원래 실행에 미리 입력된 파라미터, 실행 모드 및 대상 구성을 검토합니다.

1. (선택 사항) 재실행에 필요한 파라미터, 대상 또는 기타 설정을 수정합니다.

1. **실행**을 선택하여 새 실행 ID로 재실행을 시작합니다.

**자동화 실행을 새 실행에 복사하는 방법**

AWS Systems Manager 콘솔([https://console.aws.amazon.com/systems-manager/](https://console.aws.amazon.com/systems-manager/))을 엽니다.

1. 왼쪽 탐색 창에서 **자동화**를 선택합니다.

1. 복사하려는 자동화의 실행 ID를 선택합니다.

1. 실행 세부 정보 페이지에서 **작업**을 선택한 다음 **새로 복사**를 선택합니다.

1. **자동화 문서 실행** 페이지에서 원래 실행에 미리 입력된 파라미터, 실행 모드 및 대상 구성을 검토합니다.

1. (선택 사항) 새 실행에 필요한 파라미터, 대상 또는 기타 설정을 수정합니다.

1. **실행**을 선택하여 새 실행을 시작합니다.

# 승인이 필요한 자동화 실행
<a name="running-automations-require-approvals"></a>

다음 절차에서는 단순 실행 모드에서 승인자를 사용하여 자동화를 실행하도록 AWS Systems Manager 콘솔과 AWS Command Line Interface(AWS CLI)를 사용하는 방법을 설명합니다. 자동화는 지정된 보안 주체가 작업을 승인 또는 거부할 때까지 자동화를 일시 중지하는 자동화 작업 `aws:approve`를 사용합니다. 자동화는 현재 사용자의 컨텍스트에서 실행됩니다. 이는 런북과 그 런북에 의해 호출되는 모든 작업을 사용할 권한이 있는 한 추가 IAM 권한을 구성할 필요가 없음을 뜻합니다. IAM에서 관리자 권한이 있는 경우 이 런북을 사용할 권한이 이미 있습니다.

**시작하기 전 준비 사항**  
실행서에 요구되는 표준 입력 이외에 `aws:approve` 작업에는 다음 두 파라미터가 필요합니다.
+ 승인자 목록. 승인자 목록은 사용자 이름 또는 사용자 ARN 형식의 승인자를 하나 이상 포함해야 합니다. 여러 승인자를 제공하는 경우 런북 내에 해당하는 최소 승인 횟수도 지정해야 합니다.
+ Amazon Simple Notification Service(Amazon SNS) 주제 ARN Amazon SNS 주제 이름은 `Automation`으로 시작해야 합니다.

이 절차에서는 승인 요청을 전송하는 데 필요한 Amazon SNS 주제를 이미 생성한 것으로 가정합니다. 자세한 내용은 *Amazon Simple Notification Service Developer Guide*의 [Create a Topic](https://docs.aws.amazon.com/sns/latest/dg/sns-getting-started.html#CreateTopic)을 참조하세요.

## 승인자를 사용하여 자동화 실행(콘솔)
<a name="approval-console"></a>

**승인자를 사용하여 자동화를 실행하려면**

다음 절차에서는 Systems Manager 콘솔에서 승인자를 사용하여 자동화를 실행하는 방법을 설명합니다.

1. AWS Systems Manager 콘솔[https://console.aws.amazon.com/systems-manager/](https://console.aws.amazon.com/systems-manager/)을 엽니다.

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

1. [**Automation 문서(Automation document)**] 목록에서 실행서를 선택합니다. **문서 카테고리** 창에서 옵션을 1개 이상 선택하여 SSM 문서를 목적에 따라 필터링합니다. 자신이 소유한 실행서를 보려면 [**내 소유(Owned by me)**] 탭을 선택합니다. 자신의 계정과 공유하고 있는 실행서를 보려면 [**나와 공유됨(Shared with me)**] 탭을 선택합니다. 모든 실행서를 보려면 [**모든 문서(All documents)**] 탭을 선택합니다.
**참고**  
실행서 이름을 선택하여 실행서에 대한 정보를 볼 수 있습니다.

1. **문서 세부 정보** 섹션에서 **문서 버전**이 실행할 버전으로 설정되었는지 확인합니다. 이 시스템에는 다음 버전 옵션이 포함되어 있습니다.
   + **런타임 시 기본 버전** - Automation 런북이 정기적으로 업데이트되며 새 기본 버전이 할당된 경우 이 옵션을 선택합니다.
   + **런타임 시 최신 버전** - Automation 런북이 정기적으로 업데이트되며 최근에 업데이트된 버전을 실행하려는 경우 이 옵션을 선택합니다.
   + **1(기본값)** - 문서의 최초 버전을 실행하려면 이 옵션을 선택합니다(기본값).

1. **다음**을 선택합니다.

1. **Execute automation document(자동화 문서 실행)** 페이지에서 **Simple execution(단순 실행)**을 선택합니다.

1. **입력 파라미터** 섹션에서 필요한 입력 파라미터를 지정합니다.

   예를 들어 `AWS-StartEC2InstanceWithApproval` 런북을 선택한 경우 **InstanceId** 파라미터에 대해 인스턴스 ID를 지정하거나 선택해야 합니다.

1. **승인자** 섹션에서 자동화 작업 승인자의 IAM 사용자 또는 사용자 ARN을 지정합니다.

1. **SNSTopicARN** 섹션에서 승인 알림을 전송하는 데 사용할 SNS 주제 ARN을 지정합니다. SNS 주제 이름은 **Automation**으로 시작해야 합니다.

1. 필요에 따라 [**AutomationAssumeRole**] 목록에서 IAM 서비스 역할을 선택합니다. 100개가 넘는 계정 및 리전을 대상으로 지정하는 경우 `AWS-SystemsManager-AutomationAdministrationRole`을 지정해야 합니다.

1. **자동화 실행(Execute automation)**을 선택합니다.

지정된 승인자는 자동화를 승인 또는 거부하기 위한 세부 정보가 표함된 Amazon SNS 알림을 받습니다. 이 승인 작업은 발행 날짜로부터 7일간 유효하고 Systems Manager 콘솔 또는 AWS Command Line Interface(AWS CLI)를 사용하여 발행할 수 있습니다.

자동화를 승인하기로 결정하면 자동화가 지정된 실행서에 포함된 단계를 실행합니다. 콘솔에 자동화 상태가 표시됩니다. 자동화가 실행되지 않는 경우 [Systems Manager Automation 문제 해결](automation-troubleshooting.md) 섹션을 참조하세요.

**자동화를 승인 또는 거부하려면**

1. [https://console.aws.amazon.com/systems-manager/](https://console.aws.amazon.com/systems-manager/)에서 AWS Systems Manager 콘솔을 엽니다.

1. 탐색 창에서 [**자동화(Automation)**]를 선택하고 이전 절차에서 실행한 자동화를 선택합니다.

1. **작업**을 선택하고 **Approve/Deny(승인/거부)**를 선택합니다.

1. **승인** 또는 **거부**를 선택하고 선택적으로 설명을 입력합니다.

1. **제출**을 선택합니다.

## 승인자를 사용하여 자동화 실행(명령줄)
<a name="approval-cli"></a>

다음 절차에서는 AWS CLI(Linux 또는 Windows) 또는 AWS Tools for PowerShell에서 승인자를 사용하여 자동화를 실행하는 방법을 설명합니다.

**승인자를 사용하여 자동화를 실행하려면**

1. 아직 하지 않은 경우 AWS CLI 또는 AWS Tools for PowerShell을 설치하고 구성합니다.

   자세한 내용은 [최신 버전의 AWS CLI 설치 또는 업데이트](https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html) 및 [AWS Tools for PowerShell 설치](https://docs.aws.amazon.com/powershell/latest/userguide/pstools-getting-set-up.html)를 참조하세요.

1. 승인자를 사용하여 자동화를 실행하려면 다음 명령을 실행합니다. 각 *example resource placeholder*를 사용자의 정보로 바꿉니다. 문서 이름 섹션에 `aws:approve` 자동화 작업을 포함하는 런북을 지정합니다.

   `Approvers`에서 작업 승인자의 사용자 이름 또는 사용자 ARN을 지정합니다. `SNSTopic`에서 승인 알림을 전송하는 데 사용할 SNS 주제 ARN을 지정합니다. Amazon SNS 주제 이름은 `Automation`으로 시작해야 합니다.
**참고**  
승인자 및 SNS 주제의 파라미터 값은 선택한 실행서에 지정된 값에 따라 특정한 이름이 다릅니다.

------
#### [ Linux & macOS ]

   ```
   aws ssm start-automation-execution \
       --document-name "AWS-StartEC2InstanceWithApproval" \
       --parameters "InstanceId=i-02573cafcfEXAMPLE,Approvers=arn:aws:iam::123456789012:role/Administrator,SNSTopicArn=arn:aws:sns:region:123456789012:AutomationApproval"
   ```

------
#### [ Windows ]

   ```
   aws ssm start-automation-execution ^
       --document-name "AWS-StartEC2InstanceWithApproval" ^
       --parameters "InstanceId=i-02573cafcfEXAMPLE,Approvers=arn:aws:iam::123456789012:role/Administrator,SNSTopicArn=arn:aws:sns:region:123456789012:AutomationApproval"
   ```

------
#### [ PowerShell ]

   ```
   Start-SSMAutomationExecution `
       -DocumentName AWS-StartEC2InstanceWithApproval `
       -Parameters @{
           "InstanceId"="i-02573cafcfEXAMPLE"
           "Approvers"="arn:aws:iam::123456789012:role/Administrator"
           "SNSTopicArn"="arn:aws:sns:region:123456789012:AutomationApproval"
       }
   ```

------

   시스템은 다음과 같은 정보를 반환합니다.

------
#### [ Linux & macOS ]

   ```
   {
       "AutomationExecutionId": "df325c6d-b1b1-4aa0-8003-6cb7338213c6"
   }
   ```

------
#### [ Windows ]

   ```
   {
       "AutomationExecutionId": "df325c6d-b1b1-4aa0-8003-6cb7338213c6"
   }
   ```

------
#### [ PowerShell ]

   ```
   df325c6d-b1b1-4aa0-8003-6cb7338213c6
   ```

------

**자동화를 승인하려면**
+ 자동화를 승인하려면 다음 명령을 실행합니다. 각 *example resource placeholder*를 사용자의 정보로 바꿉니다.

------
#### [ Linux & macOS ]

  ```
  aws ssm send-automation-signal \
      --automation-execution-id "df325c6d-b1b1-4aa0-8003-6cb7338213c6" \
      --signal-type "Approve" \
      --payload "Comment=your comments"
  ```

------
#### [ Windows ]

  ```
  aws ssm send-automation-signal ^
      --automation-execution-id "df325c6d-b1b1-4aa0-8003-6cb7338213c6" ^
      --signal-type "Approve" ^
      --payload "Comment=your comments"
  ```

------
#### [ PowerShell ]

  ```
  Send-SSMAutomationSignal `
      -AutomationExecutionId df325c6d-b1b1-4aa0-8003-6cb7338213c6 `
      -SignalType Approve `
      -Payload @{"Comment"="your comments"}
  ```

------

  명령이 성공해도 출력은 없습니다.

**자동화를 거부하려면**
+ 자동화를 거부하려면 다음 명령을 실행합니다. 각 *example resource placeholder*를 사용자의 정보로 바꿉니다.

------
#### [ Linux & macOS ]

  ```
  aws ssm send-automation-signal \
      --automation-execution-id "df325c6d-b1b1-4aa0-8003-6cb7338213c6" \
      --signal-type "Deny" \
      --payload "Comment=your comments"
  ```

------
#### [ Windows ]

  ```
  aws ssm send-automation-signal ^
      --automation-execution-id "df325c6d-b1b1-4aa0-8003-6cb7338213c6" ^
      --signal-type "Deny" ^
      --payload "Comment=your comments"
  ```

------
#### [ PowerShell ]

  ```
  Send-SSMAutomationSignal `
      -AutomationExecutionId df325c6d-b1b1-4aa0-8003-6cb7338213c6 `
      -SignalType Deny `
      -Payload @{"Comment"="your comments"}
  ```

------

  명령이 성공해도 출력은 없습니다.

# 대규모로 자동화된 작업 실행
<a name="running-automations-scale"></a>

AWS Systems Manager Automation을 사용하면 대상을 사용하여 AWS 리소스 플릿에서 자동화를 실행할 수 있습니다. 또한 동시성 값과 오류 임계값을 지정하여 플릿 전체의 자동화 배포를 제어할 수도 있습니다. 동시성 및 오류 임계값 기능을 통칭하여 *속도 제어*라고 합니다. 동시성 값은 자동화를 동시에 실행하도록 허용된 리소스의 수를 결정합니다. 또한 Automation은 사용자가 선택할 수 있는 적응형 동시성 모드를 제공합니다. 적응형 동시성은 동시에 실행되는 자동화 100개에서 최대 500개로 자동화 할당량을 자동으로 조정합니다. 오류 임계값은 Systems Manager가 자동화를 다른 리소스로 보내는 것을 중지할 때까지 허용되는 자동화 실패 횟수를 결정합니다.

동시성 및 오류 임계값에 대한 자세한 내용은 [대규모 자동화 제어](running-automations-scale-controls.md) 섹션을 참조하세요. 대상에 대한 자세한 내용은 [자동화를 위한 대상 매핑](running-automations-map-targets.md) 섹션을 참조하세요.

다음 절차에서는 적응형 동시성을 설정하는 방법과 Systems Manager 콘솔 및 AWS Command Line Interface(AWS CLI)에서 대상 및 속도 제어 기능을 사용하는 자동화를 실행하는 방법을 설명합니다.

## 대상 및 속도 제어를 사용하여 자동화 실행(콘솔)
<a name="scale-console"></a>

다음 절차에서는 Systems Manager 콘솔에서 대상 및 속도 제어를 사용하여 자동화를 실행하는 방법을 설명합니다.

**대상 및 속도 제어를 사용하여 자동화를 실행하려면**

1. AWS Systems Manager 콘솔[https://console.aws.amazon.com/systems-manager/](https://console.aws.amazon.com/systems-manager/)을 엽니다.

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

1. [**Automation 문서(Automation document)**] 목록에서 실행서를 선택합니다. **문서 카테고리** 창에서 옵션을 1개 이상 선택하여 SSM 문서를 목적에 따라 필터링합니다. 자신이 소유한 실행서를 보려면 [**내 소유(Owned by me)**] 탭을 선택합니다. 자신의 계정과 공유하고 있는 실행서를 보려면 [**나와 공유됨(Shared with me)**] 탭을 선택합니다. 모든 실행서를 보려면 [**모든 문서(All documents)**] 탭을 선택합니다.
**참고**  
실행서 이름을 선택하여 실행서에 대한 정보를 볼 수 있습니다.

1. **문서 세부 정보** 섹션에서 **문서 버전**이 실행할 버전으로 설정되었는지 확인합니다. 이 시스템에는 다음 버전 옵션이 포함되어 있습니다.
   + **런타임 시 기본 버전** - Automation 런북이 정기적으로 업데이트되며 새 기본 버전이 할당된 경우 이 옵션을 선택합니다.
   + **런타임 시 최신 버전** - Automation 런북이 정기적으로 업데이트되며 최근에 업데이트된 버전을 실행하려는 경우 이 옵션을 선택합니다.
   + **1(기본값)** - 문서의 최초 버전을 실행하려면 이 옵션을 선택합니다(기본값).

1. **다음**을 선택합니다.

1. **실행 모드** 섹션에서 **Rate Control(속도 제어)**을 선택합니다. 대상 및 속도 제어를 사용하려면 이 모드 또는 **다중 계정 및 리전**을 사용해야 합니다.

1. [**대상(Targets)**] 섹션에서 Automation을 실행할 AWS 리소스를 대상으로 지정할 방식을 선택합니다. 다음 옵션이 필요합니다.

   1. 파라미터를 선택하려면 **파라미터** 목록을 사용합니다. [**파라미터(Parameter)**] 목록의 항목은 이 절차의 시작 부분에서 선택한 Automation 실행서의 파라미터로 결정됩니다. 파라미터를 선택하여 자동화 워크플로에서 실행되는 리소스 유형을 정의할 수 있습니다.

   1. 리소스를 대상으로 지정하는 방식을 선택하려면 **대상** 목록을 사용합니다.

      1. 파라미터 값을 사용하여 리소스를 대상으로 지정하기로 선택한 경우 **입력 파라미터** 섹션에서 선택한 파라미터에 대한 값을 입력합니다.

      1. AWS Resource Groups을 사용하여 리소스를 대상으로 지정하기로 한 경우 **리소스 그룹** 목록에서 그룹의 이름을 선택합니다.

      1. 태그를 사용하여 리소스를 대상으로 지정하기로 한 경우 태그 키와 (선택 사항) 태그 값을 제공된 필드에 입력합니다. **추가**를 선택합니다.

      1. 현재 AWS 계정 및 AWS 리전의 전체 인스턴스에서 Automation 실행서를 실행하려면 [**전체 인스턴스(All instances)**]를 선택합니다.

1. **입력 파라미터** 섹션에서 필수 입력을 지정합니다. 필요에 따라 [**AutomationAssumeRole**] 목록에서 IAM 서비스 역할을 선택합니다.
**참고**  
**입력 파라미터** 섹션에서 일부 옵션은 선택할 필요가 없습니다. 그 이유는 태그 또는 리소스 그룹을 사용하여 리소스를 대상으로 지정했기 때문입니다. 예를 들어 `AWS-RestartEC2Instance` 실행서를 선택한 경우 [**입력 파라미터(Input parameters)**] 섹션에서 인스턴스 ID를 지정하거나 선택할 필요가 없습니다. Automation 실행 시, 지정된 태그 또는 리소스 그룹을 사용하여 다시 시작할 인스턴스를 찾을 수 있습니다.

1. 각 계정-리소스 페어 내에서 Automation을 실행할 수 있는 AWS 리소스 수를 제한하려면 **속도 제어** 섹션의 옵션을 사용합니다.

   **동시성** 섹션에서 옵션을 선택합니다.
   + **대상**을 선택하여 자동화 워크플로를 동시에 실행할 수 있는 대상 수(절대 개수)를 입력합니다.
   + **백분율**을 선택하여 자동화 워크플로를 동시에 실행할 수 있는 대상의 백분율을 입력합니다.

1. **오류 임계값** 섹션에서 옵션을 선택합니다.
   + **오류**를 선택하여 자동화를 통한 다른 리소스로의 워크플로 전송이 중지될 때까지 허용되는 오류 수(절대 개수)를 입력합니다.
   + **백분율**을 선택하여 자동화를 통한 다른 리소스로의 워크플로 전송이 중지될 때까지 허용되는 백분율을 입력합니다.

1. (선택 사항) 모니터링을 위해 자동화에 적용할 CloudWatch 경보를 선택합니다. CloudWatch 경보를 자동화에 연결하려면 자동화를 시작하는 IAM 보안 주체에 `iam:createServiceLinkedRole` 작업에 대한 권한이 있어야 합니다. CloudWatch 경보에 대한 자세한 내용은 [Amazon CloudWatch 경보 사용](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/AlarmThatSendsEmail.html)을 참조하세요. 경보가 활성화되면 자동화가 중지됩니다. AWS CloudTrail을 사용하면 추적에 API 호출이 표시됩니다.

1. **실행**을 선택합니다.

속도 제어 자동화로 시작된 자동화를 보려면 탐색 창에서 Automation을 선택한 다음 [**하위 자동화 표시(Show child automations)**]를 선택합니다.

자동화 실행이 완료되면 동일하거나 수정된 파라미터로 실행을 다시 실행할 수 있습니다. 자세한 내용은 [자동화 실행 재실행](automation-rerun-executions.md) 섹션을 참조하세요.

## 대상 및 속도 제어를 사용하여 자동화 실행(명령줄)
<a name="scale-cli"></a>

다음 절차에서는 AWS CLI(Linux 또는 Windows) 또는 AWS Tools for PowerShell에서 대상 및 속도 제어를 사용하여 자동화를 실행하는 방법을 설명합니다.

**대상 및 속도 제어를 사용하여 자동화를 실행하려면**

1. 아직 하지 않은 경우 AWS CLI 또는 AWS Tools for PowerShell을 설치하고 구성합니다.

   자세한 내용은 [최신 버전의 AWS CLI 설치 또는 업데이트](https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html) 및 [AWS Tools for PowerShell 설치](https://docs.aws.amazon.com/powershell/latest/userguide/pstools-getting-set-up.html)를 참조하세요.

1. 다음 명령을 실행하여 문서 목록을 확인합니다.

------
#### [ Linux & macOS ]

   ```
   aws ssm list-documents
   ```

------
#### [ Windows ]

   ```
   aws ssm list-documents
   ```

------
#### [ PowerShell ]

   ```
   Get-SSMDocumentList
   ```

------

   사용할 실행서의 이름을 기록해 둡니다.

1. 다음 명령을 실행하여 런북에 대한 세부 정보를 봅니다. *실행서 이름*을 세부 정보를 보려는 실행서 이름으로 바꿉니다. 또한 `--target-parameter-name` 옵션에 사용할 파라미터 이름(예: `InstanceId`)에 유의하세요. 이 파라미터는 자동화가 실행되는 리소스 유형을 결정합니다.

------
#### [ Linux & macOS ]

   ```
   aws ssm describe-document \
       --name runbook name
   ```

------
#### [ Windows ]

   ```
   aws ssm describe-document ^
       --name runbook name
   ```

------
#### [ PowerShell ]

   ```
   Get-SSMDocumentDescription `
       -Name runbook name
   ```

------

1. 실행할 대상 및 속도 제어 옵션을 사용하는 명령을 생성합니다. 각 *example resource placeholder*를 사용자의 정보로 바꿉니다.

   *태그를 사용하여 대상 지정*

------
#### [ Linux & macOS ]

   ```
   aws ssm start-automation-execution \
       --document-name runbook name \
       --targets Key=tag:key name,Values=value \
       --target-parameter-name parameter name \
       --parameters "input parameter name=input parameter value,input parameter 2 name=input parameter 2 value" \
       --max-concurrency 10 \
       --max-errors 25%
   ```

------
#### [ Windows ]

   ```
   aws ssm start-automation-execution ^
       --document-name runbook name ^
       --targets Key=tag:key name,Values=value ^
       --target-parameter-name parameter name ^
       --parameters "input parameter name=input parameter value,input parameter 2 name=input parameter 2 value" ^
       --max-concurrency 10 ^
       --max-errors 25%
   ```

------
#### [ PowerShell ]

   ```
   $Targets = New-Object Amazon.SimpleSystemsManagement.Model.Target
   $Targets.Key = "tag:key name"
   $Targets.Values = "value"
   
   Start-SSMAutomationExecution `
       DocumentName "runbook name" `
       -Targets $Targets `
       -TargetParameterName "parameter name" `
       -Parameter @{"input parameter name"="input parameter value";"input parameter 2 name"="input parameter 2 value"} `
       -MaxConcurrency "10" `
       -MaxError "25%"
   ```

------

   *파라미터 값을 사용하여 대상 지정*

------
#### [ Linux & macOS ]

   ```
   aws ssm start-automation-execution \
       --document-name runbook name \
       --targets Key=ParameterValues,Values=value,value 2,value 3 \
       --target-parameter-name parameter name \
       --parameters "input parameter name=input parameter value" \
       --max-concurrency 10 \
       --max-errors 25%
   ```

------
#### [ Windows ]

   ```
   aws ssm start-automation-execution ^
       --document-name runbook name ^
       --targets Key=ParameterValues,Values=value,value 2,value 3 ^
       --target-parameter-name parameter name ^
       --parameters "input parameter name=input parameter value" ^
       --max-concurrency 10 ^
       --max-errors 25%
   ```

------
#### [ PowerShell ]

   ```
   $Targets = New-Object Amazon.SimpleSystemsManagement.Model.Target
   $Targets.Key = "ParameterValues"
   $Targets.Values = "value","value 2","value 3"
   
   Start-SSMAutomationExecution `
       -DocumentName "runbook name" `
       -Targets $Targets `
       -TargetParameterName "parameter name" `
       -Parameter @{"input parameter name"="input parameter value"} `
       -MaxConcurrency "10" `
       -MaxError "25%"
   ```

------

   *AWS Resource Groups을 사용하여 대상 지정*

------
#### [ Linux & macOS ]

   ```
   aws ssm start-automation-execution \
       --document-name runbook name \
       --targets Key=ResourceGroup,Values=Resource group nname \
       --target-parameter-name parameter name \
       --parameters "input parameter name=input parameter value" \
       --max-concurrency 10 \
       --max-errors 25%
   ```

------
#### [ Windows ]

   ```
   aws ssm start-automation-execution ^
       --document-name runbook name ^
       --targets Key=ResourceGroup,Values=Resource group name ^
       --target-parameter-name parameter name ^
       --parameters "input parameter name=input parameter value" ^
       --max-concurrency 10 ^
       --max-errors 25%
   ```

------
#### [ PowerShell ]

   ```
   $Targets = New-Object Amazon.SimpleSystemsManagement.Model.Target
   $Targets.Key = "ResourceGroup"
   $Targets.Values = "Resource group name"
   
   Start-SSMAutomationExecution `
       -DocumentName "runbook name" `
       -Targets $Targets `
       -TargetParameterName "parameter name" `
       -Parameter @{"input parameter name"="input parameter value"} `
       -MaxConcurrency "10" `
       -MaxError "25%"
   ```

------

   **현재 AWS 계정 및 AWS 리전의 모든 Amazon EC2 인스턴스를 대상으로 지정

------
#### [ Linux & macOS ]

   ```
   aws ssm start-automation-execution \
       --document-name runbook name \
       --targets "Key=AWS::EC2::Instance,Values=*"  \
       --target-parameter-name instanceId \
       --parameters "input parameter name=input parameter value" \
       --max-concurrency 10 \
       --max-errors 25%
   ```

------
#### [ Windows ]

   ```
   aws ssm start-automation-execution ^
       --document-name runbook name ^
       --targets Key=AWS::EC2::Instance,Values=* ^
       --target-parameter-name instanceId ^
       --parameters "input parameter name=input parameter value" ^
       --max-concurrency 10 ^
       --max-errors 25%
   ```

------
#### [ PowerShell ]

   ```
   $Targets = New-Object Amazon.SimpleSystemsManagement.Model.Target
   $Targets.Key = "AWS::EC2::Instance"
   $Targets.Values = "*"
   
   Start-SSMAutomationExecution `
       -DocumentName "runbook name" `
       -Targets $Targets `
       -TargetParameterName "instanceId" `
       -Parameter @{"input parameter name"="input parameter value"} `
       -MaxConcurrency "10" `
       -MaxError "25%"
   ```

------

   이 명령으로 실행 ID가 반환됩니다. 클립보드에 이 ID를 복사합니다. 이 ID를 사용하여 자동화 상태를 확인할 수 있습니다.

------
#### [ Linux & macOS ]

   ```
   {
       "AutomationExecutionId": "a4a3c0e9-7efd-462a-8594-01234EXAMPLE"
   }
   ```

------
#### [ Windows ]

   ```
   {
       "AutomationExecutionId": "a4a3c0e9-7efd-462a-8594-01234EXAMPLE"
   }
   ```

------
#### [ PowerShell ]

   ```
   a4a3c0e9-7efd-462a-8594-01234EXAMPLE
   ```

------

1. 다음 명령을 실행하여 자동화를 봅니다. 각 *자동화 실행 ID*를 자신의 정보를 바꿉니다.

------
#### [ Linux & macOS ]

   ```
   aws ssm describe-automation-executions \
       --filter Key=ExecutionId,Values=automation execution ID
   ```

------
#### [ Windows ]

   ```
   aws ssm describe-automation-executions ^
       --filter Key=ExecutionId,Values=automation execution ID
   ```

------
#### [ PowerShell ]

   ```
   Get-SSMAutomationExecutionList | `
       Where {$_.AutomationExecutionId -eq "automation execution ID"}
   ```

------

1. 자동화 진행 상황에 대한 세부 정보를 보려면 다음 명령을 실행합니다. 각 *자동화 실행 ID*를 자신의 정보를 바꿉니다.

------
#### [ Linux & macOS ]

   ```
   aws ssm get-automation-execution \
       --automation-execution-id automation execution ID
   ```

------
#### [ Windows ]

   ```
   aws ssm get-automation-execution ^
       --automation-execution-id automation execution ID
   ```

------
#### [ PowerShell ]

   ```
   Get-SSMAutomationExecution `
       -AutomationExecutionId automation execution ID
   ```

------

   시스템은 다음과 같은 정보를 반환합니다.

------
#### [ Linux & macOS ]

   ```
   {
       "AutomationExecution": {
           "StepExecutionsTruncated": false,
           "AutomationExecutionStatus": "Success",
           "MaxConcurrency": "1",
           "Parameters": {},
           "MaxErrors": "1",
           "Outputs": {},
           "DocumentName": "AWS-StopEC2Instance",
           "AutomationExecutionId": "a4a3c0e9-7efd-462a-8594-01234EXAMPLE",
           "ResolvedTargets": {
               "ParameterValues": [
                   "i-02573cafcfEXAMPLE"
               ],
               "Truncated": false
           },
           "ExecutionEndTime": 1564681619.915,
           "Targets": [
               {
                   "Values": [
                       "DEV"
                   ],
                   "Key": "tag:ENV"
               }
           ],
           "DocumentVersion": "1",
           "ExecutionStartTime": 1564681576.09,
           "ExecutedBy": "arn:aws:sts::123456789012:assumed-role/Administrator/Admin",
           "StepExecutions": [
               {
                   "Inputs": {
                       "InstanceId": "i-02573cafcfEXAMPLE"
                   },
                   "Outputs": {},
                   "StepName": "i-02573cafcfEXAMPLE",
                   "ExecutionEndTime": 1564681619.093,
                   "StepExecutionId": "86c7b811-3896-4b78-b897-01234EXAMPLE",
                   "ExecutionStartTime": 1564681576.836,
                   "Action": "aws:executeAutomation",
                   "StepStatus": "Success"
               }
           ],
           "TargetParameterName": "InstanceId",
           "Mode": "Auto"
       }
   }
   ```

------
#### [ Windows ]

   ```
   {
       "AutomationExecution": {
           "StepExecutionsTruncated": false,
           "AutomationExecutionStatus": "Success",
           "MaxConcurrency": "1",
           "Parameters": {},
           "MaxErrors": "1",
           "Outputs": {},
           "DocumentName": "AWS-StopEC2Instance",
           "AutomationExecutionId": "a4a3c0e9-7efd-462a-8594-01234EXAMPLE",
           "ResolvedTargets": {
               "ParameterValues": [
                   "i-02573cafcfEXAMPLE"
               ],
               "Truncated": false
           },
           "ExecutionEndTime": 1564681619.915,
           "Targets": [
               {
                   "Values": [
                       "DEV"
                   ],
                   "Key": "tag:ENV"
               }
           ],
           "DocumentVersion": "1",
           "ExecutionStartTime": 1564681576.09,
           "ExecutedBy": "arn:aws:sts::123456789012:assumed-role/Administrator/Admin",
           "StepExecutions": [
               {
                   "Inputs": {
                       "InstanceId": "i-02573cafcfEXAMPLE"
                   },
                   "Outputs": {},
                   "StepName": "i-02573cafcfEXAMPLE",
                   "ExecutionEndTime": 1564681619.093,
                   "StepExecutionId": "86c7b811-3896-4b78-b897-01234EXAMPLE",
                   "ExecutionStartTime": 1564681576.836,
                   "Action": "aws:executeAutomation",
                   "StepStatus": "Success"
               }
           ],
           "TargetParameterName": "InstanceId",
           "Mode": "Auto"
       }
   }
   ```

------
#### [ PowerShell ]

   ```
   AutomationExecutionId       : a4a3c0e9-7efd-462a-8594-01234EXAMPLE
   AutomationExecutionStatus   : Success
   CurrentAction               : 
   CurrentStepName             : 
   DocumentName                : AWS-StopEC2Instance
   DocumentVersion             : 1
   ExecutedBy                  : arn:aws:sts::123456789012:assumed-role/Administrator/Admin
   ExecutionEndTime            : 8/1/2019 5:46:59 PM
   ExecutionStartTime          : 8/1/2019 5:46:16 PM
   FailureMessage              : 
   MaxConcurrency              : 1
   MaxErrors                   : 1
   Mode                        : Auto
   Outputs                     : {}
   Parameters                  : {}
   ParentAutomationExecutionId : 
   ProgressCounters            : 
   ResolvedTargets             : Amazon.SimpleSystemsManagement.Model.ResolvedTargets
   StepExecutions              : {i-02573cafcfEXAMPLE}
   StepExecutionsTruncated     : False
   Target                      : 
   TargetLocations             : {}
   TargetMaps                  : {}
   TargetParameterName         : InstanceId
   Targets                     : {tag:Name}
   ```

------
**참고**  
콘솔에서 자동화 상태를 모니터링할 수도 있습니다. **자동화 실행** 목록에서 방금 실행한 자동화를 선택한 후 **실행 단계** 탭을 선택합니다. 이 탭은 자동화 작업의 상태를 보여줍니다.

# 자동화를 위한 대상 매핑
<a name="running-automations-map-targets"></a>

자동화의 대상 리소스를 빠르게 정의하려면 `Targets` 파라미터를 사용합니다. 예를 들어 관리형 인스턴스를 다시 시작하는 자동화를 실행하려는 경우 콘솔에서 인스턴스 ID 수십 개를 직접 선택하거나 명령에 이러한 ID를 입력하는 대신에, `Targets` 파라미터를 사용하여 Amazon Elastic Compute Cloud(Amazon EC2) 태그를 지정함으로써 대상 인스턴스를 지정할 수 있습니다.

대상을 사용하는 자동화를 실행하는 경우 AWS Systems Manager는 각 대상에 대해 하위 자동화를 생성합니다. 예를 들어 태그를 지정하여 Amazon Elastic Block Store(Amazon EBS) 볼륨을 대상으로 지정하고 해당 태그가 100개의 Amazon EBS 볼륨으로 해석되면 Systems Manager는 100개의 하위 자동화를 생성합니다. 모든 하위 자동화가 최종 상태에 도달하면 상위 자동화가 완료된 것입니다.

**참고**  
런타임 시 지정하는 모든 `input parameters`(콘솔의 [**입력 파라미터(Input parameters)**] 섹션에서 또는 명령줄에서 `parameters` 옵션 사용)는 모든 하위 자동화에서 자동으로 처리됩니다.

태그, Resource Groups 및 파라미터 값을 사용하여 자동화를 위한 대상 리소스를 지정할 수 있습니다. 또한 `TargetMaps` 옵션을 사용하여 명령줄 또는 파일에서 여러 파라미터 값을 대상으로 지정할 수 있습니다. 다음 단원에서는 이러한 각각의 대상 지정 옵션에 대해 자세히 설명합니다.

## 태그를 대상으로 지정
<a name="target-tags"></a>

단일 태그를 자동화 대상으로 지정할 수 있습니다. Amazon Elastic Compute Cloud(Amazon EC2) 및 Amazon Relational Database Service(Amazon RDS) 인스턴스, Amazon Elastic Block Store(Amazon EBS) 볼륨 및 스냅샷, Resource Groups, Amazon Simple Storage Service(Amazon S3) 버킷을 비롯한 많은 AWS 리소스가 태그를 지원합니다. 태그를 대상으로 지정하여 AWS 리소스에서 자동화를 신속히 실행할 수 있습니다. 태그는 Operating\$1System:Linux 또는 Department:Finance와 같은 키-값 페어입니다. 리소스에 특정 이름을 할당할 경우 "Name"을 키로 사용하고 리소스 이름을 값으로 사용할 수도 있습니다.

자동화 대상으로 사용할 태그를 지정할 때 대상 파라미터도 지정합니다. 대상 파라미터에는 `TargetParameterName` 옵션이 사용됩니다. 대상 파라미터를 선택하면 자동화에서 실행되는 리소스 유형을 정의할 수 있습니다. 태그를 사용하여 지정하는 대상 파라미터는 실행서에 정의된 유효한 파라미터여야 합니다. 예를 들어 태그를 사용하여 수십 개 EC2 인스턴스를 대상으로 지정하려는 경우 `InstanceId` 대상 파라미터를 선택합니다. 이 파라미터를 선택하여 자동화에 대해 *인스턴스*를 리소스 유형으로 정의할 수 있습니다. 사용자 지정 런북을 생성할 때 **대상 유형**을 `/AWS::EC2::Instance`로 지정하여 인스턴스만 사용되도록 할 수 있습니다. 그렇지 않으면 태그가 동일한 모든 리소스가 대상이 됩니다. 태그를 사용하여 인스턴스를 대상으로 지정할 때 종료된 인스턴스가 포함될 수 있습니다.

다음 스크린샷에서는 `AWS-DetachEBSVolume`실행서를 사용합니다. 논리적 대상 파라미터는 `VolumeId`입니다.

![\[Systems Manager Automation의 대상으로 태그 사용\]](http://docs.aws.amazon.com/ko_kr/systems-manager/latest/userguide/images/automation-rate-control-tags-1-new.png)


`AWS-DetachEBSVolume` 실행서에는 `/AWS::EC2::Volume`으로 설정된 [**대상 유형(Target type)**]이라는 특수 속성도 포함되어 있습니다. 다시 말해서 태그-키 페어 `Finance:TestEnv`가 다양한 리소스 유형(예를 들면 EC2 인스턴스, Amazon EBS 볼륨, Amazon EBS 스냅샷)을 반환하는 경우 Amazon EBS 볼륨만 사용됩니다.

**중요**  
대상 파라미터 이름은 대/소문자를 구분합니다. AWS Command Line Interface(AWS CLI) 또는 AWS Tools for Windows PowerShell을 사용하여 자동화를 실행할 경우 실행서에 정의된 것과 똑같은 대상 파라미터 이름을 입력해야 합니다. 그렇지 않으면 `InvalidAutomationExecutionParametersException` 오류가 반환됩니다. [DescribeDocument](https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_DescribeDocument.html) API 작업을 사용하여 특정 실행서의 사용 가능한 대상 파라미터에 대한 정보를 볼 수 있습니다. 다음은 `AWS-DeleteSnapshot` 문서에 대한 정보를 제공하는 AWS CLI 명령의 예입니다.  

```
aws ssm describe-document \
    --name AWS-DeleteSnapshot
```

다음은 태그를 사용하여 대상 리소스를 지정하는 AWS CLI 명령의 예입니다.

**예 1: 키-값 페어를 통해 태그를 대상으로 지정하여 Amazon EC2 인스턴스 다시 시작**

이 예에서는 키가 *Department*이고 값이 *HumanResources*인 태그로 지정된 모든 Amazon EC2 인스턴스를 다시 시작합니다. 대상 파라미터에는 실행서의 *InstanceId* 파라미터가 사용됩니다. 이 예제에서는 자동화 서비스 역할을 사용(또는 *역할 수임*)함으로써 추가 파라미터를 사용하여 자동화를 실행합니다.

```
aws ssm start-automation-execution \
    --document-name AWS-RestartEC2Instance \
    --targets Key=tag:Department,Values=HumanResources \
    --target-parameter-name InstanceId \
    --parameters "AutomationAssumeRole=arn:aws:iam::111122223333:role/AutomationServiceRole"
```

**예 2: 키-값 페어를 통해 태그를 대상으로 지정하여 Amazon EBS 스냅샷 삭제**

다음 예에서는 `AWS-DeleteSnapshot` 실행서를 사용하여 키가 *Name*이고 값이 *January2018Backups*인 모든 스냅샷을 삭제합니다. 대상 파라미터에는 *VolumeId* 파라미터가 사용됩니다.

```
aws ssm start-automation-execution \
    --document-name AWS-DeleteSnapshot \
    --targets Key=tag:Name,Values=January2018Backups \
    --target-parameter-name VolumeId
```

## AWS Resource Groups을 대상으로 지정
<a name="target-resource-groups"></a>

단일 AWS 리소스 그룹을 자동화 대상으로 지정할 수 있습니다. Systems Manager는 대상 리소스 그룹의 모든 객체에 대한 하위 자동화를 생성합니다.

예를 들면 Resource Groups 중 하나가 PatchedAMIs라고 가정해 보겠습니다. 이 리소스 그룹에는 일상적으로 패치되는 25개 Windows Amazon Machine Images(AMIs)의 목록이 포함되어 있습니다. `AWS-CreateManagedWindowsInstance` 실행서를 사용하는 자동화를 실행하고 이 리소스 그룹을 대상으로 지정하는 경우 Systems Manager는 25개 AMIs 각각에 대해 하위 자동화를 생성합니다. 다시 말해서 이 자동화는 PatchedAMIs 리소스 그룹을 대상으로 지정하여 패치된 AMIs 목록에서 25개 인스턴스를 생성합니다. 모든 하위 자동화가 처리를 완료하거나 최종 상태에 도달하면 상위 자동화가 완료된 것입니다.

다음 AWS CLI 명령은 PatchAMIs 리소스 그룹 예제에 적용됩니다. 이 명령은 `--target-parameter-name` 옵션으로 *AmiId* 파라미터를 사용합니다. 이 명령은 각 AMI에서 생성할 인스턴스 유형을 정의하는 추가 파라미터를 포함하지 않습니다. `AWS-CreateManagedWindowsInstance` 실행서는 기본적으로 t2.medium 인스턴스 유형이므로 이 명령은 25개의 Windows Server용 t2.medium Amazon EC2 인스턴스를 생성합니다.

```
aws ssm start-automation-execution \
    --document-name AWS-CreateManagedWindowsInstance \
    --targets Key=ResourceGroup,Values=PatchedAMIs  \
    --target-parameter-name AmiId
```

다음 콘솔 예제에서는 t2-micro-instances라는 리소스 그룹이 사용됩니다.

![\[Systems Manager 자동화로 AWS 리소스 그룹 대상 지정\]](http://docs.aws.amazon.com/ko_kr/systems-manager/latest/userguide/images/automation-rate-control-resource-groups-new.png)


## 파라미터 값을 대상으로 지정
<a name="target-parameter-values"></a>

파라미터 값을 대상으로 지정할 수도 있습니다. `ParameterValues`를 키로 입력하고 나서 자동화를 실행할 특정 리소스 값을 입력합니다. 여러 값을 지정할 경우 Systems Manager는 지정된 각 값에 대해 하위 자동화를 실행합니다.

예를 들어 실행서에 **InstanceID** 파라미터가 포함되어 있다고 가정해 보겠습니다. Automation 실행 시 **InstanceID** 파라미터의 값을 대상으로 지정할 경우 Systems Manager는 지정한 각 인스턴스 ID 값마다 하위 자동화를 하나 실행합니다. 이 자동화가 각각의 지정된 인스턴스 실행을 완료하거나 실행에 실패하면 상위 자동화가 완료된 것입니다. 최대 50개 파라미터 값을 대상으로 지정할 수 있습니다.

다음 예에서는 `AWS-CreateImage` 실행서를 사용합니다. 지정된 대상 파라미터 이름은 *InstanceId*입니다. 이 키에는 *ParameterValues*가 사용됩니다. 두 Amazon EC2 인스턴스 ID가 값이 됩니다. 이 명령은 각 인스턴스마다 자동화를 하나 생성하며, 이 워크플로는 각 인스턴스에서 AMI를 생성합니다.

```
aws ssm start-automation-execution 
    --document-name AWS-CreateImage \
    --target-parameter-name InstanceId \
    --targets Key=ParameterValues,Values=i-02573cafcfEXAMPLE,i-0471e04240EXAMPLE
```

**참고**  
`AutomationAssumeRole`은 유효한 파라미터가 아닙니다. 파라미터 값을 대상으로 지정하는 자동화를 실행할 때 이 항목을 선택하지 않습니다.

### 파라미터 값 맵을 대상으로 지정
<a name="target-maps"></a>

`TargetMaps` 옵션은 `ParameterValues`를 대상으로 지정할 수 있는 기능을 확장합니다. 명령줄에서 `TargetMaps`를 사용하여 파라미터 값 배열을 입력할 수 있습니다. 명령줄에 최대 50개 파라미터 값을 지정할 수 있습니다. 50개가 넘는 파라미터 값을 지정하여 명령을 실행하려면 JSON 파일에 값을 입력할 수 있습니다. 그런 다음 명령줄에서 해당 파일을 호출할 수 있습니다.

**참고**  
`TargetMaps` 옵션은 콘솔에서 지원되지 않습니다.

명령에서 `TargetMaps` 옵션을 사용하면 다음 형식을 사용하여 여러 파라미터 값을 지정할 수 있습니다. 각 *example resource placeholder*를 사용자의 정보로 바꿉니다.

```
aws ssm start-automation-execution \
    --document-name runbook name \
    --target-maps “parameter=value, parameter 2=value, parameter 3=value”  “parameter 4=value, parameter 5=value, parameter 6=value”
```

`TargetMaps` 옵션에 대해 50개가 넘는 파라미터 값을 입력하려면 다음 JSON 형식을 사용하여 파일에 값을 지정합니다. JSON 파일을 사용하면 여러 파라미터 값 지정 시 가독성도 향상됩니다.

```
[

    {“parameter”: "value", “parameter 2”: "value", “parameter 3”: "value"},

    {“parameter 4”: "value", “parameter 5”: "value", "parameter 6": "value"}

]
```

파일을 .json 파일 확장명으로 저장합니다. 다음 명령을 사용하여 파일을 호출할 수 있습니다. 각 *example resource placeholder*를 사용자의 정보로 바꿉니다.

```
aws ssm start-automation-execution \
    --document-name runbook name \
    –-parameters input parameters \
    --target-maps path to file/file name.json
```

또한 버킷에서 데이터를 읽을 수 있는 권한이 있는 한 Amazon Simple Storage Service(Amazon S3) 버킷에서 파일을 다운로드할 수도 있습니다. 다음 명령 형식을 사용합니다. 각 *example resource placeholder*를 사용자의 정보로 바꿉니다.

```
aws ssm start-automation-execution \
    --document-name runbook name \
    --target-maps http://amzn-s3-demo-bucket.s3.amazonaws.com/file_name.json
```

다음은 `TargetMaps` 옵션을 이해하는 데 도움이 될 예제 시나리오입니다. 이 시나리오에서 사용자는 다양한 AMIs에서 다양한 유형의 Amazon EC2 인스턴스를 생성하려고 합니다. 이 태스크를 수행하기 위해 사용자는 AMI\$1Testing이라는 실행서를 생성합니다. 이 실행서는 `instanceType` 및 `imageId`라는 두 가지 입력 파라미터를 정의합니다.

```
{
  "description": "AMI Testing",
  "schemaVersion": "0.3",
  "assumeRole": "{{assumeRole}}",
  "parameters": {
    "assumeRole": {
      "type": "String",
      "description": "Role under which to run the automation",
      "default": ""
    },
    "instanceType": {
      "type": "String",
      "description": "Type of EC2 Instance to launch for this test"
    },
    "imageId": {
      "type": "String",
      "description": "Source AMI id from which to run instance"
    }
  },
  "mainSteps": [
    {
      "name": "runInstances",
      "action": "aws:runInstances",
      "maxAttempts": 1,
      "onFailure": "Abort",
      "inputs": {
        "ImageId": "{{imageId}}",
        "InstanceType": "{{instanceType}}",
        "MinInstanceCount": 1,
        "MaxInstanceCount": 1
      }
    }
  ],
  "outputs": [
    "runInstances.InstanceIds"
  ]
}
```

그런 다음 사용자는 `AMI_instance_types.json`이라는 파일에 다음과 같은 대상 파라미터 값을 지정합니다.

```
[
  {
    "instanceType" : ["t2.micro"],     
    "imageId" : ["ami-b70554c8"]     
  },
  {
    "instanceType" : ["t2.small"],     
    "imageId" : ["ami-b70554c8"]     
  },
  {
    "instanceType" : ["t2.medium"],     
    "imageId" : ["ami-cfe4b2b0"]     
  },
  {
    "instanceType" : ["t2.medium"],     
    "imageId" : ["ami-cfe4b2b0"]     
  },
  {
    "instanceType" : ["t2.medium"],     
    "imageId" : ["ami-cfe4b2b0"]     
  }
]
```

사용자는 다음 명령을 통해 이 자동화를 실행하고 `AMI_instance_types.json`에 정의된 5개 EC2 인스턴스를 생성할 수 있습니다.

```
aws ssm start-automation-execution \
    --document-name AMI_Testing \
    --target-parameter-name imageId \
    --target-maps file:///home/TestUser/workspace/runinstances/AMI_instance_types.json
```

## 모든 Amazon EC2 인스턴스를 대상으로 지정
<a name="target-all-instances"></a>

**대상** 목록에서 **모든 인스턴스**를 선택하여 현재 AWS 계정 및 AWS 리전의 모든 Amazon EC2 인스턴스에 대해 자동화를 실행할 수 있습니다. 예를 들어 AWS 계정 및 현재 AWS 리전의 모든 Amazon EC2 인스턴스를 다시 시작하려면 `AWS-RestartEC2Instance` 런북을 선택한 다음에 **대상** 목록에서 **모든 인스턴스**를 선택하면 됩니다.

![\[런북에 대한 모든 Amazon EC2 인스턴스를 대상으로 지정\]](http://docs.aws.amazon.com/ko_kr/systems-manager/latest/userguide/images/automation-rate-control-target-all-instances.png)


**모든 인스턴스(All instances)**를 선택하면 Systems Manager가 **인스턴스(Instance)** 필드를 별표(\$1)로 채우고 변경할 수 없게 됩니다(필드가 회색으로 표시됨). **입력 파라미터(Input parameters)** 필드의 **InstanceId** 필드도 사용할 수 없게 됩니다. 모든 인스턴스를 대상으로 선택하면 이러한 필드는 변경할 수 없게 됩니다.

# 대규모 자동화 제어
<a name="running-automations-scale-controls"></a>

동시성 값과 오류 임계값을 지정하여 AWS 리소스 플릿에서 자동화의 배포를 제어할 수도 있습니다. 동시성 및 오류 임계값을 통칭하여 *속도 제어*라고 합니다.

**동시성**  
동시성을 통해 자동화를 동시에 실행하도록 허용된 리소스 수를 지정할 수 있습니다. 동시성은 자동화 처리 시 리소스에 대한 영향이나 중단 시간을 제한하는 데 도움이 됩니다. 리소스의 절대 개수(예: 20개)를 지정하거나 대상 집합의 비율(예: 10%)을 지정할 수 있습니다.

대기 중인 시스템은 단일 리소스로 자동화를 전달하고 최초 호출이 완료될 때까지 기다렸다가 이 자동화를 다른 두 리소스로 전송합니다. 시스템은 동시성 값이 충족될 때까지 기하급수적으로 이 자동화를 더 많은 리소스로 전송합니다.

**오류 임계값**  
오류 임계값을 사용하여 AWS Systems Manager가 자동화를 다른 리소스로 전송하는 것을 중지하기 전에 실패할 수 있는 자동화 수를 지정합니다. 오류의 절대 개수(예: 10개)를 지정하거나 대상 집합의 비율(예: 10%)을 지정할 수 있습니다.

예를 들어 오류 수로 절대 개수 3을 지정할 경우 네 번째 오류가 수신되면 자동화 실행이 중지됩니다. 0을 지정하면 첫 번째 오류 결과가 반환된 후 추가 대상에서 자동화 실행이 중지됩니다.

예를 들어 자동화를 50개 인스턴스로 전송하고 오류 임계값을 10%로 설정하면 다섯 번째 오류가 수신되면 추가 인스턴스로의 명령 전송이 중지됩니다. 오류 임계값에 도달했을 때 자동화를 이미 실행 중인 호출은 완료될 수도 있지만, 이러한 자동화 중 일부가 실패할 수도 있습니다. 오류 수가 오류 임계값에 지정된 수보다 많지 않다고 확신하는 경우 [**동시성(Concurrency)**] 값을 1로 설정하면 자동화가 한 번에 하나씩 진행됩니다.

# 여러 AWS 리전 및 계정에서 자동화 실행
<a name="running-automations-multiple-accounts-regions"></a>

중앙 계정을 통해 여러 AWS 리전 및 AWS 계정 또는 AWS Organizations 조직 단위(OU)에서 AWS Systems Manager 자동화를 실행할 수 있습니다. Automation은 AWS Systems Manager의 도구입니다. 여러 리전 및 계정이나 OU에서 자동화를 실행하면 AWS 리소스를 관리하는 데 드는 시간이 절약될 뿐만 아니라 컴퓨팅 환경의 보안도 향상됩니다.

예를 들어, 자동화 런북을 사용하여 다음 작업을 수행할 수 있습니다.
+ 패치 및 보안 업데이트를 중앙에서 구현합니다.
+ VPC 구성 또는 Amazon S3 버킷 정책의 규정 준수 편차를 수정합니다.
+ Amazon Elastic Compute Cloud(Amazon EC2) 인스턴스와 같은 리소스를 대규모로 관리합니다.

다음 다이어그램은 중앙 계정 하나를 통해 여러 리전 및 계정에서 `AWS-RestartEC2Instances` 런북을 실행 중인 사용자 예를 보여줍니다. 이 자동화는 대상 리전 및 계정에서 지정된 태그를 사용하여 인스턴스를 찾아냅니다.

![\[여러 리전 및 여러 계정에서 실행 중인 Systems Manager 자동화를 보여주는 그림\]](http://docs.aws.amazon.com/ko_kr/systems-manager/latest/userguide/images/automation-multi-region-and-multi-account.png)


**Automation을 위한 중앙 계정 선택**  
OU에서 자동화를 실행하려면 중앙 계정에 OU의 모든 계정을 나열할 수 있는 권한이 있어야 합니다. 이는 위임된 관리자 계정 또는 조직의 관리 계정에서만 가능합니다. AWS Organizations 모범 사례를 따르고 위임된 관리자 계정을 사용하는 것이 좋습니다. AWS Organizations 모범 사례에 대한 자세한 내용은 AWS Organizations 사용 설명서의 [관리 계정의 모범 사례](https://docs.aws.amazon.com/organizations/latest/userguide/orgs_best-practices_mgmt-acct.html)를 참조하세요. Systems Manager에 대한 위임된 관리자 계정을 생성하려면 다음 예제와 같이 AWS CLI와 함께 `register-delegated-administrator` 명령을 사용할 수 있습니다.

```
aws organizations register-delegated-administrator \
    --account-id delegated admin account ID \
    --service-principal ssm.amazonaws.com
```

AWS Organizations에서 관리하지 않는 여러 계정에 걸쳐 자동화를 실행하려면 자동화 관리 전용 계정을 생성하는 것이 좋습니다. 전용 계정에서 모든 크로스 계정 자동화를 실행하면 IAM 권한 관리 및 문제 해결 작업이 간소화되고 운영과 관리를 구분할 수 있습니다. 이 접근 방식은 AWS Organizations를 사용하지만 OU가 아닌 개별 계정만 대상으로 하려는 경우에도 권장됩니다.

**자동화 실행 방식**  
여러 리전 및 계정 또는 OU에서의 자동화 실행은 다음과 같이 작동합니다.

1. Automation 중앙 계정으로 구성할 계정에 로그인합니다.

1. 이 주제의 [다중 리전 및 다중 계정 자동화를 위한 관리 계정 권한 설정](#setup-management-account-iam-roles) 절차에 따라 다음 IAM 역할을 생성합니다.
   + `AWS-SystemsManager-AutomationAdministrationRole` - 이 역할은 사용자에게 여러 계정 및 OU에서 자동화를 실행할 수 있는 권한을 부여합니다.
   + `AWS-SystemsManager-AutomationExecutionRole` - 이 역할은 사용자에게 대상 계정에서 자동화를 실행할 수 있는 권한을 부여합니다.

1. 자동화를 실행할 런북, 리전 및 계정 또는 OU를 선택합니다.
**참고**  
대상 OU에 원하는 계정이 포함되어 있는지 확인합니다. 사용자 지정 런북을 선택하는 경우 런북을 모든 대상 계정과 공유해야 합니다. 실행서 공유에 대한 자세한 내용은 [SSM 문서 공유](documents-ssm-sharing.md) 섹션을 참조하세요. 공유 런북 사용에 대한 자세한 내용은 [공유 SSM 문서 사용](documents-ssm-sharing.md#using-shared-documents) 섹션을 참조하세요.

1. 자동화를 실행합니다.

1. AWS Systems Manager 콘솔 또는 AWS CLI에서 [GetAutomationExecution](https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_GetAutomationExecution.html), [DescribeAutomationStepExecutions](https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_DescribeAutomationStepExecutions.html), 및 [DescribeAutomationExecutions](https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_DescribeAutomationExecutions.html) API 작업을 사용하여 자동화 진행 상황을 모니터링합니다. 기본 계정의 자동화 단계 출력은 하위 자동화의 `AutomationExecutionId`가 됩니다. 대상 계정에서 생성된 하위 자동화의 출력을 보려면 요청에 적절한 계정, 리전 및 `AutomationExecutionId`를 지정해야 합니다.

## 다중 리전 및 다중 계정 자동화를 위한 관리 계정 권한 설정
<a name="setup-management-account-iam-roles"></a>

다음 절차에 따라 AWS CloudFormation을 사용하여 Systems Manager Automation 다중 리전 및 다중 계정 실행에 필요한 IAM 역할을 생성합니다. 이 절차에서는 `AWS-SystemsManager-AutomationAdministrationRole` 역할을 생성하는 방법을 설명합니다. Automation 중앙 계정에서 이 역할을 생성하기만 하면 됩니다. 이 절차에서는 `AWS-SystemsManager-AutomationExecutionRole` 역할을 생성하는 방법도 설명합니다. 다중 리전 및 다중 계정 자동화를 실행할 대상으로 지정할 *모든* 계정에서 이 역할을 생성해야 합니다. 다중 리전 및 다중 계정 자동화를 실행하기 위해 대상으로 지정하려는 계정에서 `AWS-SystemsManager-AutomationExecutionRole` 역할을 생성하려면 CloudFormation StackSets를 사용하는 것이 좋습니다.

**CloudFormation을 사용하여 다중 리전 및 다중 계정 자동화에 필요한 IAM 관리 역할 생성**

1. [https://docs.aws.amazon.com/systems-manager/latest/userguide/samples/AWS-SystemsManager-AutomationAdministrationRole.zip](https://docs.aws.amazon.com/systems-manager/latest/userguide/samples/AWS-SystemsManager-AutomationAdministrationRole.zip)을 다운로드하고 압축을 해제합니다.

   -또는-

   AWS Organizations에서 계정을 관리하는 경우 [https://docs.aws.amazon.com/systems-manager/latest/userguide/samples/AWS-SystemsManager-AutomationAdministrationRole (org).zip](https://docs.aws.amazon.com/systems-manager/latest/userguide/samples/AWS-SystemsManager-AutomationAdministrationRole (org).zip).

   이러한 파일에는 `AWS-SystemsManager-AutomationAdministrationRole.yaml` 및 `AWS-SystemsManager-AutomationAdministrationRole (org).yaml` CloudFormation 템플릿 파일이 각각 포함되어 있습니다.

1. CloudFormation 콘솔([https://console.aws.amazon.com/cloudformation](https://console.aws.amazon.com/cloudformation/))을 엽니다.

1. **Create stack**(스택 생성)을 선택합니다.

1. **템플릿 지정(Specify template)** 섹션에서 **템플릿 업로드(Upload a template)**를 선택합니다.

1. **파일 선택**을 선택한 다음, 1단계에서의 선택에 따라 `AWS-SystemsManager-AutomationAdministrationRole.yaml` 또는 `AWS-SystemsManager-AutomationAdministrationRole (org).yaml` CloudFormation 템플릿 파일을 선택합니다.

1. **다음**을 선택합니다.

1. **스택 세부 정보 지정** 페이지의 **스택 이름** 필드에 이름을 입력합니다.

1. **Next**(다음)를 선택합니다.

1. **구성 스택 옵션** 페이지에서 사용할 옵션의 값을 입력합니다. **다음**을 선택합니다.

1. **검토** 페이지에서 아래로 스크롤하여 **CloudFormation이 IAM 리소스를 생성할 수 있다는 것을 알고 있음** 옵션을 선택합니다.

1. **스택 생성**을 선택합니다.

CloudFormation에 약 3분간 **CREATE\$1IN\$1PROGRESS** 상태가 표시됩니다. 상태가 **CREATE\$1COMPLETE**로 변경됩니다.

다중 리전 및 다중 계정 자동화를 실행할 대상으로 지정할 *모든* 계정에서 다음 절차를 반복해야 합니다.

**CloudFormation을 사용하여 다중 리전 및 다중 계정 자동화에 필요한 IAM 자동화 역할 생성**

1. [https://docs.aws.amazon.com/systems-manager/latest/userguide/samples/AWS-SystemsManager-AutomationExecutionRole.zip](https://docs.aws.amazon.com/systems-manager/latest/userguide/samples/AWS-SystemsManager-AutomationExecutionRole.zip)를 다운로드합니다.

   -또는

   AWS Organizations에서 계정을 관리하는 경우 [https://docs.aws.amazon.com/systems-manager/latest/userguide/samples/AWS-SystemsManager-AutomationExecutionRole (org).zip](https://docs.aws.amazon.com/systems-manager/latest/userguide/samples/AWS-SystemsManager-AutomationExecutionRole (org).zip).

   이러한 파일에는 `AWS-SystemsManager-AutomationExecutionRole.yaml` 및 `AWS-SystemsManager-AutomationExecutionRole (org).yaml`CloudFormation 템플릿 파일이 각각 포함되어 있습니다.

1. CloudFormation 콘솔([https://console.aws.amazon.com/cloudformation](https://console.aws.amazon.com/cloudformation/))을 엽니다.

1. **Create stack**(스택 생성)을 선택합니다.

1. **템플릿 지정(Specify template)** 섹션에서 **템플릿 업로드(Upload a template)**를 선택합니다.

1. **파일 선택**을 선택한 다음, 1단계에서의 선택에 따라 `AWS-SystemsManager-AutomationExecutionRole.yaml` 또는 `AWS-SystemsManager-AutomationExecutionRole (org).yaml` CloudFormation 템플릿 파일을 선택합니다.

1. **다음**을 선택합니다.

1. **스택 세부 정보 지정** 페이지의 **스택 이름** 필드에 이름을 입력합니다.

1. **Parameters**(파라미터) 섹션의 **AdminAccountId** 필드에 Automation 중앙 계정의 ID를 입력합니다.

1. AWS Organizations 환경에 대해 이 역할을 설정하는 경우 섹션에 **OrganizationID**라는 다른 필드가 있습니다. AWS 조직의 ID를 입력합니다.

1. **다음**을 선택합니다.

1. **구성 스택 옵션** 페이지에서 사용할 옵션의 값을 입력합니다. **다음**을 선택합니다.

1. **검토** 페이지에서 아래로 스크롤하여 **CloudFormation이 IAM 리소스를 생성할 수 있다는 것을 알고 있음** 옵션을 선택합니다.

1. **스택 생성**을 선택합니다.

CloudFormation에 약 3분간 **CREATE\$1IN\$1PROGRESS** 상태가 표시됩니다. 상태가 **CREATE\$1COMPLETE**로 변경됩니다.

## 여러 리전 및 계정에서 Automation 실행(콘솔)
<a name="multiple-console"></a>

다음 절차에서는 Systems Manager 콘솔을 사용하여 Automation 관리 계정을 통해 여러 리전 및 계정에서 자동화를 실행하는 방법을 설명합니다.

**시작하기 전 준비 사항**  
다음 절차를 완료하기 전에 다음 정보에 유의하세요.
+ 다중 리전 또는 다중 계정 자동화를 실행하는 데 사용하는 사용자 또는 역할은 `AWS-SystemsManager-AutomationAdministrationRole` 역할에 대한 `iam:PassRole` 권한이 있어야 합니다.
+ 자동화를 실행할 AWS 계정 ID 또는 OU.
+ 자동화를 실행할 위치인 [Systems Manager에서 지원하는 리전](https://docs.aws.amazon.com/general/latest/gr/ssm.html#ssm_region).
+ 자동화를 실행할 위치인, 태그 키 및 태그 값 또는 리소스 그룹 이름.

**여러 리전 및 계정에서 자동화를 실행하려면**

1. AWS Systems Manager 콘솔[https://console.aws.amazon.com/systems-manager/](https://console.aws.amazon.com/systems-manager/)을 엽니다.

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

1. [**Automation 문서(Automation document)**] 목록에서 실행서를 선택합니다. **문서 카테고리** 창에서 옵션을 1개 이상 선택하여 SSM 문서를 목적에 따라 필터링합니다. 자신이 소유한 실행서를 보려면 [**내 소유(Owned by me)**] 탭을 선택합니다. 자신의 계정과 공유하고 있는 실행서를 보려면 [**나와 공유됨(Shared with me)**] 탭을 선택합니다. 모든 실행서를 보려면 [**모든 문서(All documents)**] 탭을 선택합니다.
**참고**  
실행서 이름을 선택하여 실행서에 대한 정보를 볼 수 있습니다.

1. **문서 세부 정보** 섹션에서 **문서 버전**이 실행할 버전으로 설정되었는지 확인합니다. 이 시스템에는 다음 버전 옵션이 포함되어 있습니다.
   + **런타임 시 기본 버전** - Automation 런북이 정기적으로 업데이트되며 새 기본 버전이 할당된 경우 이 옵션을 선택합니다.
   + **런타임 시 최신 버전** - Automation 런북이 정기적으로 업데이트되며 최근에 업데이트된 버전을 실행하려는 경우 이 옵션을 선택합니다.
   + **1(기본값)** - 문서의 최초 버전을 실행하려면 이 옵션을 선택합니다(기본값).

1. **다음**을 선택합니다.

1. **자동화 문서 실행** 페이지에서 **다중 계정 및 리전**을 선택합니다.

1. **대상 계정 및 리전(Target accounts and Regions)** 섹션에서 **계정 및 조직 단위(OU)(Accounts and organizational(OU))** 필드를 사용하여 자동화를 실행할 서로 다른 AWS 계정 또는 AWS 조직 단위(OU)를 지정합니다. 쉼표를 사용하여 여러 계정 또는 OU를 구분합니다.

   1. (선택 사항) 지정된 OU 내에 모든 하위 조직 단위를 포함하려면 **하위 OU 포함** 확인란을 선택합니다.

   1. (선택 사항) **계정 및 조직 단위(OU) 제외** 필드에 위에 입력한 확장된 엔터티에서 제외하려는 계정 ID 및 OU ID의 쉼표로 구분된 목록을 입력합니다.

1. **리전** 목록을 사용하여 자동화를 실행할 하나 이상의 리전을 선택합니다.

1. [**다중 리전 및 계정 속도 제어(Multi-Region and account rate control)**] 옵션을 사용하여 자동화를 제한된 리전 수에서 실행 중인 제한된 계정 수로 제한합니다. 이러한 옵션은 자동화를 실행할 수 있는 AWS 리소스 수를 제한하지 않습니다.

   1. [**위치(계정-리전 페어) 동시성(Location (account-Region pair) concurrency)**] 섹션에서 옵션을 선택하여 여러 계정 및 리전에서 동시에 실행할 수 있는 자동화 수를 제한합니다. 예를 들어 4개 AWS 리전에 있는 5개 AWS 계정에서 자동화를 실행하도록 선택하는 경우 Systems Manager는 총 20개 계정-리전 페어에서 자동화를 실행합니다. 이 옵션을 사용하여 자동화가 2개 계정-리전 페어에서만 동시에 실행되도록 **2**와 같은 절대 개수를 지정할 수 있습니다. 또는 동시에 실행할 수 있는 계정-리전 페어 백분율을 지정할 수 있습니다. 예를 들어 20개 계정-리전 페어가 있을 때 20%를 지정할 경우 자동화가 최대 5개 계정-리전 페어에서 동시에 실행됩니다.
      + [**대상(targets)**]을 선택하여 자동화를 동시에 실행할 수 있는 계정-리전 페어 수(절대 개수)를 입력합니다.
      + [**백분율(percent)**]을 선택하여 자동화를 동시에 실행할 수 있는 총 계정-리전 페어 수의 백분율을 입력합니다.

   1. **Error threshold**(오류 임계값) 섹션에서 옵션을 선택합니다.
      + [**오류(errors)**]를 선택하여 Automation을 통한 다른 리소스로의 자동화 전송이 중지될 때까지 허용되는 오류 수(절대 개수)를 입력합니다.
      + [**퍼센트(percent)**]를 선택하여 Automation을 통한 다른 리소스로의 자동화 전송이 중지될 때까지 허용되는 백분율을 입력합니다.

1. [**대상(Targets)**] 섹션에서 Automation을 실행할 AWS 리소스를 대상으로 지정할 방식을 선택합니다. 다음 옵션이 필요합니다.

   1. 파라미터를 선택하려면 **파라미터** 목록을 사용합니다. [**파라미터(Parameter)**] 목록의 항목은 이 절차의 시작 부분에서 선택한 Automation 실행서의 파라미터로 결정됩니다. 파라미터를 선택하여 자동화 워크플로에서 실행되는 리소스 유형을 정의할 수 있습니다.

   1. 리소스를 대상으로 지정하는 방식을 선택하려면 **대상** 목록을 사용합니다.

      1. 파라미터 값을 사용하여 리소스를 대상으로 지정하기로 선택한 경우 **입력 파라미터** 섹션에서 선택한 파라미터에 대한 값을 입력합니다.

      1. AWS Resource Groups을 사용하여 리소스를 대상으로 지정하기로 한 경우 **리소스 그룹** 목록에서 그룹의 이름을 선택합니다.

      1. 태그를 사용하여 리소스를 대상으로 지정하기로 한 경우 태그 키와 (선택 사항) 태그 값을 제공된 필드에 입력합니다. **추가**를 선택합니다.

      1. 현재 AWS 계정 및 AWS 리전의 전체 인스턴스에서 Automation 실행서를 실행하려면 [**전체 인스턴스(All instances)**]를 선택합니다.

1. **입력 파라미터** 섹션에서 필수 입력을 지정합니다. **AutomationAssumeRole** 목록에서 `AWS-SystemsManager-AutomationAdministrationRole` IAM 서비스 역할을 선택합니다.
**참고**  
[**입력 파라미터(Input parameters)**] 섹션에서 일부 옵션은 선택할 필요가 없습니다. 그 이유는 태그 및 리소스 그룹을 사용하여 여러 리전 및 계정의 리소스를 대상으로 지정했기 때문입니다. 예를 들어 `AWS-RestartEC2Instance` 실행서를 선택한 경우 [**입력 파라미터(Input parameters)**] 섹션에서 인스턴스 ID를 지정하거나 선택할 필요가 없습니다. 자동화는 지정된 태그를 사용하여 다시 시작할 인스턴스를 정확히 찾아낼 수 있습니다.

1. (선택 사항) 모니터링을 위해 자동화에 적용할 CloudWatch 경보를 선택합니다. CloudWatch 경보를 자동화에 연결하려면 자동화를 시작하는 IAM 보안 주체에 `iam:createServiceLinkedRole` 작업에 대한 권한이 있어야 합니다. CloudWatch 경보에 대한 자세한 내용은 [Amazon CloudWatch 경보 사용](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/AlarmThatSendsEmail.html)을 참조하세요. 경보가 활성화되면 자동화가 취소되고 정의한 `OnCancel` 단계가 실행됩니다. AWS CloudTrail을 사용하면 추적에 API 호출이 표시됩니다.

1. 각 계정-리소스 페어 내에서 Automation을 실행할 수 있는 AWS 리소스 수를 제한하려면 **속도 제어** 섹션의 옵션을 사용합니다.

   **동시성** 섹션에서 옵션을 선택합니다.
   + **대상**을 선택하여 자동화 워크플로를 동시에 실행할 수 있는 대상 수(절대 개수)를 입력합니다.
   + **백분율**을 선택하여 자동화 워크플로를 동시에 실행할 수 있는 대상의 백분율을 입력합니다.

1. **오류 임계값** 섹션에서 옵션을 선택합니다.
   + **오류**를 선택하여 자동화를 통한 다른 리소스로의 워크플로 전송이 중지될 때까지 허용되는 오류 수(절대 개수)를 입력합니다.
   + **백분율**을 선택하여 자동화를 통한 다른 리소스로의 워크플로 전송이 중지될 때까지 허용되는 백분율을 입력합니다.

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

자동화 실행이 완료되면 동일하거나 수정된 파라미터로 실행을 다시 실행할 수 있습니다. 자세한 내용은 [자동화 실행 재실행](automation-rerun-executions.md) 섹션을 참조하세요.

## 여러 리전 및 계정에서 Automation 실행(명령줄)
<a name="multiple-cli"></a>

다음 절차에서는 AWS CLI(Linux 또는 Windows) 또는 AWS Tools for PowerShell을 사용하여 Automation 관리 계정을 통해 여러 리전 및 계정에서 자동화를 실행하는 방법을 설명합니다.

**시작하기 전 준비 사항**  
다음 절차를 완료하기 전에 다음 정보에 유의하세요.
+ 자동화를 실행할 AWS 계정 ID 또는 OU.
+ 자동화를 실행할 위치인 [Systems Manager에서 지원하는 리전](https://docs.aws.amazon.com/general/latest/gr/ssm.html#ssm_region).
+ 자동화를 실행할 위치인, 태그 키 및 태그 값 또는 리소스 그룹 이름.

**여러 리전 및 계정에서 자동화를 실행하려면**

1. 아직 하지 않은 경우 AWS CLI 또는 AWS Tools for PowerShell을 설치하고 구성합니다.

   자세한 내용은 [최신 버전의 AWS CLI 설치 또는 업데이트](https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html) 및 [AWS Tools for PowerShell 설치](https://docs.aws.amazon.com/powershell/latest/userguide/pstools-getting-set-up.html)를 참조하세요.

1. 다음 형식을 사용하여 여러 리전 및 계정에서 자동화를 실행하기 위한 명령을 생성합니다. 각 *example resource placeholder*를 사용자의 정보로 바꿉니다.

------
#### [ Linux & macOS ]

   ```
   aws ssm start-automation-execution \
           --document-name runbook name \
           --parameters AutomationAssumeRole=arn:aws:iam::management account ID:role/AWS-SystemsManager-AutomationAdministrationRole \
           --target-parameter-name parameter name \
           --targets Key=tag key,Values=value \
           --target-locations Accounts=account ID,account ID 2,Regions=Region,Region 2,ExecutionRoleName=AWS-SystemsManager-AutomationExecutionRole
   ```

------
#### [ Windows ]

   ```
   aws ssm start-automation-execution ^
           --document-name runbook name ^
           --parameters AutomationAssumeRole=arn:aws:iam::management account ID:role/AWS-SystemsManager-AutomationAdministrationRole ^
           --target-parameter-name parameter name ^
           --targets Key=tag key,Values=value ^
           --target-locations Accounts=account ID,account ID 2,Regions=Region,Region 2,ExecutionRoleName=AWS-SystemsManager-AutomationExecutionRole
   ```

------
#### [ PowerShell ]

   ```
   $Targets = New-Object Amazon.SimpleSystemsManagement.Model.Target
       $Targets.Key = "tag key"
       $Targets.Values = "value"
       
       Start-SSMAutomationExecution `
           -DocumentName "runbook name" `
           -Parameter @{
           "AutomationAssumeRole"="arn:aws:iam::management account ID:role/AWS-SystemsManager-AutomationAdministrationRole" } `
           -TargetParameterName "parameter name" `
           -Target $Targets `
           -TargetLocation @{
           "Accounts"="account ID","account ID 2";
           "Regions"="Region","Region 2";
           "ExecutionRoleName"="AWS-SystemsManager-AutomationExecutionRole" }
   ```

------

**예: 여러 리전 및 계정에서 자동화 실행**  
다음은 AWS CLI 및 PowerShell을 사용하여 단일 명령으로 여러 계정 및 리전에서 자동화를 실행하는 방법을 보여주는 예제입니다.

   **예제 1**: 이 예제는 전체 AWS Organizations 조직의 3개 리전에서 EC2 인스턴스를 다시 시작합니다. 이는 조직의 루트 ID를 대상으로 하고 하위 OU를 포함함으로써 달성됩니다.

------
#### [ Linux & macOS ]

   ```
   aws ssm start-automation-execution \
           --document-name "AWS-RestartEC2Instance" \
           --target-parameter-name InstanceId \
           --targets '[{"Key":"AWS::EC2::Instance","Values":["*"]}]' \
           --target-locations '[{
               "Accounts": ["r-example"],
               "IncludeChildOrganizationUnits": true,
               "Regions": ["us-east-1", "us-east-2", "us-west-2"]
           }]'
   ```

------
#### [ Windows ]

   ```
   aws ssm start-automation-execution \
           --document-name "AWS-RestartEC2Instance" ^
           --target-parameter-name InstanceId ^
           --targets '[{"Key":"AWS::EC2::Instance","Values":["*"]}]' ^
           --target-locations '[{
               "Accounts": ["r-example"],
               "IncludeChildOrganizationUnits": true,
               "Regions": ["us-east-1", "us-east-2", "us-west-2"]
           }]'
   ```

------
#### [ PowerShell ]

   ```
   Start-SSMAutomationExecution `
           -DocumentName "AWS-RestartEC2Instance" `
           -TargetParameterName "InstanceId" `
           -Targets '[{"Key":"AWS::EC2::Instance","Values":["*"]}]'
           -TargetLocation @{
               "Accounts"="r-example";
               "Regions"="us-east-1", "us-east-2", "us-west-2";
               "IncludeChildOrganizationUnits"=true}
   ```

------

   **예제 2**:이 예제는 서로 다른 계정 및 리전에서 특정 EC2 인스턴스를 다시 시작합니다.
**참고**  
`TargetLocationMaxConcurrency` 옵션은 AWS CLI 및 AWS SDK를 사용하여 제공됩니다.

------
#### [ Linux & macOS ]

   ```
   aws ssm start-automation-execution \
           --document-name "AWS-RestartEC2Instance" \
           --target-parameter-name InstanceId \
           --target-locations '[{
               "Accounts": ["123456789012"],
               "Targets": [{
                   "Key":"ParameterValues",
                   "Values":["i-02573cafcfEXAMPLE", "i-0471e04240EXAMPLE"]
               }],
               "TargetLocationMaxConcurrency": "100%",
               "Regions": ["us-east-1"]
           }, {
               "Accounts": ["987654321098"],
               "Targets": [{
                   "Key":"ParameterValues",
                   "Values":["i-07782c72faEXAMPLE"]
               }],
               "TargetLocationMaxConcurrency": "100%",
               "Regions": ["us-east-2"]
           }]'
   ```

------
#### [ Windows ]

   ```
   aws ssm start-automation-execution ^
           --document-name "AWS-RestartEC2Instance" ^
           --target-parameter-name InstanceId ^
           --target-locations '[{
               "Accounts": ["123456789012"],
               "Targets": [{
                   "Key":"ParameterValues",
                   "Values":["i-02573cafcfEXAMPLE", "i-0471e04240EXAMPLE"]
               }],
               "TargetLocationMaxConcurrency": "100%",
               "Regions": ["us-east-1"]
           }, {
               "Accounts": ["987654321098"],
               "Targets": [{
                   "Key":"ParameterValues",
                   "Values":["i-07782c72faEXAMPLE"]
               }],
               "TargetLocationMaxConcurrency": "100%",
               "Regions": ["us-east-2"]
           }]'
   ```

------
#### [ PowerShell ]

   ```
   Start-SSMAutomationExecution `
           -DocumentName "AWS-RestartEC2Instance" `
           -TargetParameterName "InstanceId" `
           -Targets '[{"Key":"AWS::EC2::Instance","Values":["*"]}]'
           -TargetLocation @({
               "Accounts"="123456789012",
               "Targets"= @{
                   "Key":"ParameterValues",
                   "Values":["i-02573cafcfEXAMPLE", "i-0471e04240EXAMPLE"]
               },
               "TargetLocationMaxConcurrency"="100%",
               "Regions"=["us-east-1"]
           }, {
               "Accounts"="987654321098",
               "Targets": @{
                   "Key":"ParameterValues",
                   "Values":["i-07782c72faEXAMPLE"]
               },
               "TargetLocationMaxConcurrency": "100%",
               "Regions"=["us-east-2"]
           })
   ```

------

   **예제 3**: 이 예제는 `--target-locations-url` 옵션을 사용하여 자동화를 실행해야 하는 여러 AWS 계정 및 리전을 지정하는 방법을 보여줍니다. 이 옵션의 값은 공개적으로 액세스할 수 있는 [미리 서명된 Amazon S3 URL](https://docs.aws.amazon.com/AmazonS3/latest/userguide/using-presigned-url.html)의 JSON 파일이어야 합니다.
**참고**  
`--target-locations-url`는 AWS CLI 및 AWS SDK를 사용하여 제공됩니다.

------
#### [ Linux & macOS ]

   ```
   aws ssm start-automation-execution \
       --document-name "MyCustomAutomationRunbook" \
       --target-locations-url "https://amzn-s3-demo-bucket.s3.amazonaws.com/target-locations.json"
   ```

------
#### [ Windows ]

   ```
   aws ssm start-automation-execution ^
       --document-name "MyCustomAutomationRunbook" ^
       --target-locations-url "https://amzn-s3-demo-bucket.s3.amazonaws.com/target-locations.json"
   ```

------
#### [ PowerShell ]

   ```
   Start-SSMAutomationExecution `
       -DocumentName "MyCustomAutomationRunbook" `
       -TargetLocationsUrl "https://amzn-s3-demo-bucket.s3.amazonaws.com/target-locations.json"
   ```

------

   JSON 파일의 샘플 콘텐츠:

   ```
   [
   { 
            "Accounts": [ "123456789012", "987654321098", "456789123012" ],
            "ExcludeAccounts": [ "111222333444", "999888444666" ],
            "ExecutionRoleName": "MyAutomationExecutionRole",
            "IncludeChildOrganizationUnits": true,
            "Regions": [ "us-east-1", "us-west-2", "ap-south-1", "ap-northeast-1" ],
            "Targets": ["Key": "AWS::EC2::Instance", "Values": ["i-2"]],
            "TargetLocationMaxConcurrency": "50%",
            "TargetLocationMaxErrors": "10",
            "TargetsMaxConcurrency": "20",
            "TargetsMaxErrors": "12"
    }
   ]
   ```

   **예제 4**: 이 예제에서는 `123456789012` 및 `987654321098` 계정의 EC2 인스턴스를 다시 시작하며 이는 `us-east-2` 및 `us-west-1` 리전에 있습니다. 인스턴스에 태그 키 페어 값 `Env-PROD`가 태그로 지정되어야 합니다.

------
#### [ Linux & macOS ]

   ```
   aws ssm start-automation-execution \
           --document-name AWS-RestartEC2Instance \
           --parameters AutomationAssumeRole=arn:aws:iam::123456789012:role/AWS-SystemsManager-AutomationAdministrationRole \
           --target-parameter-name InstanceId \
           --targets Key=tag:Env,Values=PROD \
           --target-locations Accounts=123456789012,987654321098,Regions=us-east-2,us-west-1,ExecutionRoleName=AWS-SystemsManager-AutomationExecutionRole
   ```

------
#### [ Windows ]

   ```
   aws ssm start-automation-execution ^
           --document-name AWS-RestartEC2Instance ^
           --parameters AutomationAssumeRole=arn:aws:iam::123456789012:role/AWS-SystemsManager-AutomationAdministrationRole ^
           --target-parameter-name InstanceId ^
           --targets Key=tag:Env,Values=PROD ^
           --target-locations Accounts=123456789012,987654321098,Regions=us-east-2,us-west-1,ExecutionRoleName=AWS-SystemsManager-AutomationExecutionRole
   ```

------
#### [ PowerShell ]

   ```
   $Targets = New-Object Amazon.SimpleSystemsManagement.Model.Target
       $Targets.Key = "tag:Env"
       $Targets.Values = "PROD"
       
       Start-SSMAutomationExecution `
           -DocumentName "AWS-RestartEC2Instance" `
           -Parameter @{
           "AutomationAssumeRole"="arn:aws:iam::123456789012:role/AWS-SystemsManager-AutomationAdministrationRole" } `
           -TargetParameterName "InstanceId" `
           -Target $Targets `
           -TargetLocation @{
           "Accounts"="123456789012","987654321098";
           "Regions"="us-east-2","us-west-1";
           "ExecutionRoleName"="AWS-SystemsManager-AutomationExecutionRole" }
   ```

------

   **예제 5**: 이 예제에서는 `123456789012` 및 `987654321098` 계정의 EC2 인스턴스를 다시 시작하며 이는 `eu-central-1` 리전에 있습니다. 인스턴스가 `prod-instances` AWS 리소스 그룹의 멤버여야 합니다.

------
#### [ Linux & macOS ]

   ```
   aws ssm start-automation-execution \
           --document-name AWS-RestartEC2Instance \
           --parameters AutomationAssumeRole=arn:aws:iam::123456789012:role/AWS-SystemsManager-AutomationAdministrationRole \
           --target-parameter-name InstanceId \
           --targets Key=ResourceGroup,Values=prod-instances \
           --target-locations Accounts=123456789012,987654321098,Regions=eu-central-1,ExecutionRoleName=AWS-SystemsManager-AutomationExecutionRole
   ```

------
#### [ Windows ]

   ```
   aws ssm start-automation-execution ^
           --document-name AWS-RestartEC2Instance ^
           --parameters AutomationAssumeRole=arn:aws:iam::123456789012:role/AWS-SystemsManager-AutomationAdministrationRole ^
           --target-parameter-name InstanceId ^
           --targets Key=ResourceGroup,Values=prod-instances ^
           --target-locations Accounts=123456789012,987654321098,Regions=eu-central-1,ExecutionRoleName=AWS-SystemsManager-AutomationExecutionRole
   ```

------
#### [ PowerShell ]

   ```
   $Targets = New-Object Amazon.SimpleSystemsManagement.Model.Target
       $Targets.Key = "ResourceGroup"
       $Targets.Values = "prod-instances"
       
       Start-SSMAutomationExecution `
           -DocumentName "AWS-RestartEC2Instance" `
           -Parameter @{
           "AutomationAssumeRole"="arn:aws:iam::123456789012:role/AWS-SystemsManager-AutomationAdministrationRole" } `
           -TargetParameterName "InstanceId" `
           -Target $Targets `
           -TargetLocation @{
           "Accounts"="123456789012","987654321098";
           "Regions"="eu-central-1";
           "ExecutionRoleName"="AWS-SystemsManager-AutomationExecutionRole" }
   ```

------

   **예제 6**: 이 예제에서는 `ou-1a2b3c-4d5e6c` AWS 조직 단위(OU)에서 EC2 인스턴스를 다시 시작합니다. 이들 인스턴스는 `us-west-1` 및 `us-west-2` 리전에 위치합니다. 인스턴스가 `WebServices` AWS 리소스 그룹의 멤버여야 합니다.

------
#### [ Linux & macOS ]

   ```
   aws ssm start-automation-execution \
           --document-name AWS-RestartEC2Instance \
           --parameters AutomationAssumeRole=arn:aws:iam::123456789012:role/AWS-SystemsManager-AutomationAdministrationRole \
           --target-parameter-name InstanceId \
           --targets Key=ResourceGroup,Values=WebServices \
           --target-locations Accounts=ou-1a2b3c-4d5e6c,Regions=us-west-1,us-west-2,ExecutionRoleName=AWS-SystemsManager-AutomationExecutionRole
   ```

------
#### [ Windows ]

   ```
   aws ssm start-automation-execution ^
           --document-name AWS-RestartEC2Instance ^
           --parameters AutomationAssumeRole=arn:aws:iam::123456789012:role/AWS-SystemsManager-AutomationAdministrationRole ^
           --target-parameter-name InstanceId ^
           --targets Key=ResourceGroup,Values=WebServices ^
           --target-locations Accounts=ou-1a2b3c-4d5e6c,Regions=us-west-1,us-west-2,ExecutionRoleName=AWS-SystemsManager-AutomationExecutionRole
   ```

------
#### [ PowerShell ]

   ```
   $Targets = New-Object Amazon.SimpleSystemsManagement.Model.Target
       $Targets.Key = "ResourceGroup"
       $Targets.Values = "WebServices"
       
       Start-SSMAutomationExecution `
           -DocumentName "AWS-RestartEC2Instance" `
           -Parameter @{
           "AutomationAssumeRole"="arn:aws:iam::123456789012:role/AWS-SystemsManager-AutomationAdministrationRole" } `
           -TargetParameterName "InstanceId" `
           -Target $Targets `
           -TargetLocation @{
           "Accounts"="ou-1a2b3c-4d5e6c";
           "Regions"="us-west-1";
           "ExecutionRoleName"="AWS-SystemsManager-AutomationExecutionRole" }
   ```

------

   시스템은 다음과 유사한 정보를 반환합니다.

------
#### [ Linux & macOS ]

   ```
   {
           "AutomationExecutionId": "4f7ca192-7e9a-40fe-9192-5cb15EXAMPLE"
       }
   ```

------
#### [ Windows ]

   ```
   {
           "AutomationExecutionId": "4f7ca192-7e9a-40fe-9192-5cb15EXAMPLE"
       }
   ```

------
#### [ PowerShell ]

   ```
   4f7ca192-7e9a-40fe-9192-5cb15EXAMPLE
   ```

------

1. 다음 명령을 실행하여 자동화에 대한 세부 정보를 봅니다. *자동화 실행 ID*를 자신의 정보를 바꿉니다.

------
#### [ Linux & macOS ]

   ```
   aws ssm describe-automation-executions \
           --filters Key=ExecutionId,Values=automation execution ID
   ```

------
#### [ Windows ]

   ```
   aws ssm describe-automation-executions ^
           --filters Key=ExecutionId,Values=automation execution ID
   ```

------
#### [ PowerShell ]

   ```
   Get-SSMAutomationExecutionList | `
           Where {$_.AutomationExecutionId -eq "automation execution ID"}
   ```

------

1. 다음 명령을 실행하여 자동화 진행 상황에 대한 세부 정보를 봅니다.

------
#### [ Linux & macOS ]

   ```
   aws ssm get-automation-execution \
           --automation-execution-id 4f7ca192-7e9a-40fe-9192-5cb15EXAMPLE
   ```

------
#### [ Windows ]

   ```
   aws ssm get-automation-execution ^
           --automation-execution-id 4f7ca192-7e9a-40fe-9192-5cb15EXAMPLE
   ```

------
#### [ PowerShell ]

   ```
   Get-SSMAutomationExecution `
           -AutomationExecutionId a4a3c0e9-7efd-462a-8594-01234EXAMPLE
   ```

------
**참고**  
콘솔에서 자동화 상태를 모니터링할 수도 있습니다. **자동화 실행** 목록에서 방금 실행한 자동화를 선택한 후 **실행 단계** 탭을 선택합니다. 이 탭은 자동화 작업의 상태를 보여줍니다.

**추가 정보**  
[AWS Systems Manager 자동화를 사용하여 중앙 집중식 다중 계정 및 다중 리전 패치 적용](https://aws.amazon.com/blogs/mt/centralized-multi-account-and-multi-region-patching-with-aws-systems-manager-automation/)

# EventBridge 이벤트를 기반으로 자동화 실행
<a name="running-automations-event-bridge"></a>

실행서를 Amazon EventBridge 이벤트의 대상으로 지정하여 자동화를 시작할 수 있습니다. 일정에 따라 또는 특정 AWS 시스템 이벤트가 발생할 때 자동화를 시작할 수 있습니다. 예를 들어 인스턴스가 시작될 때 인스턴스에서 소프트웨어를 설치하는 *BootStrapInstances*라는 실행서를 생성한다고 가정합니다. *BootStrapInstances* 실행서와 해당 자동화를 EventBridge 이벤트의 대상으로 지정하려면 먼저 새 EventBridge 규칙을 생성합니다. (예제 규칙: **서비스 이름**: EC2, **이벤트 유형**: EC2 인스턴스 상태 변경 알림, **특정 상태**: 실행 중, **모든 인스턴스**.) 그리고 다음 절차에 따라 EventBridge 콘솔 및 AWS Command Line Interface(AWS CLI)를 사용하여 *BootStrapInstances* 실행서를 이벤트 대상으로 지정합니다. 새 인스턴스가 시작되면 시스템에서 자동화를 실행하고 소프트웨어를 설치합니다.

실행서 생성에 대한 자세한 내용은 [사용자 런북 생성](automation-documents.md) 섹션을 참조하세요.

## 실행서를 사용하는 EventBridge 이벤트 생성(콘솔)
<a name="automation-cwe-target-console"></a>

다음 절차에 따라 실행서를 EventBridge 이벤트 대상으로 구성합니다.

**실행서를 EventBridge 이벤트 규칙의 대상으로 구성하려면**

1. [https://console.aws.amazon.com/events/](https://console.aws.amazon.com/events/)에서 Amazon EventBridge 콘솔을 엽니다.

1. 탐색 창에서 **규칙**을 선택합니다.

1. **규칙 생성**을 선택합니다.

1. 규칙에 대해 이름과 설명을 입력하세요.

   규칙은 동일한 리전과 동일한 이벤트 버스의 다른 규칙과 동일한 이름을 가질 수 없습니다.

1. **이벤트 버스**에서 이 규칙과 연결할 이벤트 버스를 선택합니다. 이 규칙이 자신의 AWS 계정에서 오는 일치하는 이벤트에 응답하도록 하려면 **default**(기본)를 선택합니다. 계정의 AWS 서비스이(가) 이벤트를 출력하면 항상 계정의 기본 이벤트 버스로 이동합니다.

1. 규칙이 트리거되는 방식을 선택합니다.    
[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/systems-manager/latest/userguide/running-automations-event-bridge.html)

1. **다음**을 선택합니다.

1. **대상 유형**에서 **AWS서비스**를 선택합니다.

1. **Target**(대상)에서 **Systems Manager Automation**을 선택합니다.

1. [**문서(Document)**]에서 대상이 호출될 때 사용할 실행서를 선택합니다.

1. **Configure automation parameter(s)**(자동화 파라미터 구성) 섹션에서 기본 파라미터 값을 유지하거나(사용 가능한 경우) 값을 직접 입력할 수 있습니다.
**참고**  
대상을 생성하려면 각 필수 파라미터에 대한 값을 지정해야 합니다. 그렇지 않으면 시스템에서 규칙이 생성되지만 실행되지 않습니다.

1. 여러 대상 유형에 대해 EventBridge에서는 대상에 이벤트를 보낼 권한이 필요합니다. 이 경우 EventBridge는 규칙 실행에 필요한 IAM 역할을 생성할 수 있습니다. 다음 중 하나를 수행하세요.
   + IAM 역할을 자동으로 생성하려면 **이 특정 리소스에 대해 새 역할 생성**을 선택합니다.
   + 이전에 생성한 IAM 역할을 사용하려면 **기존 역할 사용(Use existing role)**을 선택하고 드롭다운에서 기존 역할을 선택합니다. EventBridge를 포함하도록 IAM 역할에 대한 신뢰 정책을 업데이트해야 할 수도 있습니다. 다음은 예제입니다.

------
#### [ JSON ]

****  

   ```
   {
       "Version":"2012-10-17",		 	 	 
       "Statement": [
           {
               "Sid": "",
               "Effect": "Allow",
               "Principal": {
                   "Service": [
                       "events.amazonaws.com",
                       "ssm.amazonaws.com"
                   ]
               },
               "Action": "sts:AssumeRole"
           }
       ]
   }
   ```

------

1. **다음**을 선택합니다.

1. (선택 사항)규칙에 대해 하나 이상의 태그를 입력하세요. 자세한 내용은 *Amazon EventBridge User Guide*의 [Tagging Your Amazon EventBridge Resources](https://docs.aws.amazon.com/eventbridge/latest/userguide/eventbridge-tagging.html)를 참조하세요.

1. **다음**을 선택합니다.

1. 규칙의 세부 정보를 검토하고 **규칙 생성**을 선택합니다.

## 실행서를 사용하는 EventBridge 이벤트 생성(명령줄)
<a name="automation-cwe-target-commandline"></a>

다음 절차에서는 AWS CLI(Linux 또는 Windows) 또는 AWS Tools for PowerShell을 사용하여 EventBridge 이벤트 규칙을 생성하고 실행서를 대상으로 구성하는 방법을 설명합니다.

**실행서를 EventBridge 이벤트 규칙의 대상으로 구성하려면**

1. 아직 하지 않은 경우 AWS CLI 또는 AWS Tools for PowerShell을 설치하고 구성합니다.

   자세한 내용은 [최신 버전의 AWS CLI 설치 또는 업데이트](https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html) 및 [AWS Tools for PowerShell 설치](https://docs.aws.amazon.com/powershell/latest/userguide/pstools-getting-set-up.html)를 참조하세요.

1. 새 EventBridge 이벤트 규칙을 지정하기 위한 명령을 생성합니다. 각 *example resource placeholder*를 사용자의 정보로 바꿉니다.

   *일정을 기반으로 트리거*

------
#### [ Linux & macOS ]

   ```
   aws events put-rule \
   --name "rule name" \
   --schedule-expression "cron or rate expression"
   ```

------
#### [ Windows ]

   ```
   aws events put-rule ^
   --name "rule name" ^
   --schedule-expression "cron or rate expression"
   ```

------
#### [ PowerShell ]

   ```
   Write-CWERule `
   -Name "rule name" `
   -ScheduleExpression "cron or rate expression"
   ```

------

   다음 예에서는 매일 오전 9:00(UTC)에 트리거하는 EventBridge 이벤트 규칙을 생성합니다.

------
#### [ Linux & macOS ]

   ```
   aws events put-rule \
   --name "DailyAutomationRule" \
   --schedule-expression "cron(0 9 * * ? *)"
   ```

------
#### [ Windows ]

   ```
   aws events put-rule ^
   --name "DailyAutomationRule" ^
   --schedule-expression "cron(0 9 * * ? *)"
   ```

------
#### [ PowerShell ]

   ```
   Write-CWERule `
   -Name "DailyAutomationRule" `
   -ScheduleExpression "cron(0 9 * * ? *)"
   ```

------

   *이벤트를 기반으로 트리거*

------
#### [ Linux & macOS ]

   ```
   aws events put-rule \
   --name "rule name" \
   --event-pattern "{\"source\":[\"aws.service\"],\"detail-type\":[\"service event detail type\"]}"
   ```

------
#### [ Windows ]

   ```
   aws events put-rule ^
   --name "rule name" ^
   --event-pattern "{\"source\":[\"aws.service\"],\"detail-type\":[\"service event detail type\"]}"
   ```

------
#### [ PowerShell ]

   ```
   Write-CWERule `
   -Name "rule name" `
   -EventPattern '{"source":["aws.service"],"detail-type":["service event detail type"]}'
   ```

------

   다음 예에서는 리전의 EC2 인스턴스가 상태가 변경될 때 시작되는 EventBridge 이벤트 규칙을 생성합니다.

------
#### [ Linux & macOS ]

   ```
   aws events put-rule \
   --name "EC2InstanceStateChanges" \
   --event-pattern "{\"source\":[\"aws.ec2\"],\"detail-type\":[\"EC2 Instance State-change Notification\"]}"
   ```

------
#### [ Windows ]

   ```
   aws events put-rule ^
   --name "EC2InstanceStateChanges" ^
   --event-pattern "{\"source\":[\"aws.ec2\"],\"detail-type\":[\"EC2 Instance State-change Notification\"]}"
   ```

------
#### [ PowerShell ]

   ```
   Write-CWERule `
   -Name "EC2InstanceStateChanges" `
   -EventPattern '{"source":["aws.ec2"],"detail-type":["EC2 Instance State-change Notification"]}'
   ```

------

   이 명령은 다음과 비슷한 새 EventBridge 규칙의 세부 정보를 반환합니다.

------
#### [ Linux & macOS ]

   ```
   {
   "RuleArn": "arn:aws:events:us-east-1:123456789012:rule/automationrule"
   }
   ```

------
#### [ Windows ]

   ```
   {
   "RuleArn": "arn:aws:events:us-east-1:123456789012:rule/automationrule"
   }
   ```

------
#### [ PowerShell ]

   ```
   arn:aws:events:us-east-1:123456789012:rule/EC2InstanceStateChanges
   ```

------

1. 실행서를 2단계에서 생성한 EventBridge 이벤트 규칙의 대상으로 지정하기 위한 명령을 생성합니다. 각 *example resource placeholder*를 사용자의 정보로 바꿉니다.

------
#### [ Linux & macOS ]

   ```
   aws events put-targets \
   --rule rule name \
   --targets '{"Arn": " arn:aws:ssm:region:account ID:automation-definition/runbook name","Input":"{\"Message\":[\"{\\\"Key\\\":\\\"key name\\\",\\\"Values\\\":[\\\"value\\\"]}\"]}","Id": "target ID","RoleArn": "arn:aws:iam::123456789012:role/service-role/EventBridge service role"}'
   ```

------
#### [ Windows ]

   ```
   aws events put-targets ^
   --rule rule name ^
   --targets '{"Arn": "arn:aws:ssm:region:account ID:automation-definition/runbook name","Input":"{\"Message\":[\"{\\\"Key\\\":\\\"key name\\\",\\\"Values\\\":[\\\"value\\\"]}\"]}","Id": "target ID","RoleArn": "arn:aws:iam::123456789012:role/service-role/EventBridge service role"}'
   ```

------
#### [ PowerShell ]

   ```
   $Target = New-Object Amazon.CloudWatchEvents.Model.Target
   $Target.Id = "target ID"
   $Target.Arn = "arn:aws:ssm:region:account ID:automation-definition/runbook name"
   $Target.RoleArn = "arn:aws:iam::123456789012:role/service-role/EventBridge service role"
   $Target.Input = '{"input parameter":["value"],"AutomationAssumeRole":["arn:aws:iam::123456789012:role/AutomationServiceRole"]}'
   
   Write-CWETarget `
   -Rule "rule name" `
   -Target $Target
   ```

------

   다음 예에서는 실행서 `AWS-StartEC2Instance`를 사용하여 지정된 인스턴스 ID를 시작하는 EventBridge 이벤트 대상을 생성합니다.

------
#### [ Linux & macOS ]

   ```
   aws events put-targets \
   --rule DailyAutomationRule \
   --targets '{"Arn": "arn:aws:ssm:region:*:automation-definition/AWS-StartEC2Instance","Input":"{\"InstanceId\":[\"i-02573cafcfEXAMPLE\"],\"AutomationAssumeRole\":[\"arn:aws:iam::123456789012:role/AutomationServiceRole\"]}","Id": "Target1","RoleArn": "arn:aws:iam::123456789012:role/service-role/AWS_Events_Invoke_Start_Automation_Execution_1213609520"}'
   ```

------
#### [ Windows ]

   ```
   aws events put-targets ^
   --rule DailyAutomationRule ^
   --targets '{"Arn": "arn:aws:ssm:region:*:automation-definition/AWS-StartEC2Instance","Input":"{\"InstanceId\":[\"i-02573cafcfEXAMPLE\"],\"AutomationAssumeRole\":[\"arn:aws:iam::123456789012:role/AutomationServiceRole\"]}","Id": "Target1","RoleArn": "arn:aws:iam::123456789012:role/service-role/AWS_Events_Invoke_Start_Automation_Execution_1213609520"}'
   ```

------
#### [ PowerShell ]

   ```
   $Target = New-Object Amazon.CloudWatchEvents.Model.Target
   $Target.Id = "Target1"
   $Target.Arn = "arn:aws:ssm:region:*:automation-definition/AWS-StartEC2Instance"
   $Target.RoleArn = "arn:aws:iam::123456789012:role/service-role/AWS_Events_Invoke_Start_Automation_Execution_1213609520"
   $Target.Input = '{"InstanceId":["i-02573cafcfEXAMPLE"],"AutomationAssumeRole":["arn:aws:iam::123456789012:role/AutomationServiceRole"]}'
   
   Write-CWETarget `
   -Rule "DailyAutomationRule" `
   -Target $Target
   ```

------

   시스템은 다음과 같은 정보를 반환합니다.

------
#### [ Linux & macOS ]

   ```
   {
   "FailedEntries": [],
   "FailedEntryCount": 0
   }
   ```

------
#### [ Windows ]

   ```
   {
   "FailedEntries": [],
   "FailedEntryCount": 0
   }
   ```

------
#### [ PowerShell ]

   PowerShell에 대해 명령이 성공해도 결과는 없습니다.

------

# 단계별 자동화 실행
<a name="automation-working-executing-manually"></a>

다음 절차에서는 수동 실행 모드를 사용하여 자동화를 실행하도록 AWS Systems Manager 콘솔과 AWS Command Line Interface(AWS CLI)를 사용하는 방법을 설명합니다. 수동 실행 모드를 사용하면 자동화가 [*대기 중(Waiting)*] 상태로 시작하고 각 단계 간에 [*대기 중(Waiting)*] 상태로 일시 중지합니다. 그러면 사용자가 자동화를 진행할 시점을 제어할 수 있어 다음 단계로 넘어가기 전에 단계의 결과를 검토해야 할 경우 유용합니다.

자동화는 현재 사용자의 컨텍스트에서 실행됩니다. 이는 런북과 그 런북에 의해 호출되는 모든 작업을 사용할 권한이 있는 한 추가 IAM 권한을 구성할 필요가 없음을 뜻합니다. IAM에서 관리자 권한이 있는 경우 이 자동화를 실행할 권한이 이미 있습니다.

## 단계별 자동화 실행(콘솔)
<a name="automation-working-executing-manually-console"></a>

다음 절차에서는 Systems Manager 콘솔을 사용하여 단계별 자동화를 수동으로 실행하는 방법을 보여줍니다.

**단계별 자동화를 실행하려면**

1. AWS Systems Manager 콘솔[https://console.aws.amazon.com/systems-manager/](https://console.aws.amazon.com/systems-manager/)을 엽니다.

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

1. [**Automation 문서(Automation document)**] 목록에서 실행서를 선택합니다. **문서 카테고리** 창에서 옵션을 1개 이상 선택하여 SSM 문서를 목적에 따라 필터링합니다. 자신이 소유한 실행서를 보려면 [**내 소유(Owned by me)**] 탭을 선택합니다. 자신의 계정과 공유하고 있는 실행서를 보려면 [**나와 공유됨(Shared with me)**] 탭을 선택합니다. 모든 실행서를 보려면 [**모든 문서(All documents)**] 탭을 선택합니다.
**참고**  
실행서 이름을 선택하여 실행서에 대한 정보를 볼 수 있습니다.

1. **문서 세부 정보** 섹션에서 **문서 버전**이 실행할 버전으로 설정되었는지 확인합니다. 이 시스템에는 다음 버전 옵션이 포함되어 있습니다.
   + **런타임 시 기본 버전** - Automation 런북이 정기적으로 업데이트되며 새 기본 버전이 할당된 경우 이 옵션을 선택합니다.
   + **런타임 시 최신 버전** - Automation 런북이 정기적으로 업데이트되며 최근에 업데이트된 버전을 실행하려는 경우 이 옵션을 선택합니다.
   + **1(기본값)** - 문서의 최초 버전을 실행하려면 이 옵션을 선택합니다(기본값).

1. **다음**을 선택합니다.

1. **실행 모드** 섹션에서 **Manual execution(수동 실행)**을 선택합니다.

1. **입력 파라미터** 섹션에서 필수 입력을 지정합니다. 필요에 따라 [**AutomationAssumeRole**] 목록에서 IAM 서비스 역할을 선택합니다.

1. **실행**을 선택합니다.

1. 자동화의 첫 번째 단계를 실행할 준비가 되면 [**이 단계를 실행(Execute this step)**]을 선택합니다. 자동화가 1단계를 실행하고 이 절차의 3단계에서 선택한 런북에 지정된 이후 단계를 실행하기 전에 일시 중지됩니다. 실행서에 여러 단계가 포함된 경우 각 단계마다 [**이 단계 실행(Execute this step)**]을 선택하여 자동화를 진행합니다. [**이 단계 실행(Execute this step)**]을 선택할 때마다 작업이 실행됩니다.
**참고**  
콘솔에 자동화 상태가 표시됩니다. 자동화 단계가 실행되지 않는 경우 [Systems Manager Automation 문제 해결](automation-troubleshooting.md) 섹션을 참조하세요.

1. 실행서에 지정된 모든 단계를 마쳤으면 [**완료 및 결과 보기(Complete and view results)**]를 선택하여 자동화를 완료하고 결과를 확인합니다.

자동화 실행이 완료되면 동일하거나 수정된 파라미터로 실행을 다시 실행할 수 있습니다. 자세한 내용은 [자동화 실행 재실행](automation-rerun-executions.md) 섹션을 참조하세요.

## 단계별 자동화 실행(명령줄)
<a name="automation-working-executing-manually-commandline"></a>

다음 절차에서는 AWS CLI(Linux, macOS 또는 Windows) 또는 AWS Tools for PowerShell을 사용하여 단계별 자동화를 수동으로 실행하는 방법을 설명합니다.

**단계별 자동화를 실행하려면**

1. 아직 하지 않은 경우 AWS CLI 또는 AWS Tools for PowerShell을 설치하고 구성합니다.

   자세한 내용은 [최신 버전의 AWS CLI 설치 또는 업데이트](https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html) 및 [AWS Tools for PowerShell 설치](https://docs.aws.amazon.com/powershell/latest/userguide/pstools-getting-set-up.html)를 참조하세요.

1. 수동 자동화를 시작하려면 다음 명령을 실행합니다. 각 *example resource placeholder*를 사용자의 정보로 바꿉니다.

------
#### [ Linux & macOS ]

   ```
   aws ssm start-automation-execution \
       --document-name runbook name \
       --mode Interactive \
       --parameters runbook parameters
   ```

------
#### [ Windows ]

   ```
   aws ssm start-automation-execution ^
       --document-name runbook name ^
       --mode Interactive ^
       --parameters runbook parameters
   ```

------
#### [ PowerShell ]

   ```
   Start-SSMAutomationExecution `
       -DocumentName runbook name `
       -Mode Interactive `
       -Parameter runbook parameters
   ```

------

   여기에 실행서 `AWS-RestartEC2Instance`를 사용하여 지정된 EC2 인스턴스를 다시 시작하는 예가 있습니다.

------
#### [ Linux & macOS ]

   ```
   aws ssm start-automation-execution \
       --document-name "AWS-RestartEC2Instance" \
       --mode Interactive \
       --parameters "InstanceId=i-02573cafcfEXAMPLE"
   ```

------
#### [ Windows ]

   ```
   aws ssm start-automation-execution ^
       --document-name "AWS-RestartEC2Instance" ^
       --mode Interactive ^
       --parameters "InstanceId=i-02573cafcfEXAMPLE"
   ```

------
#### [ PowerShell ]

   ```
   Start-SSMAutomationExecution `
       -DocumentName AWS-RestartEC2Instance `
       -Mode Interactive 
       -Parameter @{"InstanceId"="i-02573cafcfEXAMPLE"}
   ```

------

   시스템은 다음과 같은 정보를 반환합니다.

------
#### [ Linux & macOS ]

   ```
   {
       "AutomationExecutionId": "ba9cd881-1b36-4d31-a698-0123456789ab"
   }
   ```

------
#### [ Windows ]

   ```
   {
       "AutomationExecutionId": "ba9cd881-1b36-4d31-a698-0123456789ab"
   }
   ```

------
#### [ PowerShell ]

   ```
   ba9cd881-1b36-4d31-a698-0123456789ab
   ```

------

1. 자동화의 첫 번째 단계를 실행할 준비가 되면 다음 명령을 실행합니다. 각 *example resource placeholder*를 사용자의 정보로 바꿉니다. 자동화가 1단계를 실행하고 이 절차의 1단계에서 선택한 런북에 지정된 이후 단계를 실행하기 전에 일시 중지됩니다. 실행서에 여러 단계가 포함된 경우 각 단계마다 다음 명령을 실행하여 자동화를 진행합니다.

------
#### [ Linux & macOS ]

   ```
   aws ssm send-automation-signal \
       --automation-execution-id ba9cd881-1b36-4d31-a698-0123456789ab \
       --signal-type StartStep \
       --payload StepName="stopInstances"
   ```

------
#### [ Windows ]

   ```
   aws ssm send-automation-signal ^
       --automation-execution-id ba9cd881-1b36-4d31-a698-0123456789ab ^
       --signal-type StartStep ^
       --payload StepName="stopInstances"
   ```

------
#### [ PowerShell ]

   ```
   Send-SSMAutomationSignal `
       -AutomationExecutionId ba9cd881-1b36-4d31-a698-0123456789ab `
       -SignalType StartStep 
       -Payload @{"StepName"="stopInstances"}
   ```

------

   명령이 성공해도 출력은 없습니다.

1. 다음 명령을 실행하여 자동화의 각 단계 실행 상태를 검색합니다.

------
#### [ Linux & macOS ]

   ```
   aws ssm describe-automation-step-executions \
       --automation-execution-id ba9cd881-1b36-4d31-a698-0123456789ab
   ```

------
#### [ Windows ]

   ```
   aws ssm describe-automation-step-executions ^
       --automation-execution-id ba9cd881-1b36-4d31-a698-0123456789ab
   ```

------
#### [ PowerShell ]

   ```
   Get-SSMAutomationStepExecution `
       -AutomationExecutionId ba9cd881-1b36-4d31-a698-0123456789ab
   ```

------

   시스템은 다음과 같은 정보를 반환합니다.

------
#### [ Linux & macOS ]

   ```
   {
       "StepExecutions": [
           {
               "StepName": "stopInstances",
               "Action": "aws:changeInstanceState",
               "ExecutionStartTime": 1557167178.42,
               "ExecutionEndTime": 1557167220.617,
               "StepStatus": "Success",
               "Inputs": {
                   "DesiredState": "\"stopped\"",
                   "InstanceIds": "[\"i-02573cafcfEXAMPLE\"]"
               },
               "Outputs": {
                   "InstanceStates": [
                       "stopped"
                   ]
               },
               "StepExecutionId": "654243ba-71e3-4771-b04f-0123456789ab",
               "OverriddenParameters": {},
               "ValidNextSteps": [
                   "startInstances"
               ]
           },
           {
               "StepName": "startInstances",
               "Action": "aws:changeInstanceState",
               "ExecutionStartTime": 1557167273.754,
               "ExecutionEndTime": 1557167480.73,
               "StepStatus": "Success",
               "Inputs": {
                   "DesiredState": "\"running\"",
                   "InstanceIds": "[\"i-02573cafcfEXAMPLE\"]"
               },
               "Outputs": {
                   "InstanceStates": [
                       "running"
                   ]
               },
               "StepExecutionId": "8a4a1e0d-dc3e-4039-a599-0123456789ab",
               "OverriddenParameters": {}
           }
       ]
   }
   ```

------
#### [ Windows ]

   ```
   {
       "StepExecutions": [
           {
               "StepName": "stopInstances",
               "Action": "aws:changeInstanceState",
               "ExecutionStartTime": 1557167178.42,
               "ExecutionEndTime": 1557167220.617,
               "StepStatus": "Success",
               "Inputs": {
                   "DesiredState": "\"stopped\"",
                   "InstanceIds": "[\"i-02573cafcfEXAMPLE\"]"
               },
               "Outputs": {
                   "InstanceStates": [
                       "stopped"
                   ]
               },
               "StepExecutionId": "654243ba-71e3-4771-b04f-0123456789ab",
               "OverriddenParameters": {},
               "ValidNextSteps": [
                   "startInstances"
               ]
           },
           {
               "StepName": "startInstances",
               "Action": "aws:changeInstanceState",
               "ExecutionStartTime": 1557167273.754,
               "ExecutionEndTime": 1557167480.73,
               "StepStatus": "Success",
               "Inputs": {
                   "DesiredState": "\"running\"",
                   "InstanceIds": "[\"i-02573cafcfEXAMPLE\"]"
               },
               "Outputs": {
                   "InstanceStates": [
                       "running"
                   ]
               },
               "StepExecutionId": "8a4a1e0d-dc3e-4039-a599-0123456789ab",
               "OverriddenParameters": {}
           }
       ]
   }
   ```

------
#### [ PowerShell ]

   ```
   Action: aws:changeInstanceState
   ExecutionEndTime     : 5/6/2019 19:45:46
   ExecutionStartTime   : 5/6/2019 19:45:03
   FailureDetails       : 
   FailureMessage       : 
   Inputs               : {[DesiredState, "stopped"], [InstanceIds, ["i-02573cafcfEXAMPLE"]]}
   IsCritical           : False
   IsEnd                : False
   MaxAttempts          : 0
   NextStep             : 
   OnFailure            : 
   Outputs              : {[InstanceStates, Amazon.Runtime.Internal.Util.AlwaysSendList`1[System.String]]}
   OverriddenParameters : {}
   Response             : 
   ResponseCode         : 
   StepExecutionId      : 8fcc9641-24b7-40b3-a9be-0123456789ab
   StepName             : stopInstances
   StepStatus           : Success
   TimeoutSeconds       : 0
   ValidNextSteps       : {startInstances}
   ```

------

1. 선택한 런북 내에 지정된 모든 단계가 종료된 후에 다음 명령을 실행하여 자동화를 완료합니다. 각 *example resource placeholder*를 사용자의 정보로 바꿉니다.

------
#### [ Linux & macOS ]

   ```
   aws ssm stop-automation-execution \
       --automation-execution-id ba9cd881-1b36-4d31-a698-0123456789ab \
       --type Complete
   ```

------
#### [ Windows ]

   ```
   aws ssm stop-automation-execution ^
       --automation-execution-id ba9cd881-1b36-4d31-a698-0123456789ab ^
       --type Complete
   ```

------
#### [ PowerShell ]

   ```
   Stop-SSMAutomationExecution `
       -AutomationExecutionId ba9cd881-1b36-4d31-a698-0123456789ab `
       -Type Complete
   ```

------

   명령이 성공해도 출력은 없습니다.

# State Manager 연결을 사용하여 자동화 예약
<a name="scheduling-automations-state-manager-associations"></a>

런북과 State Manager 연결을 생성하여 자동화를 시작할 수 있습니다. State Manager는 AWS Systems Manager의 도구입니다. 실행서와의 State Manager 연결을 생성하면 여러 유형의 AWS 리소스를 대상으로 지정할 수 있습니다. 예를 들어 다음과 같이 AWS 리소스에 원하는 상태를 적용하는 연결을 생성할 수 있습니다.
+ Amazon Elastic Compute Cloud(Amazon EC2) 인스턴스에 연결하여 Systems Manager 역할을 *관리형 인스턴스*로 만듭니다.
+ 보안 그룹에 원하는 인바운드 및 아웃바운드 규칙을 적용합니다.
+ Amazon DynamoDB 백업을 생성하거나 삭제합니다.
+ Amazon Elastic Block Store(Amazon EBS) 스냅샷을 생성하거나 삭제합니다.
+ Amazon Simple Storage Service(Amazon S3) 버킷에 대한 읽기 및 쓰기 권한을 해제합니다.
+ 관리형 인스턴스 및 Amazon Relational Database Service(Amazon RDS) 인스턴스를 시작, 재시작 또는 중지합니다.
+ Linux, macOS 및 Window AMIs를 패치합니다.

AWS Systems Manager 콘솔과 AWS Command Line Interface(AWS CLI)에서 다음 절차를 사용하여 자동화를 실행하는 State Manager 연결을 생성합니다. 연결에 대한 일반 정보 및 SSM `Command` 문서 또는 `Policy` 문서를 사용하는 연결을 생성하는 방법에 대한 내용은 [연결 생성](state-manager-associations-creating.md) 문서를 참조하세요.

**시작하기 전 준비 사항**  
State Manager를 사용하여 자동화를 실행하기 전에 다음과 같은 중요 세부 정보를 알고 있어야 합니다.
+ 런북을 사용하는 연결을 생성하기 전에 AWS Systems Manager의 도구인 Automation에 대해 구성된 권한이 있는지 확인합니다. 자세한 내용은 [Automation 설정](automation-setup.md) 섹션을 참조하세요.
+ 실행서를 사용하는 State Manager 연결은 AWS 계정에서 동시에 실행되는 최대 자동화 수에 영향을 미칩니다. 최대 100개의 자동화를 동시에 실행할 수 있습니다. 자세한 내용은 **Amazon Web Services 일반 참조의 [Systems Manager 서비스 할당량](https://docs.aws.amazon.com/general/latest/gr/ssm.html#limits_ssm)을 참조하세요.
+ 자동화를 실행하는 경우 State Manager는 AWS CloudTrail에서 자동화에 의해 시작된 API 작업을 기록하지 않습니다.
+ Systems Manager는 자동으로 서비스 연결 역할을 생성하여 State Manager에 Systems Manager Automation API 작업을 호출할 권한을 부여합니다. 원할 경우, AWS CLI 또는 AWS Tools for PowerShell에서 다음 명령을 실행하여 서비스 연결 역할을 직접 생성할 수 있습니다.

------
#### [ Linux & macOS ]

  ```
  aws iam create-service-linked-role \
  --aws-service-name ssm.amazonaws.com
  ```

------
#### [ Windows ]

  ```
  aws iam create-service-linked-role ^
  --aws-service-name ssm.amazonaws.com
  ```

------
#### [ PowerShell ]

  ```
  New-IAMServiceLinkedRole `
  -AWSServiceName ssm.amazonaws.com
  ```

------

  서비스 연결 역할에 대한 자세한 내용은 [Systems Manager에 서비스 연결 역할 사용](using-service-linked-roles.md) 섹션을 참조하세요.

## 자동화를 실행하는 연결 생성(콘솔)
<a name="create-automation-association-console"></a>

다음 절차에서는 Systems Manager 콘솔을 사용하여 자동화를 실행하는 State Manager 연결을 생성하는 방법을 설명합니다.

**자동화를 실행하는 State Manager 연결을 생성하려면**

1. [https://console.aws.amazon.com/systems-manager/](https://console.aws.amazon.com/systems-manager/)에서 AWS Systems Manager 콘솔을 엽니다.

1. 탐색 창에서 **State Manager**를 선택한 후 **연결 생성**을 선택합니다.

1. **Name(이름)** 필드에 이름을 지정합니다. 이는 선택 사항이며, 권장 사항은 아닙니다.

1. [**문서(Document)**] 목록에서 실행서를 선택합니다. 검색 창에서 [**문서 유형 : 같음 : Automation(Document type : Equal : Automation)**]를 필터링합니다. 추가 실행서를 보려면 검색 창의 오른쪽에 있는 번호를 사용합니다.
**참고**  
실행서 이름을 선택하여 실행서에 대한 정보를 볼 수 있습니다.

1. 대상의 리소스 ID를 지정하여 하나 이상의 대상에 대해 자동화를 실행하려면 **Simple execution(단순 실행)**을 선택합니다. 태그 또는 AWS Resource Groups와 같은 대상 지정 옵션을 지정하여 AWS 리소스 플릿에서 자동화를 실행하려면 [**속도 제어(Rate control)**]를 선택합니다. 또한 동시성 및 오류 임계값을 지정하여 리소스에 대한 자동화 작업을 제어할 수도 있습니다.

   [**속도 제어(Rate control)**]를 선택하면 [**대상(Targets)**] 섹션이 표시됩니다.

1. **대상** 섹션에서 리소스를 대상으로 지정할 방법을 선택합니다.

   1. (필수) **파라미터** 목록에서 파라미터 하나를 선택합니다. [**파라미터(Parameter)**] 목록의 항목은 이 절차의 시작 부분에서 선택한 실행서의 파라미터로 결정됩니다. 파라미터를 선택하면 자동화가 실행되는 리소스 유형을 정의할 수 있습니다.

   1. (필수) **대상** 목록에서 리소스를 대상으로 지정할 방법을 선택합니다.
      + **리소스 그룹**: **Resource Group(리소스 그룹)** 목록에서 그룹의 이름을 선택합니다. 실행서에서 AWS Resource Groups를 대상으로 지정에 대한 자세한 내용은 [AWS Resource Groups을 대상으로 지정](running-automations-map-targets.md#target-resource-groups) 섹션을 참조하세요.
      + **태그**: 제공된 필드에 태그 키 및 (선택적으로) 태그 값을 입력합니다. **추가**를 선택합니다. 실행서에서 태그를 대상으로 지정에 대한 자세한 내용은 [태그를 대상으로 지정](running-automations-map-targets.md#target-tags) 섹션을 참조하세요.
      + **파라미터 값**: **입력 파라미터** 섹션에 값을 입력합니다. 여러 값을 지정할 경우 Systems Manager는 지정된 각 값에 대해 하위 자동화를 실행합니다.

        예를 들어 실행서에 **InstanceID** 파라미터가 포함되어 있다고 가정해 보겠습니다. 자동화 실행 시 **InstanceID** 파라미터의 값을 대상으로 지정할 경우 Systems Manager는 지정한 각 인스턴스 ID 값마다 하위 자동화를 하나 실행합니다. 이 자동화가 각각의 지정된 인스턴스 실행을 완료하거나 실행에 실패하면 상위 자동화가 완료된 것입니다. 최대 50개 파라미터 값을 대상으로 지정할 수 있습니다. 실행서에서 파라미터 값을 대상으로 지정에 대한 자세한 내용은 [파라미터 값을 대상으로 지정](running-automations-map-targets.md#target-parameter-values) 섹션을 참조하세요.

1. **입력 파라미터** 섹션에서 필요한 입력 파라미터를 지정합니다.

   태그나 리소스 그룹을 사용하여 리소스를 대상으로 지정하기로 한 경우 [**입력 파라미터(Input parameters)**] 섹션에서 옵션 중 일부는 선택하지 않아도 될 것입니다. 예를 들어 `AWS-RestartEC2Instance` 실행서를 선택했으며 태그를 사용하여 인스턴스를 대상으로 지정하기로 한 경우 [**입력 파라미터(Input parameters)**] 섹션에서 인스턴스 ID를 지정하거나 선택할 필요가 없습니다. 자동화는 지정된 태그를 사용하여 다시 시작할 인스턴스를 정확히 찾아낼 수 있습니다.
**중요**  
**AutomationAssumeRole** 필드에 역할 ARN을 지정해야 합니다. State Manager은(는) 수임 역할을 사용하여 사용자 대신 실행서에 지정된 AWS 서비스을(를) 호출하고 Automation 연결을 실행합니다.

1. 연결을 주기적으로 실행하려면 **일정 지정** 섹션에서 **On Schedule(일정에 따라)**을 선택합니다. 이 옵션을 선택할 경우 제공된 옵션을 사용하여 Cron 또는 Rate 표현식으로 일정을 생성합니다. State Manager용 Cron 및 Rate 표현식에 대한 자세한 내용은 [연결에 대한 Cron 및 Rate 표현식](reference-cron-and-rate-expressions.md#reference-cron-and-rate-expressions-association) 섹션을 참조하세요.
**참고**  
Rate 표현식은 실행서를 사용하는 State Manager 연결에 대해 선호되는 예약 메커니즘입니다. Rate 표현식을 사용하면 동시에 실행되는 자동화가 최대 수에 도달하는 경우 연결 실행 유연성이 더 큽니다. 속도 일정에서는 Systems Manager가 동시 자동화가 최대 수에 도달하여 조절되었다는 알림을 수신한 잠시 후에 자동화를 재시도할 수 있습니다.

   연결을 한 번만 실행하려면 **No schedule(일정 없음)**을 선택합니다.

1. (선택 사항) **속도 제어(Rate Control)** 섹션에서 **동시성(Concurrency)** 및 **오류 임계값(Error threshold)** 옵션을 선택하여 AWS 리소스에 대한 자동화 배포를 제어합니다.

   1. **동시성** 섹션에서 옵션을 선택합니다.
      + [**대상(targets)**]을 선택하여 자동화를 동시에 실행할 수 있는 대상 수(절대 개수)를 입력합니다.
      + [**백분율(percentage)**]을 선택하여 자동화를 동시에 실행할 수 있는 대상의 백분율을 입력합니다.

   1. **Error threshold**(오류 임계값) 섹션에서 옵션을 선택합니다.
      + [**오류(errors)**]를 선택하여 Automation을 통한 다른 리소스로의 자동화 전송이 중지될 때까지 허용되는 오류 수(절대 개수)를 입력합니다.
      + [**백분율(percentage)**]을 선택하여 Automation을 통한 다른 리소스로의 자동화 전송이 중지될 때까지 허용되는 백분율을 입력합니다.

   자동화에서 대상 및 속도 제어 사용에 대한 자세한 내용은 [대규모로 자동화된 작업 실행](running-automations-scale.md) 섹션을 참조하세요.

1. **연결 생성**을 선택합니다.
**중요**  
연결을 생성하면 즉시 지정된 대상에 대해 연결이 실행됩니다. 그런 다음 cron 또는 rate 표현식을 기반으로 연결이 실행됩니다. [**일정 없음(No schedule)**]을 선택한 경우 연결이 다시 실행되지 않습니다.

## 자동화를 실행하는 연결 생성(명령줄)
<a name="create-automation-association-cli"></a>

다음 절차에서는 AWS CLI(Linux 또는 Windows Server) 또는 AWS Tools for PowerShell을 사용하여 자동화를 실행하는 State Manager 연결을 생성하는 방법을 설명합니다.

**시작하기 전 준비 사항**  
다음 절차를 완료하기 전에 먼저 런북을 실행하는 데 필요한 권한이 포함된 IAM 서비스 역할을 생성하고 AWS Systems Manager의 도구인 Automation에 대해 신뢰 관계를 구성했는지 확인합니다. 자세한 내용은 [작업 1: Automation을 위한 서비스 역할 생성](automation-setup-iam.md#create-service-role) 섹션을 참조하세요.

**자동화를 실행하는 연결을 생성하려면**

1. 아직 하지 않은 경우 AWS CLI 또는 AWS Tools for PowerShell을 설치하고 구성합니다.

   자세한 내용은 [최신 버전의 AWS CLI 설치 또는 업데이트](https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html) 및 [AWS Tools for PowerShell 설치](https://docs.aws.amazon.com/powershell/latest/userguide/pstools-getting-set-up.html)를 참조하세요.

1. 다음 명령을 실행하여 문서 목록을 확인합니다.

------
#### [ Linux & macOS ]

   ```
   aws ssm list-documents
   ```

------
#### [ Windows ]

   ```
   aws ssm list-documents
   ```

------
#### [ PowerShell ]

   ```
   Get-SSMDocumentList
   ```

------

   연결에 사용할 실행서의 이름을 기록해 둡니다.

1. 다음 명령을 실행하여 런북에 대한 세부 정보를 봅니다. 다음 명령에서 *실행서 이름*을 자신의 정보로 바꿉니다.

------
#### [ Linux & macOS ]

   ```
   aws ssm describe-document \
   --name runbook name
   ```

   `--automation-target-parameter-name` 옵션에 사용할 파라미터 이름(예: `InstanceId`)에 유의하세요. 이 파라미터는 자동화가 실행되는 리소스 유형을 결정합니다.

------
#### [ Windows ]

   ```
   aws ssm describe-document ^
   --name runbook name
   ```

   `--automation-target-parameter-name` 옵션에 사용할 파라미터 이름(예: `InstanceId`)에 유의하세요. 이 파라미터는 자동화가 실행되는 리소스 유형을 결정합니다.

------
#### [ PowerShell ]

   ```
   Get-SSMDocumentDescription `
   -Name runbook name
   ```

   `AutomationTargetParameterName` 옵션에 사용할 파라미터 이름(예: `InstanceId`)에 유의하세요. 이 파라미터는 자동화가 실행되는 리소스 유형을 결정합니다.

------

1. State Manager 연결을 사용하여 자동화를 실행하는 명령 생성 각 *example resource placeholder*를 사용자의 정보로 바꿉니다.

   *태그를 사용하여 대상 지정*

------
#### [ Linux & macOS ]

   ```
   aws ssm create-association \
   --association-name association name \
   --targets Key=tag:key name,Values=value \
   --name runbook name \
   --parameters AutomationAssumeRole=arn:aws:iam::123456789012:role/RunbookAssumeRole \
   --automation-target-parameter-name target parameter \
   --schedule "cron or rate expression"
   ```

**참고**  
AWS CLI를 사용하여 연결을 생성한 경우 `--targets` 파라미터를 사용하여 연결에 대한 인스턴스를 대상으로 지정합니다. `--instance-id` 파라미터를 사용하지 마세요. `--instance-id` 파라미터는 레거시 파라미터입니다.

------
#### [ Windows ]

   ```
   aws ssm create-association ^
   --association-name association name ^
   --targets Key=tag:key name,Values=value ^
   --name runbook name ^
   --parameters AutomationAssumeRole=arn:aws:iam::123456789012:role/RunbookAssumeRole ^
   --automation-target-parameter-name target parameter ^
   --schedule "cron or rate expression"
   ```

**참고**  
AWS CLI를 사용하여 연결을 생성한 경우 `--targets` 파라미터를 사용하여 연결에 대한 인스턴스를 대상으로 지정합니다. `--instance-id` 파라미터를 사용하지 마세요. `--instance-id` 파라미터는 레거시 파라미터입니다.

------
#### [ PowerShell ]

   ```
   $Targets = New-Object Amazon.SimpleSystemsManagement.Model.Target
   $Targets.Key = "tag:key name"
   $Targets.Values = "value"
   
   New-SSMAssociation `
   -AssociationName "association name" `
   -Target $Targets `
   -Name "runbook name" `
   -Parameters @{
   "AutomationAssumeRole"="arn:aws:iam::123456789012:role/RunbookAssumeRole" } `
   -AutomationTargetParameterName "target parameter" `
   -ScheduleExpression "cron or rate expression"
   ```

**참고**  
AWS Tools for PowerShell를 사용하여 연결을 생성한 경우 `Target` 파라미터를 사용하여 연결에 대한 인스턴스를 대상으로 지정합니다. `InstanceId` 파라미터를 사용하지 마세요. `InstanceId` 파라미터는 레거시 파라미터입니다.

------

   *파라미터 값을 사용하여 대상 지정*

------
#### [ Linux & macOS ]

   ```
   aws ssm create-association \
   --association-name association name \
   --targets Key=ParameterValues,Values=value,value 2,value 3 \
   --name runbook name \
   --parameters AutomationAssumeRole=arn:aws:iam::123456789012:role/RunbookAssumeRole \
   --automation-target-parameter-name target parameter \
   --schedule "cron or rate expression"
   ```

------
#### [ Windows ]

   ```
   aws ssm create-association ^
   --association-name association name ^
   --targets Key=ParameterValues,Values=value,value 2,value 3 ^
   --name runbook name ^
   --parameters AutomationAssumeRole=arn:aws:iam::123456789012:role/RunbookAssumeRole ^
   --automation-target-parameter-name target parameter ^
   --schedule "cron or rate expression"
   ```

------
#### [ PowerShell ]

   ```
   $Targets = New-Object Amazon.SimpleSystemsManagement.Model.Target
   $Targets.Key = "ParameterValues"
   $Targets.Values = "value","value 2","value 3"
   
   New-SSMAssociation `
   -AssociationName "association name" `
   -Target $Targets `
   -Name "runbook name" `
   -Parameters @{
   "AutomationAssumeRole"="arn:aws:iam::123456789012:role/RunbookAssumeRole"} `
   -AutomationTargetParameterName "target parameter" `
   -ScheduleExpression "cron or rate expression"
   ```

------

   *AWS Resource Groups을 사용하여 대상 지정*

------
#### [ Linux & macOS ]

   ```
   aws ssm create-association \
   --association-name association name \
   --targets Key=ResourceGroup,Values=resource group name \
   --name runbook name \
   --parameters AutomationAssumeRole=arn:aws:iam::123456789012:role/RunbookAssumeRole \
   --automation-target-parameter-name target parameter \
   --schedule "cron or rate expression"
   ```

------
#### [ Windows ]

   ```
   aws ssm create-association ^
   --association-name association name ^
   --targets Key=ResourceGroup,Values=resource group name ^
   --name runbook name ^
   --parameters AutomationAssumeRole=arn:aws:iam::123456789012:role/RunbookAssumeRole ^
   --automation-target-parameter-name target parameter ^
   --schedule "cron or rate expression"
   ```

------
#### [ PowerShell ]

   ```
   $Targets = New-Object Amazon.SimpleSystemsManagement.Model.Target
   $Targets.Key = "ResourceGroup"
   $Targets.Values = "resource group name"
   
   New-SSMAssociation `
   -AssociationName "association name" `
   -Target $Targets `
   -Name "runbook name" `
   -Parameters @{
   "AutomationAssumeRole"="arn:aws:iam::123456789012:role/RunbookAssumeRole"} `
   -AutomationTargetParameterName "target parameter" `
   -ScheduleExpression "cron or rate expression"
   ```

------

   *여러 계정 및 리전을 대상으로 지정*

------
#### [ Linux & macOS ]

   ```
   aws ssm create-association \
   --association-name association name \
   --targets Key=ResourceGroup,Values=resource group name \
   --name runbook name \
   --parameters AutomationAssumeRole=arn:aws:iam::123456789012:role/RunbookAssumeRole \
   --automation-target-parameter-name target parameter \
   --schedule "cron or rate expression" \ 
   --target-locations Accounts=111122223333,444455556666,444455556666,Regions=region,region
   ```

------
#### [ Windows ]

   ```
   aws ssm create-association ^
   --association-name association name ^
   --targets Key=ResourceGroup,Values=resource group name ^
   --name runbook name ^
   --parameters AutomationAssumeRole=arn:aws:iam::123456789012:role/RunbookAssumeRole ^
   --automation-target-parameter-name target parameter ^
   --schedule "cron or rate expression" ^ 
   --target-locations Accounts=111122223333,444455556666,444455556666,Regions=region,region
   ```

------
#### [ PowerShell ]

   ```
   $Targets = New-Object Amazon.SimpleSystemsManagement.Model.Target
   $Targets.Key = "ResourceGroup"
   $Targets.Values = "resource group name"
   
   New-SSMAssociation `
   -AssociationName "association name" `
   -Target $Targets `
   -Name "runbook name" `
   -Parameters @{
   "AutomationAssumeRole"="arn:aws:iam::123456789012:role/RunbookAssumeRole"} `
   -AutomationTargetParameterName "target parameter" `
   -ScheduleExpression "cron or rate expression" `
   -TargetLocations @{
       "Accounts"=["111122223333,444455556666,444455556666"],
       "Regions"=["region,region"]
   ```

------

   이 명령은 다음과 비슷한 새 연결의 세부 정보를 반환합니다.

------
#### [ Linux & macOS ]

   ```
   {
   "AssociationDescription": {
       "ScheduleExpression": "cron(0 7 ? * MON *)",
       "Name": "AWS-StartEC2Instance",
       "Parameters": {
           "AutomationAssumeRole": [
               "arn:aws:iam::123456789012:role/RunbookAssumeRole"
           ]
       },
       "Overview": {
           "Status": "Pending",
           "DetailedStatus": "Creating"
       },
       "AssociationId": "1450b4b7-bea2-4e4b-b340-01234EXAMPLE",
       "DocumentVersion": "$DEFAULT",
       "AutomationTargetParameterName": "InstanceId",
       "LastUpdateAssociationDate": 1564686638.498,
       "Date": 1564686638.498,
       "AssociationVersion": "1",
       "AssociationName": "CLI",
       "Targets": [
           {
               "Values": [
                   "DEV"
               ],
               "Key": "tag:ENV"
           }
       ]
   }
   }
   ```

------
#### [ Windows ]

   ```
   {
   "AssociationDescription": {
       "ScheduleExpression": "cron(0 7 ? * MON *)",
       "Name": "AWS-StartEC2Instance",
       "Parameters": {
           "AutomationAssumeRole": [
               "arn:aws:iam::123456789012:role/RunbookAssumeRole"
           ]
       },
       "Overview": {
           "Status": "Pending",
           "DetailedStatus": "Creating"
       },
       "AssociationId": "1450b4b7-bea2-4e4b-b340-01234EXAMPLE",
       "DocumentVersion": "$DEFAULT",
       "AutomationTargetParameterName": "InstanceId",
       "LastUpdateAssociationDate": 1564686638.498,
       "Date": 1564686638.498,
       "AssociationVersion": "1",
       "AssociationName": "CLI",
       "Targets": [
           {
               "Values": [
                   "DEV"
               ],
               "Key": "tag:ENV"
           }
       ]
   }
   }
   ```

------
#### [ PowerShell ]

   ```
   Name                  : AWS-StartEC2Instance
   InstanceId            : 
   Date                  : 8/1/2019 7:31:38 PM
   Status.Name           : 
   Status.Date           : 
   Status.Message        : 
   Status.AdditionalInfo :
   ```

------

**참고**  
태그를 사용하여 하나 이상의 대상 인스턴스에 대해 연결을 생성한 다음 인스턴스에서 태그를 제거하면 해당 인스턴스가 더 이상 연결을 실행하지 않습니다. 이러한 인스턴스는 State Manager 문서에서 연결 해제됩니다.

## State Manager 연결에 의해 실행되는 자동화의 문제 해결
<a name="troubleshooting-automation-associations"></a>

Systems Manager Automation은 리전별로 계정당 동시 자동화 100개 및 대기 중인 자동화 1,000개 제한을 시행합니다. 실행서를 사용하는 State Manager 연결에서 **실패(Failed)** 상태와 **AutomationExecutionLimitExceeded** 세부 상태를 표시할 경우 자동화가 한도에 도달한 것입니다. 결과적으로 Systems Manager가 자동화를 스로틀링합니다. 이 문제를 해결하려면 다음과 같이 실행합니다.
+ 연결에 다른 rate 또는 cron 표현식을 사용합니다. 예를 들어 연결이 30분마다 실행하도록 지정된 경우 1시간 또는 2시간마다 실행하도록 표현식을 변경합니다.
+ **보류 중(Pending)** 상태인 기존 자동화를 삭제합니다. 이러한 자동화를 삭제하면 현재 대기열을 삭제하는 것입니다.

# 유지 관리 기간으로 자동화 예약
<a name="scheduling-automations-maintenance-windows"></a>

실행서를 유지 관리 기간의 등록된 태스크로 구성하여 자동화를 시작할 수 있습니다. 실행서를 등록된 태스크로 등록하면 유지 관리 기간은 예약된 유지 관리 기간 중에 자동화를 실행합니다.

예를 들어 유지 관리 기간에 대상으로 등록된 인스턴스의 Amazon Machine Image(AMI)를 만드는 `CreateAMI`라는 실행서를 생성한다고 가정해 보겠습니다. `CreateAMI` 실행서와 해당 자동화를 유지 관리 기간의 등록된 태스크로 지정하려면 먼저 유지 관리 기간을 생성하고 대상을 등록합니다. 그런 다음, 다음 절차에 따라 유지 관리 기간에서 `CreateAMI` 문서를 등록된 태스크로 지정합니다. 예약된 기간 중에 유지 관리 기간이 시작되면 시스템은 자동화를 실행하여 등록된 대상의 AMI를 생성합니다.

Automation 실행서 생성에 대한 자세한 내용은 [사용자 런북 생성](automation-documents.md) 섹션을 참조하세요. Automation은 AWS Systems Manager의 도구입니다.

AWS Systems Manager 콘솔, AWS Command Line Interface(AWS CLI) 또는 AWS Tools for Windows PowerShell에서 다음 절차에 따라 자동화를 유지 관리 기간의 등록된 태스크로 구성합니다.

## 자동화 태스크를 유지 관리 기간으로 등록(콘솔)
<a name="register-automation-task-maintenance-window-console"></a>

다음 절차에서는 Systems Manager 콘솔을 사용하여 자동화를 유지 관리 기간의 등록된 태스크로 구성하는 방법을 설명합니다.

**시작하기 전 준비 사항**  
다음 절차를 완료하기 전에 유지 관리 기간을 생성하고 하나 이상의 대상을 등록해야 합니다. 자세한 내용은 다음 절차를 참조하세요.
+ [콘솔을 사용하여 유지 관리 기간 생성](sysman-maintenance-create-mw.md).
+ [콘솔을 사용하여 유지 관리 기간에 대상 할당](sysman-maintenance-assign-targets.md)

**자동화를 유지 관리 기간의 등록된 태스크로 구성하려면**

1. [https://console.aws.amazon.com/systems-manager/](https://console.aws.amazon.com/systems-manager/)에서 AWS Systems Manager 콘솔을 엽니다.

1. 왼쪽 탐색 창에서 **Maintenance Windows**를 선택하고 자동화 작업을 등록하려는 유지 관리 기간을 선택합니다.

1. **작업**을 선택합니다. 그런 다음 [**자동화 태스크 등록(Register Automation task)**]을 선택하여 실행서를 사용해 대상에서 원하는 자동화를 실행합니다.

1. **이름**에 작업 이름을 입력합니다.

1. **설명**에 설명을 입력합니다.

1. [**문서(Document)**]에서 실행할 태스크를 정의하는 실행서를 선택합니다.

1. [**문서 버전(Document version)**]에서 사용할 실행서 버전을 선택합니다.

1. [**태스크 우선순위(Task priority)**]에서 이 태스크의 우선순위를 지정합니다. `1`이 가장 높은 우선순위입니다. 유지 관리 기간의 작업은 우선순위에 따라 예약되며, 우선순위가 같은 작업은 동시에 예약됩니다.

1. [**대상(Targets)**] 섹션에서 선택한 실행서가 리소스에 대한 태스크를 실행하는 경우 태그를 지정하거나 수동으로 인스턴스를 선택하여 이 자동화를 실행할 대상을 식별합니다.
**참고**  
대상 대신 입력 파라미터를 통해 리소스를 전달하려는 경우 유지 관리 기간 대상을 지정할 필요가 없습니다.  
대부분의 경우 자동화 태스크의 대상을 명시적으로 지정할 필요가 없습니다. 예를 들어 `AWS-UpdateLinuxAmi` 실행서를 사용하여 Linux용 Amazon Machine Image(AMI)를 업데이트하는 Automation 유형 태스크를 생성한다고 가정해 보겠습니다. 태스크가 실행되면 AMI는 사용 가능한 최신 Linux 배포 패키지와 Amazon 소프트웨어로 업데이트됩니다. AMI에서 생성된 새 인스턴스에는 이러한 업데이트가 이미 설치되어 있습니다. 업데이트할 AMI의 ID가 실행서에 대한 입력 파라미터에 지정되어 유지 관리 기간 태스크에서 대상을 다시 지정할 필요가 없습니다.

   대상이 필요하지 않은 유지 관리 기간 태스크에 대한 자세한 내용은 [대상 없이 유지 관리 기간 태스크 등록](maintenance-windows-targetless-tasks.md) 섹션을 참조하세요.

1. (선택 사항) **속도 제어**:
**참고**  
실 행중인 태스크가 대상을 지정하지 않으면 속도 제어를 지정할 필요가 없습니다.
   + **동시성(Concurrency)**에 자동화를 동시에 실행할 대상의 수 또는 백분율을 지정합니다.

     태크 키-값 페어를 선택하여 대상을 선택했지만 몇 개의 대상이 선택된 태그를 사용할지 확실치 않다면 백분율을 지정하여 동시에 실행할 수 있는 자동화 수를 제한합니다.

     유지 관리 기간이 실행되면 대상별로 새로운 자동화가 시작됩니다. AWS 계정당 동시 자동화는 100개로 제한됩니다. 100보다 높은 동시성을 지정할 경우 100개를 초과하는 동시 자동화는 자동화 대기열에 자동으로 추가됩니다. 자세한 내용은 **Amazon Web Services 일반 참조의 [Systems Manager 서비스 할당량](https://docs.aws.amazon.com/general/latest/gr/ssm.html#limits_ssm)을 참조하세요.
   + [**오류 임계값(Error threshold)**]에서 대상 수 또는 백분율 때문에 실패한 후 언제 다른 대상에서 자동화 실행을 중지할지 지정합니다. 예를 들어 세 번의 오류를 지정할 경우 Systems Manager는 네 번째 오류가 수신하면 자동화 실행을 중지합니다. 여전히 자동화를 처리하는 대상도 오류를 보낼 수 있습니다.

1. [**입력 파라미터(Input Parameters)**] 섹션에서 실행서의 파라미터를 지정합니다. 실행서의 경우 시스템에서 일부 값을 자동으로 채웁니다. 이러한 값을 유지하거나 바꿀 수 있습니다.
**중요**  
실행서의 경우 선택적으로 Automation 수임 역할을 지정할 수 있습니다. 이 파라미터에 역할을 지정하지 않으면 자동화가 11단계에서 선택한 유지 관리 기간 서비스 역할을 수임합니다. 그러므로 선택한 유지 관리 기간 서비스 역할이 실행서 내에 정의된 작업을 수행할 수 있는 적절한 AWS Identity and Access Management(IAM) 권한을 가지고 있는지 확인해야 합니다.  
예를 들어 Systems Manager용 서비스 연결 역할은 실행서 `AWS-CopySnapshot`을 실행하는 데 필요한 IAM 권한 `ec2:CreateSnapshot`이 없습니다. 이 시나리오에서는 사용자 지정 유지 관리 기간 서비스 역할을 사용하거나 `ec2:CreateSnapshot` 권한이 있는 자동화 수임 역할을 지정해야 합니다. 자세한 내용은 [Automation 설정](automation-setup.md) 섹션을 참조하세요.

1. **IAM 서비스 역할(IAM service role)** 영역에서 역할을 선택하여 Systems Manager에 자동화를 시작할 수 있는 권한을 부여합니다.

   유지 관리 기간 작업을 위한 사용자 지정 서비스 역할을 생성하려면 [Maintenance Windows 설정](setting-up-maintenance-windows.md)의 내용을 참조하세요.

1. **자동화 작업 등록**을 선택합니다

## Automation 태스크를 유지 관리 기간으로 등록(명령줄)
<a name="register-automation-task-maintenance-window-cli"></a>

다음 절차에서는 AWS CLI(Linux 또는 Windows Server) 또는 AWS Tools for PowerShell을 사용하여 자동화를 유지 관리 기간의 등록된 태스크로 구성하는 방법을 설명합니다.

**시작하기 전 준비 사항**  
다음 절차를 완료하기 전에 유지 관리 기간을 생성하고 하나 이상의 대상을 등록해야 합니다. 자세한 내용은 다음 절차를 참조하세요.
+ [1단계: AWS CLI를 사용한 유지 관리 기간 생성](mw-cli-tutorial-create-mw.md).
+ [2단계: AWS CLI를 사용하여 유지 관리 기간에 대상 노드 등록](mw-cli-tutorial-targets.md)

**자동화를 유지 관리 기간의 등록된 태스크로 구성하려면**

1. 아직 하지 않은 경우 AWS CLI 또는 AWS Tools for PowerShell을 설치하고 구성합니다.

   자세한 내용은 [최신 버전의 AWS CLI 설치 또는 업데이트](https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html) 및 [AWS Tools for PowerShell 설치](https://docs.aws.amazon.com/powershell/latest/userguide/pstools-getting-set-up.html)를 참조하세요.

1. 자동화를 유지 관리 기간의 등록된 태스크로 구성하기 위한 명령을 생성합니다. 각 *example resource placeholder*를 사용자의 정보로 바꿉니다.

------
#### [ Linux & macOS ]

   ```
   aws ssm register-task-with-maintenance-window \
   --window-id window ID \
   --name task name \
   --task-arn runbook name \
   --targets Key=targets,Values=value \
   --service-role-arn IAM role arn \
   --task-type AUTOMATION \
   --task-invocation-parameters task parameters \
   --priority task priority \
   --max-concurrency 10% \
   --max-errors 5
   ```

**참고**  
AWS CLI를 사용하여 등록된 태스크로 자동화를 구성하려면 `--Task-Invocation-Parameters` 파라미터를 사용하여 태스크 실행 시 태스크에 전달할 파라미터를 지정합니다. `--Task-Parameters` 파라미터를 사용하지 마세요. `--Task-Parameters` 파라미터는 레거시 파라미터입니다.  
대상이 지정되지 않은 유지 관리 기간 태스크의 경우 `--max-errors` 및 `--max-concurrency` 값을 제공할 수 없습니다. 그 대신에 시스템에서 [https://docs.aws.amazon.com/cli/latest/reference/ssm/describe-maintenance-window-tasks.html](https://docs.aws.amazon.com/cli/latest/reference/ssm/describe-maintenance-window-tasks.html) 및 [https://docs.aws.amazon.com/cli/latest/reference/ssm/get-maintenance-window-task.html](https://docs.aws.amazon.com/cli/latest/reference/ssm/get-maintenance-window-task.html)와 같은 명령에 대한 응답으로 보고될 수 있는 자리 표시자 값 `1`을 삽입합니다. 이러한 값은 태스크 실행에 영향을 주지 않으며 무시할 수 있습니다.  
대상이 필요하지 않은 유지 관리 기간 태스크에 대한 자세한 내용은 [대상 없이 유지 관리 기간 태스크 등록](maintenance-windows-targetless-tasks.md) 섹션을 참조하세요.

------
#### [ Windows ]

   ```
   aws ssm register-task-with-maintenance-window ^
   --window-id window ID ^
   --name task name ^
   --task-arn runbook name ^
   --targets Key=targets,Values=value ^
   --service-role-arn IAM role arn ^
   --task-type AUTOMATION ^
   --task-invocation-parameters task parameters ^
   --priority task priority ^
   --max-concurrency 10% ^
   --max-errors 5
   ```

**참고**  
AWS CLI를 사용하여 등록된 태스크로 자동화를 구성하려면 `--task-invocation-parameters` 파라미터를 사용하여 태스크 실행 시 태스크에 전달할 파라미터를 지정합니다. `--task-parameters` 파라미터를 사용하지 마세요. `--task-parameters` 파라미터는 레거시 파라미터입니다.  
대상이 지정되지 않은 유지 관리 기간 태스크의 경우 `--max-errors` 및 `--max-concurrency` 값을 제공할 수 없습니다. 그 대신에 시스템에서 [https://docs.aws.amazon.com/cli/latest/reference/ssm/describe-maintenance-window-tasks.html](https://docs.aws.amazon.com/cli/latest/reference/ssm/describe-maintenance-window-tasks.html) 및 [https://docs.aws.amazon.com/cli/latest/reference/ssm/get-maintenance-window-task.html](https://docs.aws.amazon.com/cli/latest/reference/ssm/get-maintenance-window-task.html)와 같은 명령에 대한 응답으로 보고될 수 있는 자리 표시자 값 `1`을 삽입합니다. 이러한 값은 태스크 실행에 영향을 주지 않으며 무시할 수 있습니다.  
대상이 필요하지 않은 유지 관리 기간 태스크에 대한 자세한 내용은 [대상 없이 유지 관리 기간 태스크 등록](maintenance-windows-targetless-tasks.md) 섹션을 참조하세요.

------
#### [ PowerShell ]

   ```
   Register-SSMTaskWithMaintenanceWindow `
   -WindowId window ID `
   -Name "task name" `
   -TaskArn "runbook name" `
   -Target @{ Key="targets";Values="value" } `
   -ServiceRoleArn "IAM role arn" `
   -TaskType "AUTOMATION" `
   -Automation_Parameter @{ "task parameter"="task parameter value"} `
   -Priority task priority `
   -MaxConcurrency 10% `
   -MaxError 5
   ```

**참고**  
AWS Tools for PowerShell를 사용하여 등록된 태스크로 자동화를 구성하려면 `-Automation_Parameter` 파라미터를 사용하여 태스크 실행 시 태스크에 전달할 파라미터를 지정합니다. `-TaskParameters` 파라미터를 사용하지 마세요. `-TaskParameters` 파라미터는 레거시 파라미터입니다.  
대상이 지정되지 않은 유지 관리 기간 태스크의 경우 `-MaxError` 및 `-MaxConcurrency` 값을 제공할 수 없습니다. 대신 시스템은 `Get-SSMMaintenanceWindowTaskList` 및 `Get-SSMMaintenanceWindowTask`와 같은 명령에 대한 응답으로 보고될 수 있는 자리 표시자 값 1을 삽입합니다. 이러한 값은 태스크 실행에 영향을 주지 않으며 무시할 수 있습니다.  
대상이 필요하지 않은 유지 관리 기간 태스크에 대한 자세한 내용은 [대상 없이 유지 관리 기간 태스크 등록](maintenance-windows-targetless-tasks.md) 섹션을 참조하세요.

------

   다음 예에서는 자동화를 우선순위 1의 유지 관리 기간의 등록된 태스크로 구성합니다. 또한 대상 없는 유지 관리 기간 태스크에 대해 `--targets`, `--max-errors` 및 `--max-concurrency` 옵션을 생략하는 방법도 보여줍니다. 자동화는 `AWS-StartEC2Instance` 실행서 및 지정된 Automation 수임 역할을 사용하여 유지 관리 기간의 대상으로 등록된 EC2 인스턴스를 시작합니다. 유지 관리 기간은 지정된 시간에 최대 5번의 인스턴스에서 동시에 자동화를 실행합니다. 또한 등록된 태스크는 오류 수가 1을 초과하는 경우 특정 간격에 대해 더 많은 인스턴스에서 실행을 중지합니다.

------
#### [ Linux & macOS ]

   ```
   aws ssm register-task-with-maintenance-window \
   --window-id mw-0c50858d01EXAMPLE \
   --name StartEC2Instances \
   --task-arn AWS-StartEC2Instance \
   --service-role-arn arn:aws:iam::123456789012:role/MaintenanceWindowRole \
   --task-type AUTOMATION \
   --task-invocation-parameters "{\"Automation\":{\"Parameters\":{\"InstanceId\":[\"{{TARGET_ID}}\"],\"AutomationAssumeRole\":[\"arn:aws:iam::123456789012:role/AutomationAssumeRole\"]}}}" \
   --priority 1
   ```

------
#### [ Windows ]

   ```
   aws ssm register-task-with-maintenance-window ^
   --window-id mw-0c50858d01EXAMPLE ^
   --name StartEC2Instances ^
   --task-arn AWS-StartEC2Instance ^
   --service-role-arn arn:aws:iam::123456789012:role/MaintenanceWindowRole ^
   --task-type AUTOMATION ^
   --task-invocation-parameters "{\"Automation\":{\"Parameters\":{\"InstanceId\":[\"{{TARGET_ID}}\"],\"AutomationAssumeRole\":[\"arn:aws:iam::123456789012:role/AutomationAssumeRole\"]}}}" ^
   --priority 1
   ```

------
#### [ PowerShell ]

   ```
   Register-SSMTaskWithMaintenanceWindow `
   -WindowId mw-0c50858d01EXAMPLE `
   -Name "StartEC2" `
   -TaskArn "AWS-StartEC2Instance" `
   -ServiceRoleArn "arn:aws:iam::123456789012:role/MaintenanceWindowRole" `
   -TaskType "AUTOMATION" `
   -Automation_Parameter @{ "InstanceId"="{{TARGET_ID}}";"AutomationAssumeRole"="arn:aws:iam::123456789012:role/AutomationAssumeRole" } `
   -Priority 1
   ```

------

   이 명령은 다음과 비슷한 새로운 등록된 작업의 세부 정보를 반환합니다.

------
#### [ Linux & macOS ]

   ```
   {
   "WindowTaskId": "4f7ca192-7e9a-40fe-9192-5cb15EXAMPLE"
   }
   ```

------
#### [ Windows ]

   ```
   {
   "WindowTaskId": "4f7ca192-7e9a-40fe-9192-5cb15EXAMPLE"
   }
   ```

------
#### [ PowerShell ]

   ```
   4f7ca192-7e9a-40fe-9192-5cb15EXAMPLE
   ```

------

1. 등록된 작업을 보려면 다음 명령을 실행합니다. *유지 관리 기간 ID*를 자신의 정보로 바꿉니다.

------
#### [ Linux & macOS ]

   ```
   aws ssm describe-maintenance-window-tasks \
   --window-id maintenance window ID
   ```

------
#### [ Windows ]

   ```
   aws ssm describe-maintenance-window-tasks ^
   --window-id maintenance window ID
   ```

------
#### [ PowerShell ]

   ```
   Get-SSMMaintenanceWindowTaskList `
   -WindowId maintenance window ID
   ```

------

   시스템은 다음과 같은 정보를 반환합니다.

------
#### [ Linux & macOS ]

   ```
   {
   "Tasks": [
       {
           "ServiceRoleArn": "arn:aws:iam::123456789012:role/MaintenanceWindowRole",
           "MaxErrors": "1",
           "TaskArn": "AWS-StartEC2Instance",
           "MaxConcurrency": "1",
           "WindowTaskId": "4f7ca192-7e9a-40fe-9192-5cb15EXAMPLE",
           "TaskParameters": {},
           "Priority": 1,
           "WindowId": "mw-0c50858d01EXAMPLE",
           "Type": "AUTOMATION",
           "Targets": [
           ],
           "Name": "StartEC2"
       }
   ]
   }
   ```

------
#### [ Windows ]

   ```
   {
   "Tasks": [
       {
           "ServiceRoleArn": "arn:aws:iam::123456789012:role/MaintenanceWindowRole",
           "MaxErrors": "1",
           "TaskArn": "AWS-StartEC2Instance",
           "MaxConcurrency": "1",
           "WindowTaskId": "4f7ca192-7e9a-40fe-9192-5cb15EXAMPLE",
           "TaskParameters": {},
           "Priority": 1,
           "WindowId": "mw-0c50858d01EXAMPLE",
           "Type": "AUTOMATION",
           "Targets": [
           ],
           "Name": "StartEC2"
       }
   ]
   }
   ```

------
#### [ PowerShell ]

   ```
   Description    : 
   LoggingInfo    : 
   MaxConcurrency : 5
   MaxErrors      : 1
   Name           : StartEC2
   Priority       : 1
   ServiceRoleArn : arn:aws:iam::123456789012:role/MaintenanceWindowRole
   Targets        : {}
   TaskArn        : AWS-StartEC2Instance
   TaskParameters : {}
   Type           : AUTOMATION
   WindowId       : mw-0c50858d01EXAMPLE
   WindowTaskId   : 4f7ca192-7e9a-40fe-9192-5cb15EXAMPLE
   ```

------

# Systems Manager Automation 작업 참조
<a name="automation-actions"></a>

이 참조는 Automation 실행서에서 지정할 수 있는 Automation 작업을 설명합니다. Automation은 AWS Systems Manager의 도구입니다. 이러한 작업은 다른 유형의 Systems Manager(SSM) 문서에는 사용할 수 없습니다. 다른 유형의 SSM 문서용 플러그인에 대한 자세한 내용은 [Command 문서 플러그인 참조](documents-command-ssm-plugin-reference.md) 섹션을 참조하세요.

Systems Manager Automation은 Automation 실행서에 정의된 단계를 실행합니다. 각 단계는 특정 작업과 관련되어 있습니다. 작업은 해당 단계의 입력, 동작 및 출력을 결정합니다. 단계는 실행서의 `mainSteps` 섹션에 정의됩니다.

작업 또는 단계의 출력은 지정할 필요가 없습니다. 출력은 단계와 관련된 작업에 의해 미리 결정되어 있습니다. 실행서에 단계 입력을 지정할 때 이전 단계로부터 하나 이상의 출력을 참조할 수 있습니다. 예를 들어 후속 `aws:runCommand` 작업에 `aws:runInstances` 출력을 사용 가능하게 할 수 있습니다. 또한 실행서의 `Output` 섹션에서 이전 단계의 출력을 참조할 수도 있습니다.

**중요**  
AWS Identity and Access Management(IAM) 서비스 역할을 사용하여 다른 서비스를 호출하는 자동화 워크플로를 실행하는 경우 해당 서비스 역할이 다른 서비스를 호출할 권한이 있도록 구성되어야 합니다. 이 요구 사항은 `AWS-ConfigureS3BucketLogging`, `AWS-CreateDynamoDBBackup`, `AWS-RestartEC2Instance` 실행서 등의 모든 AWS Automation 실행서(`AWS-*` 실행서)에 적용됩니다. 또한 다른 서비스를 호출하는 작업을 사용하여 다른 AWS 서비스을(를) 호출하는 사용자 정의 Automation 실행서를 생성하는 경우에도 이 요구 사항이 항상 적용됩니다. 예를 들어 `aws:executeAwsApi`, `aws:createStack` 또는 `aws:copyImage` 작업을 사용하는 경우 이러한 서비스를 호출할 수 있는 권한을 포함하여 서비스 역할을 구성합니다. 역할에 IAM 인라인 정책을 추가하여 다른 AWS 서비스에 대한 권한을 부여할 수 있습니다. 자세한 내용은 [(선택 사항) 다른 AWS 서비스를 간접적으로 호출할 Automation 인라인 정책과 고객 관리형 정책 추가](automation-setup-iam.md#add-inline-policy) 섹션을 참조하세요.

**Topics**
+ [

## 모든 작업에서 공유하는 속성
](#automation-common)
+ [

# `aws:approve` - 수동 승인을 위해 자동화 일시 중지
](automation-action-approve.md)
+ [

# `aws:assertAwsResourceProperty` - AWS 리소스 상태 또는 이벤트 상태 어설션
](automation-action-assertAwsResourceProperty.md)
+ [

# `aws:branch` - 조건부 자동화 단계 실행
](automation-action-branch.md)
+ [

# `aws:changeInstanceState` - 인스턴스 상태 변경 또는 어설션
](automation-action-changestate.md)
+ [

# `aws:copyImage` - Amazon Machine Image 복사 또는 암호화
](automation-action-copyimage.md)
+ [

# `aws:createImage` - Amazon Machine Image 생성
](automation-action-create.md)
+ [

# `aws:createStack` - CloudFormation 스택 생성
](automation-action-createstack.md)
+ [

# `aws:createTags` - AWS 리소스에 대한 태그 생성
](automation-action-createtag.md)
+ [

# `aws:deleteImage` - Amazon Machine Image 삭제
](automation-action-delete.md)
+ [

# `aws:deleteStack` - CloudFormation 스택 삭제
](automation-action-deletestack.md)
+ [

# `aws:executeAutomation` - 또 다른 자동화 실행
](automation-action-executeAutomation.md)
+ [

# `aws:executeAwsApi` - AWS API 작업 호출 및 실행
](automation-action-executeAwsApi.md)
+ [

# `aws:executeScript` - 스크립트 실행
](automation-action-executeScript.md)
+ [

# `aws:executeStateMachine` - AWS Step Functions 상태 시스템을 실행합니다.
](automation-action-executeStateMachine.md)
+ [

# `aws:invokeWebhook` - Automation 웹후크 통합 호출
](invoke-webhook.md)
+ [

# `aws:invokeLambdaFunction` - AWS Lambda 함수 호출
](automation-action-lamb.md)
+ [

# `aws:loop`- 자동화의 여러 단계를 반복
](automation-action-loop.md)
+ [

# `aws:pause` - 자동화 일시 중지
](automation-action-pause.md)
+ [

# `aws:runCommand` - 관리형 인스턴스에서 명령 실행
](automation-action-runcommand.md)
+ [

# `aws:runInstances` - Amazon EC2 인스턴스 시작
](automation-action-runinstance.md)
+ [

# `aws:sleep` - 자동화 지연
](automation-action-sleep.md)
+ [

# `aws:updateVariable` - 런북 변수 값을 업데이트
](automation-action-update-variable.md)
+ [

# `aws:waitForAwsResourceProperty` - AWS 리소스 속성 대기
](automation-action-waitForAwsResourceProperty.md)
+ [

# Automation 시스템 변수
](automation-variables.md)

## 모든 작업에서 공유하는 속성
<a name="automation-common"></a>

공통 속성은 모든 작업에서 발견되는 파라미터 또는 옵션입니다. 일부 옵션은 단계가 완료될 때까지 기다리는 시간, 단계가 실패할 경우 수행할 작업 등과 같은 단계에 대한 동작을 정의합니다. 다음은 모든 작업에 공통적인 속성입니다.

[description](#descriptProp)  
런북 또는 단계의 용도를 설명하려고 제공하는 정보입니다.  
유형: 문자열  
필수 여부: 아니요

[name](#nameProp)  
실행서에 있는 모든 단계 이름을 통틀어 고유해야 하는 식별자.  
유형: 문자열  
허용 패턴: [a-zA-Z0-9\$1]\$1\$1  
필수 여부: 예

[action](#actProp)  
이 단계에서 실행해야 할 작업의 이름입니다. [`aws:runCommand` - 관리형 인스턴스에서 명령 실행](automation-action-runcommand.md)는 여기에서 지정할 수 있는 작업의 예입니다. 이 문서는 사용 가능한 모든 작업에 대한 세부 정보를 제공합니다.  
유형: 문자열  
필수 항목 여부: 예

[maxAttempts](#maxProp)  
단계가 실패할 경우 재시도해야 하는 횟수. 지정된 값이 1보다 크면 모든 재시도가 실패할 때까지 해당 단계는 실패한 것으로 간주되지 않습니다. 기본값은 1입니다.  
유형: 정수  
필수 여부: 아니요

[timeoutSeconds](#timeProp)  
단계에 대한 시간 제한 값. 시간 제한에 도달했지만 `maxAttempts` 값이 1보다 큰 경우 단계는 모든 재시도 횟수가 시도될 때까지 시간 초과된 것으로 간주되지 않습니다.  
유형: 정수  
필수 여부: 아니요

[onFailure](#failProp)  
실패 시 자동화가 중지되어야 하는지, 계속되어야 하는지 또는 다른 단계로 이동해야 하는지를 나타냅니다. 이 옵션의 기본값은 중단입니다.  
유형: 문자열  
유효 값: 중단 \$1 계속 \$1 단계:*step\$1name*  
필수 여부: 아니요

[onCancel](#canProp)  
사용자가 자동화를 취소하는 경우 자동화가 이동해야 하는 단계를 나타냅니다. Automation은 최대 2분 동안 취소 워크플로를 실행합니다.  
유형: 문자열  
유효 값: 중단 \$1 단계:*step\$1name*  
필수 여부: 아니요  
`onCancel` 속성은 다음 작업으로 이동을 지원하지 않습니다.  
+ `aws:approve`
+ `aws:copyImage`
+ `aws:createImage`
+ `aws:createStack`
+ `aws:createTags`
+ `aws:loop`
+ `aws:pause`
+ `aws:runInstances`
+ `aws:sleep`

[isEnd](#endProp)  
이 옵션은 특정 단계 종료 시 자동화를 중지합니다. 단계가 실패하거나 성공한 경우 자동화가 중지됩니다. 기본값은 false입니다.  
유형: Boolean  
유효한 값: true \$1 false  
필수 여부: 아니요

[nextStep](#nextProp)  
한 단계를 성공적으로 완료한 후 다음에 처리할 자동화의 단계를 지정합니다.  
유형: 문자열  
필수 여부: 아니요

[isCritical](#critProp)  
자동화의 성공적 완료에 대해 단계를 심각으로 지정합니다. 이 지정이 있는 단계가 실패하면 자동화는 자동화의 최종 상태를 실패로 보고합니다. 이 속성은 단계에서 명시적으로 정의하는 경우에만 평가됩니다. 단계에서 `onFailure` 속성이 `Continue`로 설정되면 기본값은 false입니다. 그렇지 않으면 이 옵션의 기본값은 true입니다.  
유형: 부울  
유효한 값: true \$1 false  
필수 여부: 아니요

[inputs](#inProp)  
작업에 특정한 속성.  
유형: 맵  
필수 여부: 예

### 예제
<a name="automation-demo"></a>

```
---
description: "Custom Automation Example"
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 run this runbook."
    default: ''
  InstanceId:
      type: String
      description: "(Required) The Instance Id whose root EBS volume you want to restore the latest Snapshot."
      default: ''
mainSteps:
- name: getInstanceDetails
  action: aws:executeAwsApi
  onFailure: Abort
  inputs:
    Service: ec2
    Api: DescribeInstances
    InstanceIds:
    - "{{ InstanceId }}"
  outputs:
    - Name: availabilityZone
      Selector: "$.Reservations[0].Instances[0].Placement.AvailabilityZone"
      Type: String
    - Name: rootDeviceName
      Selector: "$.Reservations[0].Instances[0].RootDeviceName"
      Type: String
  nextStep: getRootVolumeId
- name: getRootVolumeId
  action: aws:executeAwsApi
  maxAttempts: 3
  onFailure: Abort
  inputs:
    Service: ec2
    Api: DescribeVolumes
    Filters:
    -  Name: attachment.device
       Values: ["{{ getInstanceDetails.rootDeviceName }}"]
    -  Name: attachment.instance-id
       Values: ["{{ InstanceId }}"]
  outputs:
    - Name: rootVolumeId
      Selector: "$.Volumes[0].VolumeId"
      Type: String
  nextStep: getSnapshotsByStartTime
- name: getSnapshotsByStartTime
  action: aws:executeScript
  timeoutSeconds: 45
  onFailure: Abort
  inputs:
    Runtime: python3.8
    Handler: getSnapshotsByStartTime
    InputPayload:
      rootVolumeId : "{{ getRootVolumeId.rootVolumeId }}"
    Script: |-
      def getSnapshotsByStartTime(events,context):
        import boto3

        #Initialize client
        ec2 = boto3.client('ec2')
        rootVolumeId = events['rootVolumeId']
        snapshotsQuery = ec2.describe_snapshots(
          Filters=[
            {
              "Name": "volume-id",
              "Values": [rootVolumeId]
            }
          ]
        )
        if not snapshotsQuery['Snapshots']:
          noSnapshotFoundString = "NoSnapshotFound"
          return { 'noSnapshotFound' : noSnapshotFoundString }
        else:
          jsonSnapshots = snapshotsQuery['Snapshots']
          sortedSnapshots = sorted(jsonSnapshots, key=lambda k: k['StartTime'], reverse=True)
          latestSortedSnapshotId = sortedSnapshots[0]['SnapshotId']
          return { 'latestSnapshotId' : latestSortedSnapshotId }
  outputs:
  - Name: Payload
    Selector: $.Payload
    Type: StringMap
  - Name: latestSnapshotId
    Selector: $.Payload.latestSnapshotId
    Type: String
  - Name: noSnapshotFound
    Selector: $.Payload.noSnapshotFound
    Type: String 
  nextStep: branchFromResults
- name: branchFromResults
  action: aws:branch
  onFailure: Abort
  onCancel: step:startInstance
  inputs:
    Choices:
    - NextStep: createNewRootVolumeFromSnapshot
      Not:
        Variable: "{{ getSnapshotsByStartTime.noSnapshotFound }}"
        StringEquals: "NoSnapshotFound"
  isEnd: true
- name: createNewRootVolumeFromSnapshot
  action: aws:executeAwsApi
  onFailure: Abort
  inputs:
    Service: ec2
    Api: CreateVolume
    AvailabilityZone: "{{ getInstanceDetails.availabilityZone }}"
    SnapshotId: "{{ getSnapshotsByStartTime.latestSnapshotId }}"
  outputs:
    - Name: newRootVolumeId
      Selector: "$.VolumeId"
      Type: String
  nextStep: stopInstance
- name: stopInstance
  action: aws:executeAwsApi
  onFailure: Abort
  inputs:
    Service: ec2
    Api: StopInstances
    InstanceIds:
    - "{{ InstanceId }}"
  nextStep: verifyVolumeAvailability
- name: verifyVolumeAvailability
  action: aws:waitForAwsResourceProperty
  timeoutSeconds: 120
  inputs:
    Service: ec2
    Api: DescribeVolumes
    VolumeIds:
    - "{{ createNewRootVolumeFromSnapshot.newRootVolumeId }}"
    PropertySelector: "$.Volumes[0].State"
    DesiredValues:
    - "available"
  nextStep: verifyInstanceStopped
- name: verifyInstanceStopped
  action: aws:waitForAwsResourceProperty
  timeoutSeconds: 120
  inputs:
    Service: ec2
    Api: DescribeInstances
    InstanceIds:
    - "{{ InstanceId }}"
    PropertySelector: "$.Reservations[0].Instances[0].State.Name"
    DesiredValues:
    - "stopped"
  nextStep: detachRootVolume
- name: detachRootVolume
  action: aws:executeAwsApi
  onFailure: Abort
  isCritical: true
  inputs:
    Service: ec2
    Api: DetachVolume
    VolumeId: "{{ getRootVolumeId.rootVolumeId }}"
  nextStep: verifyRootVolumeDetached
- name: verifyRootVolumeDetached
  action: aws:waitForAwsResourceProperty
  timeoutSeconds: 30
  inputs:
    Service: ec2
    Api: DescribeVolumes
    VolumeIds:
    - "{{ getRootVolumeId.rootVolumeId }}"
    PropertySelector: "$.Volumes[0].State"
    DesiredValues:
    - "available"
  nextStep: attachNewRootVolume
- name: attachNewRootVolume
  action: aws:executeAwsApi
  onFailure: Abort
  inputs:
    Service: ec2
    Api: AttachVolume
    Device: "{{ getInstanceDetails.rootDeviceName }}"
    InstanceId: "{{ InstanceId }}"
    VolumeId: "{{ createNewRootVolumeFromSnapshot.newRootVolumeId }}"
  nextStep: verifyNewRootVolumeAttached
- name: verifyNewRootVolumeAttached
  action: aws:waitForAwsResourceProperty
  timeoutSeconds: 30
  inputs:
    Service: ec2
    Api: DescribeVolumes
    VolumeIds:
    - "{{ createNewRootVolumeFromSnapshot.newRootVolumeId }}"
    PropertySelector: "$.Volumes[0].Attachments[0].State"
    DesiredValues:
    - "attached"
  nextStep: startInstance
- name: startInstance
  action: aws:executeAwsApi
  onFailure: Abort
  inputs:
    Service: ec2
    Api: StartInstances
    InstanceIds:
    - "{{ InstanceId }}"
```

# `aws:approve` - 수동 승인을 위해 자동화 일시 중지
<a name="automation-action-approve"></a>

지정된 보안 주체가 작업을 승인하거나 거부할 때까지 자동화를 일시 중지합니다. 필요한 승인 횟수에 도달하면 자동화가 다시 시작됩니다. 런북의 `mainSteps` 섹션에 승인 단계를 삽입할 수 있습니다.

**참고**  
이 작업은 다중 계정 및 리전 자동화를 지원하지 않습니다. 이 작업에 대한 기본 제한 시간은 7일(604800초)이고 최대 값은 30일(2592000초)입니다. `aws:approve` 단계에서 `timeoutSeconds` 파라미터를 지정하여 제한 시간을 제한 또는 연장할 수 있습니다.

다음 예에서 `aws:approve` 작업은 승인자 중 한 명이 자동화를 승인하거나 거부할 때까지 자동화를 일시 중지합니다. 승인하면 자동화는 간단한 PowerShell 명령을 실행합니다.

------
#### [ YAML ]

```
---
description: RunInstancesDemo1
schemaVersion: '0.3'
assumeRole: "{{ assumeRole }}"
parameters:
  assumeRole:
    type: String
  message:
    type: String
mainSteps:
- name: approve
  action: aws:approve
  timeoutSeconds: 1000
  onFailure: Abort
  inputs:
    NotificationArn: arn:aws:sns:us-east-2:12345678901:AutomationApproval
    Message: "{{ message }}"
    MinRequiredApprovals: 1
    Approvers:
    - arn:aws:iam::12345678901:user/AWS-User-1
- name: run
  action: aws:runCommand
  inputs:
    InstanceIds:
    - i-1a2b3c4d5e6f7g
    DocumentName: AWS-RunPowerShellScript
    Parameters:
      commands:
      - date
```

------
#### [ JSON ]

```
{
   "description":"RunInstancesDemo1",
   "schemaVersion":"0.3",
   "assumeRole":"{{ assumeRole }}",
   "parameters":{
      "assumeRole":{
         "type":"String"
      },
      "message":{
         "type":"String"
      }
   },
   "mainSteps":[
      {
         "name":"approve",
         "action":"aws:approve",
         "timeoutSeconds":1000,
         "onFailure":"Abort",
         "inputs":{
            "NotificationArn":"arn:aws:sns:us-east-2:12345678901:AutomationApproval",
            "Message":"{{ message }}",
            "MinRequiredApprovals":1,
            "Approvers":[
               "arn:aws:iam::12345678901:user/AWS-User-1"
            ]
         }
      },
      {
         "name":"run",
         "action":"aws:runCommand",
         "inputs":{
            "InstanceIds":[
               "i-1a2b3c4d5e6f7g"
            ],
            "DocumentName":"AWS-RunPowerShellScript",
            "Parameters":{
               "commands":[
                  "date"
               ]
            }
         }
      }
   ]
}
```

------

콘솔에서 승인을 기다리는 자동화를 승인 또는 거부할 수 있습니다.

**대기 중인 자동화를 승인하거나 거부하려면**

1. [https://console.aws.amazon.com/systems-manager/](https://console.aws.amazon.com/systems-manager/)에서 AWS Systems Manager 콘솔을 엽니다.

1. 왼쪽 탐색 창에서 **Automation**을 선택합니다.

1. **대기 중** 상태와 함께 자동화 옆의 옵션을 선택합니다.  
![\[자동화 승인/거부 페이지에 액세스\]](http://docs.aws.amazon.com/ko_kr/systems-manager/latest/userguide/images/automation-approve-action-aws.png)

1. **승인/거부**를 선택합니다.

1. 자동화의 세부 정보를 검토합니다.

1. **승인** 또는 **거부**를 선택하고 필요에 따라 설명을 입력한 후 **제출**을 선택합니다.

**입력 예제**

------
#### [ YAML ]

```
NotificationArn: arn:aws:sns:us-west-1:12345678901:Automation-ApprovalRequest
Message: Please approve this step of the Automation.
MinRequiredApprovals: 3
Approvers:
- IamUser1
- IamUser2
- arn:aws:iam::12345678901:user/IamUser3
- arn:aws:iam::12345678901:role/IamRole
```

------
#### [ JSON ]

```
{
   "NotificationArn":"arn:aws:sns:us-west-1:12345678901:Automation-ApprovalRequest",
   "Message":"Please approve this step of the Automation.",
   "MinRequiredApprovals":3,
   "Approvers":[
      "IamUser1",
      "IamUser2",
      "arn:aws:iam::12345678901:user/IamUser3",
      "arn:aws:iam::12345678901:role/IamRole"
   ]
}
```

------

NotificationArn  
Automation 승인을 위한 Amazon Simple Notification Service(Amazon SNS) 주제의 Amazon 리소스 이름(ARN)입니다. 실행서에서 `aws:approve` 단계를 지정하면 보안 주체가 Automation 단계를 승인하거나 거부해야 한다고 알려주는 메시지가 이 주제에 전송됩니다. Amazon SNS 주제의 제목에는 "Automation"을 접두사로 지정해야 합니다.  
유형: 문자열  
필수 항목 여부: 아니요

Message  
승인 요청을 전송할 때 Amazon SNS 주제에 포함할 정보입니다. 최대 메시지 길이는 4,096자입니다.  
유형: 문자열  
필수 여부: 아니요

MinRequiredApprovals  
자동화를 다시 시작하는 데 필요한 최소 승인 횟수입니다. 값을 지정하지 않으면 기본값 1이 사용됩니다. 이 파라미터의 값은 양수여야 합니다. 이 파라미터의 값은 `Approvers` 파라미터에 정의된 승인자 수를 초과할 수 없습니다.  
유형: 정수  
필수 여부: 아니요

승인자  
작업을 승인하거나 거부할 수 있는 AWS 인증 보안 주체의 목록입니다. 최대 승인자자 수는 10명입니다. 다음 형식을 사용하여 보안 주체를 지정할 수 있습니다.  
+ 사용자 이름
+ 사용자 ARN
+ IAM 역할 ARN
+ IAM 수임 역할 ARN
유형: StringList  
필수 여부: 예

EnhancedApprovals  
이 입력은 Change Manager 템플릿에서만 사용됩니다. 작업을 승인하거나 거부할 수 있는 AWS의 인증된 보안 주체, IAM 보안 주체 유형, 최소 승인자 수 목록. 다음은 예제입니다.  

```
schemaVersion: "0.3"
emergencyChange: false
autoApprovable: false
mainSteps:
    - name: ApproveAction1
    action: aws:approve
    timeoutSeconds: 604800
    inputs:
        Message: Please approve this change request
        MinRequiredApprovals: 3
        EnhancedApprovals:
        Approvers:
            - approver: John Stiles
            type: IamUser
            minRequiredApprovals: 0
            - approver: Ana Carolina Silva
            type: IamUser
            minRequiredApprovals: 0
            - approver: GroupOfThree
            type: IamGroup
            minRequiredApprovals: 0
            - approver: RoleOfTen
            type: IamRole
            minRequiredApprovals: 0
```
유형: StringList  
필수 여부: 예

**출력**

ApprovalStatus  
단계의 승인 상태입니다. 상태는 Approved, Rejected, Waiting 중 하나일 수 있습니다. Waiting은 승인자의 입력을 대기 중임을 나타냅니다.  
유형: 문자열

ApproverDecisions  
각 승인자의 승인 결정을 포함하는 JSON 맵입니다.  
유형: MapList

# `aws:assertAwsResourceProperty` - AWS 리소스 상태 또는 이벤트 상태 어설션
<a name="automation-action-assertAwsResourceProperty"></a>

`aws:assertAwsResourceProperty` 작업은 특정 Automation 단계에 대해 특정 리소스 상태 또는 이벤트 상태를 어설션할 수 있게 합니다.

**참고**  
`aws:assertAwsResourceProperty` 작업은 자동 스로틀링 재시도를 지원합니다. 자세한 내용은 [스로틀링된 작업에 대한 자동 재시도 구성](automation-throttling-retry.md) 섹션을 참조하세요.

이 작업을 사용하는 방법에 관한 자세한 내용은 [추가 런북 예제](automation-document-examples.md) 섹션을 참조하세요.

**Input**  
입력은 선택하는 API 작업에 의해 정의됩니다.

------
#### [ YAML ]

```
action: aws:assertAwsResourceProperty
inputs:
  Service: The official namespace of the service
  Api: The API operation or method name
  API operation inputs or parameters: A value
  PropertySelector: Response object
  DesiredValues:
  - Desired property values
```

------
#### [ JSON ]

```
{
  "action": "aws:assertAwsResourceProperty",
  "inputs": {
    "Service":"The official namespace of the service",
    "Api":"The API operation or method name",
    "API operation inputs or parameters":"A value",
    "PropertySelector": "Response object",
    "DesiredValues": [
      "Desired property values"
    ]
  }
}
```

------

서비스  
실행하려는 API 작업을 포함하는 AWS 서비스 네임스페이스입니다. 예를 들면 Systems Manager의 네임스페이스는 `ssm`입니다. Amazon EC2의 네임스페이스는 `ec2`입니다. *AWS CLI 명령 참조*의 [사용 가능한 서비스](https://docs.aws.amazon.com/cli/latest/reference/#available-services) 섹션에서 지원되는 AWS 서비스 네임스페이스 목록을 볼 수 있습니다.  
유형: 문자열  
필수 항목 여부: 예

Api  
실행할 API 작업의 이름입니다. 다음 [[서비스 참조(Services Reference)](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/index.html)] 페이지의 왼쪽 탐색 영역에서 서비스를 선택하여 API 작업(메서드라고도 함)을 볼 수 있습니다. 호출할 서비스에 대한 **클라이언트** 섹션에서 메서드를 선택합니다. 예를 들어 Amazon Relational Database Service(Amazon RDS)에 대한 모든 API 작업(메서드)이 [Amazon RDS 메서드](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/rds.html) 페이지에 나열됩니다.  
유형: 문자열  
필수 항목 여부: 예

API 작업 입력  
하나 이상의 API 작업 입력입니다. 다음 [서비스 참조](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/index.html) 페이지의 왼쪽 탐색 영역에서 서비스를 선택하여 사용할 수 있는 입력(파라미터)을 볼 수 있습니다. 호출할 서비스에 대한 **클라이언트** 섹션에서 메서드를 선택합니다. 예를 들어 Amazon RDS에 대한 모든 메서드는 [Amazon RDS 메서드](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/rds.html) 페이지에 나열됩니다. [describe\$1db\$1instances](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/rds.html#RDS.Client.describe_db_instances) 메서드를 선택하고 아래로 스크롤하여 **DBInstanceIdentifier**, **Name** 및 **Values** 같은 사용할 수 있는 파라미터를 볼 수 있습니다. 두 개 이상의 입력을 지정하려면 다음 형식을 사용합니다.  

```
inputs:
  Service: The official namespace of the service
  Api: The API operation name
  API input 1: A value
  API Input 2: A value
  API Input 3: A value
```

```
"inputs":{
      "Service":"The official namespace of the service",
      "Api":"The API operation name",
      "API input 1":"A value",
      "API Input 2":"A value",
      "API Input 3":"A value"
}
```
형식: 선택한 API 작업에 의해 결정됨  
필수 여부: 예

PropertySelector  
응답 객체의 특정 속성에 대한 JSONPath입니다. 다음 [서비스 참조](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/index.html) 페이지의 왼쪽 탐색 영역에서 서비스를 선택하여 응답 객체를 볼 수 있습니다. 호출할 서비스에 대한 **클라이언트** 섹션에서 메서드를 선택합니다. 예를 들어 Amazon RDS에 대한 모든 메서드는 [Amazon RDS 메서드](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/rds.html) 페이지에 나열됩니다. [describe\$1db\$1instances](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/rds.html#RDS.Client.describe_db_instances) 메서드를 선택하고 **Response Structure(응답 구조)** 섹션이 있는 아래쪽으로 스크롤합니다. **DBInstances**가 응답 객체로 나열됩니다.  
유형: 문자열  
필수 항목 여부: 예

DesiredValues  
필요한 상태 또는 자동화를 계속 진행하기 위해 충족되어야 할 상태입니다. 부울 값을 지정할 경우 True 또는 False 같은 대문자를 사용해야 합니다.  
유형: StringList  
필수 여부: 예

# `aws:branch` - 조건부 자동화 단계 실행
<a name="automation-action-branch"></a>

`aws:branch` 작업을 통해 한 단계에서 여러 선택 항목을 평가한 다음 평가 결과에 따라 실행서의 다른 단계로 이동하는 동적 자동화를 생성할 수 있습니다.

단계에 대한 `aws:branch` 작업을 지정할 경우 해당 자동화에서 평가해야 하는 `Choices`를 지정할 수 있습니다. `Choices`는 실행서의 `Parameters` 섹션에 지정한 값이나 이전 단계의 출력으로 생성된 동적 값에 기초할 수 있습니다. 이 자동화는 부울 식을 사용하여 각 선택을 평가합니다. 첫 번째 선택 항목이 true이면 이 자동화는 해당 선택 항목에 지정된 단계로 이동합니다. 첫 번째 선택 항목이 false이면 이 자동화는 다음 선택 항목을 평가합니다. 이 자동화는 true 선택 항목을 처리할 때까지 각 선택 항목을 계속 평가합니다. 그런 다음 이 자동화는 true인 선택 항목에 지정된 단계로 이동합니다.

값이 true인 선택 항목이 없을 경우 이 자동화는 단계에 `default` 값이 포함되었는지 검사합니다. default 값은 선택 항목 중에 true인 항목이 없는 경우 자동화에서 이동해야 하는 단계를 정의합니다. 단계에 대한 `default` 값이 지정되지 않은 경우 자동화는 실행서의 다음 단계를 처리합니다.

`aws:branch` 작업은 `And`, `Not` 및 `Or` 연산자의 조합을 사용한 복합 선택 항목 평가를 지원합니다. 예제 실행서와 다양한 연산자를 사용하는 예제 등 `aws:branch`를 사용하는 방법에 대한 자세한 내용은 [런북에서 조건문 사용](automation-branch-condition.md) 섹션을 참조하세요.

**Input**  
단계에서 하나 이상의 `Choices`를 지정합니다. `Choices`는 실행서의 `Parameters` 섹션에 지정한 값이나 이전 단계의 출력으로 생성된 동적 값에 기초할 수 있습니다. 다음은 파라미터를 평가하는 YAML 샘플입니다.

```
mainSteps:
- name: chooseOS
  action: aws:branch
  inputs:
    Choices:
    - NextStep: runWindowsCommand
      Variable: "{{Name of a parameter defined in the Parameters section. For example: OS_name}}"
      StringEquals: windows
    - NextStep: runLinuxCommand
      Variable: "{{Name of a parameter defined in the Parameters section. For example: OS_name}}"
      StringEquals: linux
    Default:
      sleep3
```

다음은 이전 단계의 출력을 평가하는 YAML 샘플입니다.

```
mainSteps:
- name: chooseOS
  action: aws:branch
  inputs:
    Choices:
    - NextStep: runPowerShellCommand
      Variable: "{{Name of a response object. For example: GetInstance.platform}}"
      StringEquals: Windows
    - NextStep: runShellCommand
      Variable: "{{Name of a response object. For example: GetInstance.platform}}"
      StringEquals: Linux
    Default:
      sleep3
```

Choices  
자동화에서 처리할 다음 단계를 결정할 때 평가해야 하는 하나 이상의 표현식입니다. Choices는 부울 식을 사용하여 평가됩니다. 각 선택 항목은 다음 옵션을 정의해야 합니다.  
+ **NextStep**: 지정된 선택 항목이 true인 경우 처리할 실행서의 다음 단계.
+ **Variable**: 실행서의 `Parameters` 섹션에 정의된 파라미터의 이름을 지정합니다. 또는 실행서의 이전 단계에서 얻은 출력 객체를 지정합니다. `aws:branch`용 변수 생성에 대한 자세한 내용은 [출력 변수 생성 정보](automation-branch-condition.md#branch-action-output) 섹션을 참조하세요.
+ **Operation**: 선택 항목(choice)을 평가하는 데 사용되는 기준입니다. `aws:branch` 작업에서는 다음 연산을 지원합니다.

**문자열 연산**
  + StringEquals
  + EqualsIgnoreCase
  + StartsWith
  + EndsWith
  + 포함

**수치 연산**
  + NumericEquals
  + NumericGreater
  + NumericLesser
  + NumericGreaterOrEquals
  + NumericLesser
  + NumericLesserOrEquals

**부울 연산**
  + BooleanEquals
**중요**  
실행서를 생성하면 시스템에서 실행서의 각 작업을 검증합니다. 작업이 지원되지 않는 경우 실행서를 생성할 때 오류가 발생합니다.

기본값  
`Choices` 중에 true인 항목이 없는 경우 자동화에서 이동해야 할 단계의 이름입니다.  
유형: 문자열  
필수 여부: 아니요

**참고**  
`aws:branch` 작업은 `And`, `Or` 및 `Not` 연산자를 지원합니다. 연산자를 사용하는 `aws:branch`의 예는 [런북에서 조건문 사용](automation-branch-condition.md) 섹션을 참조하세요.

# `aws:changeInstanceState` - 인스턴스 상태 변경 또는 어설션
<a name="automation-action-changestate"></a>

인스턴스의 상태를 변경하거나 어설션합니다.

이 작업은 어설션 모드에서 사용될 수 있습니다(API를 실행하여 상태를 변경하는 것이 아니라 인스턴스가 원하는 상태에 있는지 확인함). 어설션 모드를 사용하려면 `CheckStateOnly` 파라미터를 true로 설정합니다. 이 모드는 배경에서 장시간 실행할 수 있는 비동기식 명령인 Sysprep 명령을 Windows Server에서 실행할 때 유용합니다. Amazon Machine Image(AMI)를 생성하기 전에 인스턴스가 중지되게 할 수 있습니다.

**참고**  
이 작업의 기본 제한 시간 값은 3,600초(1시간)입니다. `aws:changeInstanceState` 단계에서 `timeoutSeconds` 파라미터를 지정하여 제한 시간을 제한 또는 연장할 수 있습니다.

**참고**  
`aws:changeInstanceState` 작업은 자동 스로틀링 재시도를 지원합니다. 자세한 내용은 [스로틀링된 작업에 대한 자동 재시도 구성](automation-throttling-retry.md) 섹션을 참조하세요.

**입력**

------
#### [ YAML ]

```
name: stopMyInstance
action: aws:changeInstanceState
maxAttempts: 3
timeoutSeconds: 3600
onFailure: Abort
inputs:
  InstanceIds:
  - i-1234567890abcdef0
  CheckStateOnly: true
  DesiredState: stopped
```

------
#### [ JSON ]

```
{
    "name":"stopMyInstance",
    "action": "aws:changeInstanceState",
    "maxAttempts": 3,
    "timeoutSeconds": 3600,
    "onFailure": "Abort",
    "inputs": {
        "InstanceIds": ["i-1234567890abcdef0"],
        "CheckStateOnly": true,
        "DesiredState": "stopped"
    }
}
```

------

InstanceIds  
인스턴스의 ID.  
유형: StringList  
필수 여부: 예

CheckStateOnly  
false인 경우 인스턴스 상태를 원하는 상태로 설정합니다. true인 경우 폴링을 사용하여 원하는 상태를 어설션합니다.  
기본값: `false`  
유형: 부울  
필수 여부: 아니요

DesiredState  
원하는 상태. `running`으로 설정하는 경우 이 작업은 완료하기 전에 Amazon EC2 상태가 `Running`, 인스턴스 상태가 `OK` 그리고 시스템 상태가 `OK`가 될 때까지 기다립니다.  
유형: 문자열  
유효한 값: `running` \$1 `stopped` \$1 `terminated`  
필수 여부: 예

강제  
설정되면 인스턴스가 중지합니다. 인스턴스는 파일 시스템 캐시 또는 파일 시스템 메타데이터를 플러시하지 않습니다. 이 옵션을 사용하는 경우 파일 시스템 확인 및 복구 절차를 수행해야 합니다. 이 옵션은 Windows Server용 EC2 인스턴스에는 권장하지 않습니다.  
유형: 부울  
필수 여부: 아니요

AdditionalInfo  
예약.  
유형: 문자열  
필수 여부: 아니요

**출력**  
없음

# `aws:copyImage` - Amazon Machine Image 복사 또는 암호화
<a name="automation-action-copyimage"></a>

모든 AWS 리전의 Amazon Machine Image(AMI)를 현재 리전에 복사합니다. 이 작업은 새 AMI를 암호화할 수도 있습니다.

**참고**  
`aws:copyImage` 작업은 자동 스로틀링 재시도를 지원합니다. 자세한 내용은 [스로틀링된 작업에 대한 자동 재시도 구성](automation-throttling-retry.md) 섹션을 참조하세요.

**Input**  
이 작업은 대부분의 `CopyImage` 파라미터를 지원합니다. 자세한 내용은 [CopyImage](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CopyImage.html)를 참조하세요.

다음 예에서는 서울 리전의 AMI 복사본을 생성합니다(`SourceImageID`: ami-0fe10819. `SourceRegion`: ap-northeast-2). 새 AMI가 Automation 작업을 시작한 리전에 복사됩니다. `Encrypted` 플래그(옵션)가 `true`로 설정되어 있으므로 복사한 AMI가 암호화됩니다.

------
#### [ YAML ]

```
name: createEncryptedCopy
action: aws:copyImage
maxAttempts: 3
onFailure: Abort
inputs:
  SourceImageId: ami-0fe10819
  SourceRegion: ap-northeast-2
  ImageName: Encrypted Copy of LAMP base AMI in ap-northeast-2
  Encrypted: true
```

------
#### [ JSON ]

```
{   
    "name": "createEncryptedCopy",
    "action": "aws:copyImage",
    "maxAttempts": 3,
    "onFailure": "Abort",
    "inputs": {
        "SourceImageId": "ami-0fe10819",
        "SourceRegion": "ap-northeast-2",
        "ImageName": "Encrypted Copy of LAMP base AMI in ap-northeast-2",
        "Encrypted": true
    }   
}
```

------

SourceRegion  
원본 AMI가 존재하는 리전입니다.  
유형: 문자열  
필수 항목 여부: 예

SourceImageId  
원본 리전에서 복사할 AMI ID입니다.  
유형: 문자열  
필수 항목 여부: 예

ImageName  
새 이미지의 이름입니다.  
유형: 문자열  
필수 항목 여부: 예

ImageDescription  
대상 이미지에 대한 설명입니다.  
유형: 문자열  
필수 여부: 아니요

Encrypted  
대상 AMI를 암호화합니다.  
유형: 부울  
필수 여부: 아니요

KmsKeyId  
복사 작업 중에 이미지의 스냅샷을 암호화할 때 사용할 AWS KMS key의 전체 Amazon 리소스 이름(ARN)입니다. 자세한 내용은 [CopyImage](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/api_copyimage.html)를 참조하세요.  
유형: 문자열  
필수 여부: 아니요

ClientToken  
요청 멱등성을 보장하기 위해 제공하는 고유의 대/소문자 구분 식별자입니다. 자세한 내용은 [CopyImage](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/api_copyimage.html)를 참조하세요.  
유형: 문자열  
필수 여부: 아니요출력

ImageId  
복사한 이미지의 ID입니다.

ImageState  
복사한 이미지의 상태입니다.  
유효한 값: `available` \$1 `pending` \$1 `failed`

# `aws:createImage` - Amazon Machine Image 생성
<a name="automation-action-create"></a>

실행 중이거나 중지 중이거나 중지된 인스턴스에서 Amazon Machine Image(AMI)를 생성하고 `ImageState`가 `available`이 되도록 폴링합니다.

**참고**  
`aws:createImage` 작업은 자동 스로틀링 재시도를 지원합니다. 자세한 내용은 [스로틀링된 작업에 대한 자동 재시도 구성](automation-throttling-retry.md) 섹션을 참조하세요.

**Input**  
이 작업은 다음 `CreateImage` 파라미터를 지원합니다. 자세한 내용은 [CreateImage](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateImage.html)를 참조하세요.

------
#### [ YAML ]

```
name: createMyImage
action: aws:createImage
maxAttempts: 3
onFailure: Abort
inputs:
  InstanceId: i-1234567890abcdef0
  ImageName: AMI Created on{{global:DATE_TIME}}
  NoReboot: true
  ImageDescription: My newly created AMI
```

------
#### [ JSON ]

```
{
    "name": "createMyImage",
    "action": "aws:createImage",
    "maxAttempts": 3,
    "onFailure": "Abort",
    "inputs": {
        "InstanceId": "i-1234567890abcdef0",
        "ImageName": "AMI Created on{{global:DATE_TIME}}",
        "NoReboot": true,
        "ImageDescription": "My newly created AMI"
    }
}
```

------

InstanceId  
인스턴스의 ID  
유형: 문자열  
필수 항목 여부: 예

ImageName  
이미지의 이름입니다.  
유형: 문자열  
필수 항목 여부: 예

ImageDescription  
이미지의 설명.  
유형: 문자열  
필수 여부: 아니요

NoReboot  
부울 리터럴.  
기본적으로 Amazon Elastic Compute Cloud(Amazon EC2)는 이미지를 생성하기 전에 인스턴스를 종료하고 재부팅하려고 시도합니다. [**재부팅 안 함(No Reboot)**] 옵션이 `true`로 설정된 경우 Amazon EC2는 이미지를 생성하기 전에 인스턴스를 종료하지 않습니다. 이 옵션을 사용하는 경우 생성된 이미지의 파일 시스템 무결성을 보장할 수 없습니다.  
인스턴스에서 AMI를 생성한 후 인스턴스가 실행되지 않게 하려면 먼저 [`aws:changeInstanceState` - 인스턴스 상태 변경 또는 어설션](automation-action-changestate.md) 작업을 사용하여 인스턴스를 중지한 다음 [**NoReboot**] 옵션을 `true`로 설정한 상태에서 이 `aws:createImage` 작업을 사용합니다.  
유형: 부울  
필수 여부: 아니요

BlockDeviceMappings  
해당 인스턴스용 블록 디바이스.  
유형: 맵  
필수 여부: 아니요출력

ImageId  
새롭게 생성된 이미지의 ID.  
유형: 문자열

ImageState  
이미지의 현재 상태입니다. 상태가 사용 가능한 경우 이미지가 성공적으로 등록되고 인스턴스를 시작하는 데 사용할 수 있습니다.  
유형: 문자열

# `aws:createStack` - CloudFormation 스택 생성
<a name="automation-action-createstack"></a>

템플릿에서 AWS CloudFormation 스택을 생성합니다.

**참고**  
`aws:createStack` 작업은 자동 스로틀링 재시도를 지원합니다. 자세한 내용은 [스로틀링된 작업에 대한 자동 재시도 구성](automation-throttling-retry.md) 섹션을 참조하세요.

CloudFormation 스택 생성에 대한 추가 정보는 *AWS CloudFormation API Reference*의 [CreateStack](https://docs.aws.amazon.com/AWSCloudFormation/latest/APIReference/API_CreateStack.html)을 참조하세요.

**입력**

------
#### [ YAML ]

```
name: makeStack
action: aws:createStack
maxAttempts: 1
onFailure: Abort
inputs:
  Capabilities:
  - CAPABILITY_IAM
  StackName: myStack
  TemplateURL: http://s3.amazonaws.com/amzn-s3-demo-bucket/myStackTemplate
  TimeoutInMinutes: 5
  Parameters:
    - ParameterKey: LambdaRoleArn
      ParameterValue: "{{LambdaAssumeRole}}"
    - ParameterKey: createdResource
      ParameterValue: createdResource-{{automation:EXECUTION_ID}}
```

------
#### [ JSON ]

```
{
    "name": "makeStack",
    "action": "aws:createStack",
    "maxAttempts": 1,
    "onFailure": "Abort",
    "inputs": {
        "Capabilities": [
            "CAPABILITY_IAM"
        ],
        "StackName": "myStack",
        "TemplateURL": "http://s3.amazonaws.com/amzn-s3-demo-bucket/myStackTemplate",
        "TimeoutInMinutes": 5,
        "Parameters": [
          {
            "ParameterKey": "LambdaRoleArn",
            "ParameterValue": "{{LambdaAssumeRole}}"
          },
          {
            "ParameterKey": "createdResource",
            "ParameterValue": "createdResource-{{automation:EXECUTION_ID}}"
          }
    }
}
```

------

기능  
CloudFormation에서 특정 스택을 생성할 수 있으려면 지정해야 하는 값의 목록입니다. 일부 스택 템플릿은 AWS 계정의 권한에 영향을 줄 수 있는 리소스를 포함합니다. 이러한 스택에서는 이 파라미터를 지정하여 스택의 기능을 명시적으로 확인해야 합니다.  
유효값에는 `CAPABILITY_IAM`, `CAPABILITY_NAMED_IAM` 및 `CAPABILITY_AUTO_EXPAND`이 있습니다.  
**CAPABILITY\$1IAM 및 CAPABILITY\$1NAMED\$1IAM**  
IAM 리소스가 있는 경우 어느 기능이든 지정할 수 있습니다. 사용자 정의 이름을 갖는 IAM 리소스가 있는 경우 `CAPABILITY_NAMED_IAM`을 지정해야 합니다. 이 파라미터를 지정하지 않으면 이 작업은 `InsufficientCapabilities` 오류를 반환합니다. 다음 리소스의 경우 `CAPABILITY_IAM` 또는 `CAPABILITY_NAMED_IAM`을 지정해야 합니다.
+ [https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iam-accesskey.html](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iam-accesskey.html)
+ [https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iam-group.html](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iam-group.html)
+ [https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-iam-instanceprofile.html](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-iam-instanceprofile.html)
+ [https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iam-policy.html](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iam-policy.html)
+ [https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-iam-role.html](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-iam-role.html)
+ [https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iam-user.html](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iam-user.html)
+ [https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iam-addusertogroup.html](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iam-addusertogroup.html)
스택 템플릿에 이러한 리소스가 포함되어 있는 경우, 관련 권한을 모두 검토하고 필요에 따라 권한을 편집하는 것이 좋습니다.  
자세한 내용은 [CloudFormation 템플릿에서 IAM 리소스 승인](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-iam-template.html#capabilities)을 참조하세요.  
**CAPABILITY\$1AUTO\$1EXPAND**  
일부 템플릿에는 매크로가 포함되어 있습니다. 매크로는 템플릿에서 사용자 지정 처리를 수행합니다. 여기에는 찾기 및 바꾸기 작업과 같은 간단한 작업과 전체 템플릿의 광범위한 변환을 위한 모든 방법을 포함할 수 있습니다. 그러므로 사용자는 일반적으로 처리된 템플릿에서 변경 세트를 생성하여 실제로 스택을 생성하기 전에 매크로로 인한 변경 사항을 검토할 수 있습니다. 스택 템플릿에 매크로가 하나 이상 포함되어 있고 변경 세트의 결과 변경 사항을 먼저 검토하지 않고 처리된 템플릿에서 직접 스택을 생성하도록 선택한 경우 이 기능을 확인해야 합니다.
자세한 내용은 *AWS CloudFormation 사용 설명서*의 [템플릿에서 사용자 정의 처리를 수행하는 AWS CloudFormation 매크로 사용](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/template-macros.html)을 참조하세요.  
형식: 문자열 배열  
유효 값: `CAPABILITY_IAM | CAPABILITY_NAMED_IAM | CAPABILITY_AUTO_EXPAND`  
필수 여부: 아니요

ClientRequestToken  
이 CreateStack 요청에 대한 고유 식별자입니다. 이 단계에서 maxAttempts를 1보다 큰 값으로 설정한 경우 이 토큰을 지정하세요. 이 토큰을 지정하면 사용자가 같은 이름으로 새 스택을 생성하려는 것이 아님을 CloudFormation에서 알게 됩니다.  
유형: 문자열  
필수 여부: 아니요  
길이 제약: 최소 길이 1. 최대 길이 128.  
패턴: [a-zA-Z0-9][-a-zA-Z0-9]\$1

DisableRollback  
스택 생성에 실패한 경우 스택의 롤백을 해제하려면 `true`로 설정합니다.  
조건: `DisableRollback` 또는 `OnFailure` 파라미터를 지정할 수 있지만, 둘 다 지정하지 않을 수도 있습니다.  
기본값: `false`  
유형: 부울  
필수 여부: 아니요

NotificationARNs  
스택 관련 이벤트를 게시할 Amazon Simple Notification Service(Amazon SNS) 주제 ARN입니다. Amazon SNS 콘솔([https://console.aws.amazon.com/sns/v3/home](https://console.aws.amazon.com/sns/v3/home))을 사용하여 SNS 주제 ARN을 찾을 수 있습니다.  
형식: 문자열 배열  
배열 멤버: 최대 항목 수 5개.  
필수 여부: 아니요

OnFailure  
스택 생성에 실패한 경우 취할 조치를 결정합니다. `DO_NOTHING`, `ROLLBACK` 또는 `DELETE`를 지정해야 합니다.  
조건: `OnFailure` 또는 `DisableRollback` 파라미터를 지정할 수 있지만, 둘 다 지정하지 않을 수도 있습니다.  
기본값: `ROLLBACK`  
유형: 문자열  
유효한 값:` DO_NOTHING | ROLLBACK | DELETE`  
필수 여부: 아니요

파라미터  
스택에 대한 입력 파라미터를 지정하는 `Parameter` 구조의 목록. 자세한 내용은 [Parameter](https://docs.aws.amazon.com/AWSCloudFormation/latest/APIReference/API_Parameter.html) 데이터 형식을 참조하세요.  
형식: [Parameter](https://docs.aws.amazon.com/AWSCloudFormation/latest/APIReference/API_Parameter.html) 객체 배열   
필수 여부: 아니요

ResourceTypes  
이 스택 생성 작업에 대해 함께 작업할 수 있는 권한을 갖는 템플릿 리소스 유형. 예: `AWS::EC2::Instance`, `AWS::EC2::*` 또는 `Custom::MyCustomInstance`. 템플릿 리소스 유형을 기술하려면 다음 구문을 사용합니다.  
+ 모든 AWS 리소스의 경우:

  ```
  AWS::*
  ```
+ 모든 사용자 지정 리소스의 경우:

  ```
  Custom::*
  ```
+ 특정 사용자 지정 리소스의 경우:

  ```
  Custom::logical_ID
  ```
+ 특정 AWS 서비스에 대한 모든 리소스의 경우:

  ```
  AWS::service_name::*
  ```
+ 특정 AWS 리소스의 경우:

  ```
  AWS::service_name::resource_logical_ID
  ```
리소스 유형 목록에 사용자가 생성 중인 리소스가 포함되어 있지 않으면 스택 생성에 실패합니다. 기본적으로 CloudFormation은 모든 리소스 유형에 권한을 부여합니다. IAM은 IAM 정책의 CloudFormation별 조건 키에 이 파라미터를 사용합니다. 자세한 내용은 [AWS Identity and Access Management을 통한 액세스 제어](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-iam-template.html)를 참조하세요.  
형식: 문자열 배열  
길이 제약: 최소 길이 1. 최대 길이는 256.  
필수 여부: 아니요

RoleARN  
CloudFormation이 스택을 생성하기 위해 수임하는 IAM 역할의 Amazon 리소스 이름(ARN)입니다. CloudFormation은 역할의 자격 증명을 사용하여 사용자를 대신하여 호출합니다. CloudFormation은 스택의 모든 향후 작업에 항상 이 역할을 사용합니다. 사용자에게 스택에서 작업할 수 있는 권한이 있는 경우에는 역할을 전달할 수 있는 권한은 없더라도 CloudFormation에서 이 역할을 사용합니다. 역할이 최소한의 권한을 부여하는지 확인하세요.  
값을 지정하지 않으면 CloudFormation에서는 이전에 스택과 연결된 역할을 사용합니다. 사용 가능한 역할이 없으면 CloudFormation에서는 사용자 자격 증명으로부터 생성되는 임시 세션을 사용합니다.  
유형: 문자열  
길이 제약: 최소 길이는 20. 최대 길이는 2,048.  
필수 여부: 아니요

StackName  
스택과 연결되어 있는 이름. 이름은 스택을 생성하는 리전에서 고유해야 합니다.  
스택 이름에는 영숫자(대소문자 구분)와 하이픈만 사용할 수 있습니다. 영문자로 시작해야 하고 128자 이하여야 합니다.
유형: 문자열  
필수 항목 여부: 예

StackPolicyBody  
스택 정책 본문이 포함된 구조. 자세한 내용은 [스택 리소스에 대한 업데이트 방지](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/protect-stack-resources.html)를 참조하세요.  
조건: `StackPolicyBody` 또는 `StackPolicyURL` 파라미터를 지정할 수 있지만, 둘 다 지정하지 않을 수도 있습니다.  
유형: 문자열  
길이 제약 조건: 최소 길이는 1입니다. 최대 길이는 16384입니다.  
필수 여부: 아니요

StackPolicyURL  
스택 정책이 포함된 파일의 위치. URL은 스택과 동일한 리전의 S3 버킷에 있는 정책을 가리켜야 합니다. 스택 정책에 허용되는 최대 파일 크기는 16KB입니다.  
조건: `StackPolicyBody` 또는 `StackPolicyURL` 파라미터를 지정할 수 있지만, 둘 다 지정하지 않을 수도 있습니다.  
유형: 문자열  
길이 제약: 최소 길이 1. 최대 길이 1350.  
필수 여부: 아니요

Tags  
이 스택과 연결할 키-값 페어. 또한 CloudFormation은 이러한 태그를 해당 스택에 생성된 리소스로 전파합니다. 태그를 최대 10개까지 지정할 수 있습니다.  
형식: [Tag](https://docs.aws.amazon.com/AWSCloudFormation/latest/APIReference/API_Tag.html) 객체 배열   
필수 여부: 아니요

TemplateBody  
최소 길이가 1바이트이고 최대 길이가 51,200바이트인 템플릿 본문이 포함된 구조. 자세한 내용은 [Template Anatomy](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/template-anatomy.html)를 참조하세요.  
조건: `TemplateBody` 또는 `TemplateURL` 파라미터를 지정할 수 있지만, 둘 다 지정하지 않을 수도 있습니다.  
유형: 문자열  
길이 제약: 최소 길이 1.  
필수 여부: 아니요

TemplateURL  
템플릿 본문이 포함된 파일의 위치. URL은 S3 버킷에 있는 템플릿을 가리켜야 합니다. 템플릿에 허용되는 최대 크기는 460,800바이트입니다. 자세한 내용은 [Template Anatomy](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/template-anatomy.html)를 참조하세요.  
조건: `TemplateBody` 또는 `TemplateURL` 파라미터를 지정할 수 있지만, 둘 다 지정하지 않을 수도 있습니다.  
유형: 문자열  
길이 제약: 최소 길이 1. 최대 길이 1024.  
필수 여부: 아니요

TimeoutInMinutes  
스택 상태가 `CREATE_FAILED`가 되기 전에 경과할 수 있는 시간. `DisableRollback`이 설정되지 않거나 `false`로 설정되면 스택은 롤백됩니다.  
타입: 정수  
유효 범위: 최소값 1.  
필수 여부: 아니요

## 출력
<a name="automation-action-createstack-output"></a>

StackId  
스택의 고유 식별자.  
유형: 문자열

StackStatus  
스택의 현재 상태.  
타입: 문자열  
유효 값: `CREATE_IN_PROGRESS | CREATE_FAILED | CREATE_COMPLETE | ROLLBACK_IN_PROGRESS | ROLLBACK_FAILED | ROLLBACK_COMPLETE | DELETE_IN_PROGRESS | DELETE_FAILED | DELETE_COMPLETE | UPDATE_IN_PROGRESS | UPDATE_COMPLETE_CLEANUP_IN_PROGRESS | UPDATE_COMPLETE | UPDATE_ROLLBACK_IN_PROGRESS | UPDATE_ROLLBACK_FAILED | UPDATE_ROLLBACK_COMPLETE_CLEANUP_IN_PROGRESS | UPDATE_ROLLBACK_COMPLETE | REVIEW_IN_PROGRESS`  
필수 여부: 예

StackStatusReason  
스택 상태와 관련된 성공 또는 실패 메시지.  
유형: 문자열  
필수 여부: 아니요  
자세한 내용은 [CreateStack](https://docs.aws.amazon.com/AWSCloudFormation/latest/APIReference/API_CreateStack.html)을 참조하세요.

## 보안 고려 사항
<a name="automation-action-createstack-security"></a>

`aws:createStack` 작업을 사용하려면 먼저 IAM Automation 수임 역할에 다음 정책을 할당해야 합니다. assume role에 대한 자세한 내용은 [작업 1: Automation을 위한 서비스 역할 생성](automation-setup-iam.md#create-service-role) 섹션을 참조하세요.

------
#### [ JSON ]

****  

```
{
   "Version":"2012-10-17",		 	 	 
   "Statement":[
      {
         "Effect":"Allow",
         "Action":[
            "sqs:*",
            "cloudformation:CreateStack",
            "cloudformation:DescribeStacks"
         ],
         "Resource":"*"
      }
   ]
}
```

------

# `aws:createTags` - AWS 리소스에 대한 태그 생성
<a name="automation-action-createtag"></a>

Amazon Elastic Compute Cloud(Amazon EC2) 인스턴스 또는 AWS Systems Manager 관리형 인스턴스에 대한 새 태그를 생성합니다.

**참고**  
`aws:createTags` 작업은 자동 스로틀링 재시도를 지원합니다. 자세한 내용은 [스로틀링된 작업에 대한 자동 재시도 구성](automation-throttling-retry.md) 섹션을 참조하세요.

**Input**  
이 작업은 대부분의 Amazon EC2 `CreateTags` 및 Systems Manager `AddTagsToResource` 파라미터를 지원합니다. 자세한 내용은 [CreateTags](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/api_createtags.html) 및 [AddTagsToResource](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/api_addtagstoresource.html)를 참조하세요.

다음 예에서는 Amazon Machine Image(AMI)와 인스턴스를 특정 부서의 프로덕션 리소스로 태그 지정하는 방법을 보여줍니다.

------
#### [ YAML ]

```
name: createTags
action: aws:createTags
maxAttempts: 3
onFailure: Abort
inputs:
  ResourceType: EC2
  ResourceIds:
  - ami-9a3768fa
  - i-02951acd5111a8169
  Tags:
  - Key: production
    Value: ''
  - Key: department
    Value: devops
```

------
#### [ JSON ]

```
{
    "name": "createTags",
    "action": "aws:createTags",
    "maxAttempts": 3,
    "onFailure": "Abort",
    "inputs": {
        "ResourceType": "EC2",
        "ResourceIds": [
            "ami-9a3768fa",
            "i-02951acd5111a8169"
        ],
        "Tags": [
            {
                "Key": "production",
                "Value": ""
            },
            {
                "Key": "department",
                "Value": "devops"
            }
        ]
    }
}
```

------

ResourceIds  
태그 지정할 리소스의 ID입니다. 리소스 유형이 "EC2"가 아니면 이 필드는 항목을 하나만 포함할 수 있습니다.  
형식: 문자열 목록  
필수 여부: 예

Tags  
리소스와 연결할 태그입니다.  
형식: 맵 목록  
필수 여부: 예

ResourceType  
태그 지정할 리소스의 유형입니다. 제공되지 않은 경우 기본값 "EC2"가 사용됩니다.  
유형: 문자열  
필수 여부: 아니요  
유효한 값: `EC2` \$1 `ManagedInstance` \$1 `MaintenanceWindow` \$1 `Parameter`

**출력**  
없음

# `aws:deleteImage` - Amazon Machine Image 삭제
<a name="automation-action-delete"></a>

지정된 Amazon Machine Image(AMI) 및 관련된 모든 스냅샷을 삭제합니다.

**참고**  
`aws:deleteImage` 작업은 자동 스로틀링 재시도를 지원합니다. 자세한 내용은 [스로틀링된 작업에 대한 자동 재시도 구성](automation-throttling-retry.md) 섹션을 참조하세요.

**Input**  
이 작업은 하나의 파라미터만 지원합니다. 자세한 내용은 [DeregisterImage](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_DeregisterImage.html) and [DeleteSnapshot](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_DeleteSnapshot.html) 문서를 참조하세요.

------
#### [ YAML ]

```
name: deleteMyImage
action: aws:deleteImage
maxAttempts: 3
timeoutSeconds: 180
onFailure: Abort
inputs:
  ImageId: ami-12345678
```

------
#### [ JSON ]

```
{
    "name": "deleteMyImage",
    "action": "aws:deleteImage",
    "maxAttempts": 3,
    "timeoutSeconds": 180,
    "onFailure": "Abort",
    "inputs": {
        "ImageId": "ami-12345678"
    }
}
```

------

ImageId  
삭제되는 이미지의 ID.  
유형: 문자열  
필수 항목 여부: 예

**출력**  
없음

# `aws:deleteStack` - CloudFormation 스택 삭제
<a name="automation-action-deletestack"></a>

AWS CloudFormation 스택을 삭제합니다.

**참고**  
`aws:deleteStack` 작업은 자동 스로틀링 재시도를 지원합니다. 자세한 내용은 [스로틀링된 작업에 대한 자동 재시도 구성](automation-throttling-retry.md) 섹션을 참조하세요.

**입력**

------
#### [ YAML ]

```
name: deleteStack
action: aws:deleteStack
maxAttempts: 1
onFailure: Abort
inputs:
  StackName: "{{stackName}}"
```

------
#### [ JSON ]

```
{
   "name":"deleteStack",
   "action":"aws:deleteStack",
   "maxAttempts":1,
   "onFailure":"Abort",
   "inputs":{
      "StackName":"{{stackName}}"
   }
}
```

------

ClientRequestToken  
이 `DeleteStack` 요청에 대한 고유 식별자입니다. 요청을 재시도하여 사용자가 동일한 이름의 스택을 삭제하지 않을 것임을 CloudFormation에 알릴 계획인 경우 이 토큰을 지정합니다. `DeleteStack` 요청을 재시도하여 CloudFormation에서 수신했음을 확인할 수 있습니다.  
유형: 문자열  
길이 제약: 최소 길이는 1. 최대 길이 128.  
패턴: [a-zA-Z][-a-zA-Z0-9]\$1  
필수 여부: 아니요

RetainResources.member.N  
이 입력은 `DELETE_FAILED` 상태에 있는 스택에만 적용됩니다. 보유할 리소스에 대한 논리적 리소스 ID 목록입니다. 삭제하는 동안 CloudFormation은 스택을 삭제하지만 보유한 리소스는 삭제하지 않습니다.  
비어 있지 않은 S3 버킷 같은 리소스를 삭제할 수 없지만, 스택을 삭제하고자 하는 경우에 리소스를 보유하면 유용합니다.  
형식: 문자열 배열  
필수 여부: 아니요

RoleARN  
CloudFormation이 스택을 생성하기 위해 수임하는 AWS Identity and Access Management(IAM) 역할의 Amazon 리소스 이름(ARN)입니다. CloudFormation은 역할의 자격 증명을 사용하여 사용자를 대신하여 호출합니다. CloudFormation은 스택의 모든 향후 작업에 항상 이 역할을 사용합니다. 사용자에게 스택에서 작업할 수 있는 권한이 있는 경우에는 역할을 전달할 수 있는 권한은 없더라도 CloudFormation에서 이 역할을 사용합니다. 역할이 최소한의 권한을 부여하는지 확인하세요.  
값을 지정하지 않으면 CloudFormation에서는 이전에 스택과 연결된 역할을 사용합니다. 사용 가능한 역할이 없으면 CloudFormation에서는 사용자 자격 증명으로부터 생성되는 임시 세션을 사용합니다.  
유형: 문자열  
길이 제약: 최소 길이는 20. 최대 길이는 2,048.  
필수 여부: 아니요

StackName  
스택이 연결되어 있는 이름 또는 고유한 스택 ID입니다.  
유형: 문자열  
필수 항목 여부: 예

## 보안 고려 사항
<a name="automation-action-deletestack-security"></a>

`aws:deleteStack` 작업을 사용하려면 먼저 IAM Automation 수임 역할에 다음 정책을 할당해야 합니다. assume role에 대한 자세한 내용은 [작업 1: Automation을 위한 서비스 역할 생성](automation-setup-iam.md#create-service-role) 섹션을 참조하세요.

------
#### [ JSON ]

****  

```
{
   "Version":"2012-10-17",		 	 	 
   "Statement":[
      {
         "Effect":"Allow",
         "Action":[
            "sqs:*",
            "cloudformation:DeleteStack",
            "cloudformation:DescribeStacks"
         ],
         "Resource":"*"
      }
   ]
}
```

------

# `aws:executeAutomation` - 또 다른 자동화 실행
<a name="automation-action-executeAutomation"></a>

보조 실행서를 호출하여 보조 자동화를 실행합니다. 이 작업을 수행하여 가장 일반적인 작업에 대한 실행서를 생성하고 자동화 중에 해당 실행서를 참조할 수 있습니다. 이 작업을 수행하면 비슷한 실행서 간에 복제 단계가 필요하지 않으므로 실행서를 간소화할 수 있습니다.

보조 자동화는 기본 자동화를 시작한 사용자의 컨텍스트에서 실행됩니다. 이는 보조 자동화가 첫 자동화를 시작한 사용자와 동일한 AWS Identity and Access Management(IAM) 역할 또는 사용자를 사용한다는 의미입니다.

**중요**  
수임 역할(iam:passRole 정책을 사용하는 역할)을 사용하는 보조 자동화에서 파라미터를 지정하는 경우 기본 자동화를 시작한 사용자 또는 역할에 보조 자동화에서 지정한 수임 역할을 전달할 권한이 있어야 합니다. 자동화의 assume role 설정에 대한 자세한 내용은 [콘솔을 사용하여 Automation을 위한 서비스 역할 생성](automation-setup-iam.md)을 참조하십시오.

**입력**

------
#### [ YAML ]

```
name: Secondary_Automation
action: aws:executeAutomation
maxAttempts: 3
timeoutSeconds: 3600
onFailure: Abort
inputs:
  DocumentName: secondaryAutomation
  RuntimeParameters:
    instanceIds:
    - i-1234567890abcdef0
```

------
#### [ JSON ]

```
{
   "name":"Secondary_Automation",
   "action":"aws:executeAutomation",
   "maxAttempts":3,
   "timeoutSeconds":3600,
   "onFailure":"Abort",
   "inputs":{
      "DocumentName":"secondaryAutomation",
      "RuntimeParameters":{
         "instanceIds":[
            "i-1234567890abcdef0"
         ]
      }
   }
}
```

------

DocumentName  
단계 중에 실행할 보조 실행서의 이름입니다. 같은 AWS 계정에 있는 실행서의 경우 실행서 이름을 지정합니다. 다른 AWS 계정에서 공유되는 실행서의 경우 실행서의 Amazon 리소스 이름(ARN)을 지정합니다. 공유 실행서 사용에 대한 자세한 내용은 [공유 SSM 문서 사용](documents-ssm-sharing.md#using-shared-documents) 섹션을 참조하세요.  
유형: 문자열  
필수 항목 여부: 예

DocumentVersion  
실행할 보조 실행서의 버전입니다. 지정하지 않은 경우 Automation은 기본 실행서 버전을 실행합니다.  
유형: 문자열  
필수 여부: 아니요

MaxConcurrency  
이 태스크를 병렬로 실행할 수 있는 최대 대상 수입니다. 숫자(예: 10) 또는 백분율(예: 10%)로 지정할 수 있습니다.  
유형: 문자열  
필수 여부: 아니요

MaxErrors  
시스템에서 추가 대상에 대한 자동화 실행을 중지하기 전에 허용되는 오류 수입니다. 오류의 절대 개수(예: 10개)를 지정하거나 대상 집합의 비율(예: 10%)을 지정할 수 있습니다. 예를 들어 3을 지정할 경우 네 번째 오류가 수신되면 자동화 실행이 중지됩니다. 0을 지정하면 첫 번째 오류 결과가 반환된 후 추가 대상에서 자동화 실행이 중지됩니다. 50개의 리소스에서 자동화를 실행하고 `MaxErrors`를 10%로 설정하면 6번째 오류 수신 시 추가 대상에서 자동화 실행이 중지됩니다.  
`MaxErrors` 임계값에 도달했을 때 이미 실행 중인 자동화는 완료될 수 있지만 일부는 실패할 수도 있습니다. 지정된 `MaxErrors`보다 많이 자동화 실패가 발생하지 않게 자동화가 한 번에 하나씩 진행되도록 `MaxConcurrency`를 1로 설정합니다.  
유형: 문자열  
필수 여부: 아니요

RuntimeParameters  
보조 실행서에 필요한 파라미터입니다. 매핑은 \$1"parameter1" : "value1", "parameter2" : "value2" \$1 형식을 사용합니다.  
유형: 맵  
필수 여부: 아니요

Tags  
리소스에 할당하는 선택적 메타데이터입니다. 자동화에 대해 최대 5개의 태그를 지정할 수 있습니다.  
유형: MapList  
필수 여부: 아니요

TargetLocations  
위치는 자동화를 실행하려는 AWS 리전 및/또는 AWS 계정의 조합입니다. 최소 1개 항목을 지정해야 하며 최대 100개 항목을 지정할 수 있습니다. 이 파라미터의 값을 지정하면 출력이 상위 자동화로 반환되지 않습니다. 필요한 경우 API 작업을 후속 호출하여 하위 자동화에서 출력을 검색해야 합니다.  
유형: MapList  
필수 여부: 아니요

TargetMaps  
대상 리소스에 대한 문서 파라미터의 키-값 매핑 목록입니다. `Targets`와 `TargetMaps`는 함께 지정할 수 없습니다.  
유형: MapList  
필수 여부: 아니요

TargetParameterName  
속도 제어 자동화의 대상 리소스로 사용되는 파라미터의 이름입니다. `Targets`를 지정한 경우에만 필요합니다.  
유형: 문자열  
필수 여부: 아니요

대상  
대상 리소스에 대한 키-값 매핑 목록입니다. `TargetParameterName`를 지정한 경우에만 필요합니다.  
유형: MapList  
필수 여부: 아니요출력

출력  
보조 자동화에서 생성된 출력입니다. *Secondary\$1Automation\$1Step\$1Name*.Output 형식을 사용하여 출력을 참조할 수 있습니다.  
유형: StringList  
다음 예를 참고하세요  

```
- name: launchNewWindowsInstance
  action: 'aws:executeAutomation'
  onFailure: Abort
  inputs:
    DocumentName: launchWindowsInstance
  nextStep: getNewInstanceRootVolume
- name: getNewInstanceRootVolume
  action: 'aws:executeAwsApi'
  onFailure: Abort
  inputs:
    Service: ec2
    Api: DescribeVolumes
    Filters:
    - Name: attachment.device
      Values:
      - /dev/sda1
    - Name: attachment.instance-id
      Values:
      - '{{launchNewWindowsInstance.Output}}'
  outputs:
  - Name: rootVolumeId
    Selector: '$.Volumes[0].VolumeId'
    Type: String
  nextStep: snapshotRootVolume
- name: snapshotRootVolume
  action: 'aws:executeAutomation'
  onFailure: Abort
  inputs:
    DocumentName: AWS-CreateSnapshot
    RuntimeParameters:
    VolumeId:
    - '{{getNewInstanceRootVolume.rootVolumeId}}'
    Description:
    - 'Initial root snapshot for {{launchNewWindowsInstance.Output}}'
```

ExecutionId  
보조 자동화의 ID입니다.  
유형: 문자열

Status  
보조 자동화의 상태입니다.  
유형: 문자열

# `aws:executeAwsApi` - AWS API 작업 호출 및 실행
<a name="automation-action-executeAwsApi"></a>

AWS API 작업을 호출하여 실행합니다. 일부 API 작업이 테스트되지 않았더라도 대부분의 API 작업이 지원됩니다. [GetObject](https://docs.aws.amazon.com/AmazonS3/latest/API/RESTObjectGET.html) 작업과 같은 스트리밍 API 작업은 지원되지 않습니다. 사용하려는 API 작업이 스트리밍 작업인지 확실하지 않은 경우 API에 스트리밍 입력 또는 출력이 필요한지 여부를 결정하는 서비스에 대한 [Boto3](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/index.html) 설명서를 검토하세요. 이 작업에 사용되는 Boto3 버전은 정기적으로 업데이트됩니다. 그러나 새 Boto3 버전 릴리스 후 변경 사항이 이 작업에 반영되려면 최대 몇 주가 걸릴 수 있습니다. 각 `aws:executeAwsApi` 작업은 최대 25초까지 실행할 수 있습니다. 이 작업을 사용하는 방법에 관한 자세한 내용은 [추가 런북 예제](automation-document-examples.md) 섹션을 참조하세요.

**참고**  
`aws:executeAwsApi` 작업은 자동 스로틀링 재시도를 지원합니다. 자세한 내용은 [스로틀링된 작업에 대한 자동 재시도 구성](automation-throttling-retry.md) 섹션을 참조하세요.

**입력**  
입력은 선택하는 API 작업에 의해 정의됩니다.

------
#### [ YAML ]

```
action: aws:executeAwsApi
inputs:
  Service: The official namespace of the service
  Api: The API operation or method name
  API operation inputs or parameters: A value
outputs: # These are user-specified outputs
- Name: The name for a user-specified output key
  Selector: A response object specified by using jsonpath format
  Type: The data type
```

------
#### [ JSON ]

```
{
   "action":"aws:executeAwsApi",
   "inputs":{
      "Service":"The official namespace of the service",
      "Api":"The API operation or method name",
      "API operation inputs or parameters":"A value"
   },
   "outputs":[ These are user-specified outputs
      {
         "Name":"The name for a user-specified output key",
         "Selector":"A response object specified by using JSONPath format",
         "Type":"The data type"
      }
   ]
}
```

------

서비스  
실행하려는 API 작업을 포함하는 AWS 서비스 네임스페이스입니다. AWS SDK for Python (Boto3)의 [사용 가능한 서비스](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/index.html)에서 지원되는 AWS 서비스 네임스페이스 목록을 볼 수 있습니다. 네임스페이스는 **클라이언트** 섹션에서 찾을 수 있습니다. 예를 들면 Systems Manager의 네임스페이스는 `ssm`입니다. Amazon Elastic Compute Cloud(Amazon EC2)의 네임스페이스는 `ec2`입니다.  
유형: 문자열  
필수 항목 여부: 예

Api  
실행할 API 작업의 이름입니다. 다음 [[서비스 참조(Services Reference)](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/index.html)] 페이지의 왼쪽 탐색 영역에서 서비스를 선택하여 API 작업(메서드라고도 함)을 볼 수 있습니다. 호출할 서비스에 대한 **클라이언트** 섹션에서 메서드를 선택합니다. 예를 들어 Amazon Relational Database Service(Amazon RDS)에 대한 모든 API 작업(메서드)이 [Amazon RDS 메서드](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/rds.html) 페이지에 나열됩니다.  
유형: 문자열  
필수 항목 여부: 예

API 작업 입력  
하나 이상의 API 작업 입력입니다. 다음 [서비스 참조](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/index.html) 페이지의 왼쪽 탐색 영역에서 서비스를 선택하여 사용할 수 있는 입력(파라미터)을 볼 수 있습니다. 호출할 서비스에 대한 **클라이언트** 섹션에서 메서드를 선택합니다. 예를 들어 Amazon RDS에 대한 모든 메서드는 [Amazon RDS 메서드](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/rds.html) 페이지에 나열됩니다. [describe\$1db\$1instances](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/rds.html#RDS.Client.describe_db_instances) 메서드를 선택하고 아래로 스크롤하여 **DBInstanceIdentifier**, **Name** 및 **Values** 같은 사용할 수 있는 파라미터를 볼 수 있습니다.  

```
inputs:
  Service: The official namespace of the service
  Api: The API operation name
  API input 1: A value
  API Input 2: A value
  API Input 3: A value
```

```
"inputs":{
      "Service":"The official namespace of the service",
      "Api":"The API operation name",
      "API input 1":"A value",
      "API Input 2":"A value",
      "API Input 3":"A value"
}
```
형식: 선택한 API 작업에 의해 결정됨  
필수 여부: 예

**출력**  
출력은 선택한 API 작업의 응답을 기반으로 사용자가 지정합니다.

이름  
출력의 이름입니다.  
유형: 문자열  
필수 항목 여부: 예

Selector  
응답 객체의 특정 속성에 대한 JSONPath입니다. 다음 [서비스 참조](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/index.html) 페이지의 왼쪽 탐색 영역에서 서비스를 선택하여 응답 객체를 볼 수 있습니다. 호출할 서비스에 대한 **클라이언트** 섹션에서 메서드를 선택합니다. 예를 들어 Amazon RDS에 대한 모든 메서드는 [Amazon RDS 메서드](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/rds.html) 페이지에 나열됩니다. [describe\$1db\$1instances](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/rds.html#RDS.Client.describe_db_instances) 메서드를 선택하고 **Response Structure(응답 구조)** 섹션이 있는 아래쪽으로 스크롤합니다. **DBInstances**가 응답 객체로 나열됩니다.  
형식: Integer, Boolean, String, StringList, StringMap, MapList  
필수 여부: 예

Type  
응답 요소의 데이터 유형입니다.  
형식: 다양  
필수 여부: 예

# `aws:executeScript` - 스크립트 실행
<a name="automation-action-executeScript"></a>

지정된 런타임 및 핸들러를 사용하여 제공된 Python 또는 PowerShell 스크립트를 실행합니다. 각 `aws:executeScript` 작업은 최대 600초(10분)까지 실행할 수 있습니다. `aws:executeScript` 단계에서 `timeoutSeconds` 파라미터를 지정하여 시간 제한을 제한할 수 있습니다.

함수에서 return 문을 사용하여 출력 페이로드에 출력을 추가합니다. `aws:executeScript` 작업에 대한 출력 정의 예시는 [예제 2: 스크립팅된 실행서](automation-authoring-runbooks-scripted-example.md)의 내용을 참조하세요. 실행서에 있는 `aws:executeScript` 작업의 출력을 지정하는 Amazon CloudWatch Logs 로그 그룹으로 전송할 수 있습니다. 자세한 내용은 [CloudWatch Logs로 Automation 작업 출력 로깅](automation-action-logging.md) 섹션을 참조하세요.

`aws:executeScript` 작업에서 CloudWatch Logs로 출력을 전송하거나 `aws:executeScript` 작업에 대해 지정한 스크립트가 AWS API 작업을 호출하는 경우, 런북을 실행하려면 AWS Identity and Access Management(IAM) 서비스 역할(또는 역할 수임)이 항상 필요합니다.

**참고**  
`aws:executeScript` 작업은 자동 스로틀링 재시도를 지원하지 않습니다. 스크립트가 스로틀링될 수 있는 AWS API 호출을 수행하는 경우 스크립트 코드에 자체 재시도 로직을 구현해야 합니다.

`aws:executeScript` 작업에는 다음과 같은 사전 설치된 PowerShell Core 모듈이 포함되어 있습니다.
+ Microsoft.PowerShell.Host
+ Microsoft.PowerShell.Management
+ Microsoft.PowerShell.Security
+ Microsoft.PowerShell.Utility
+ PackageManagement
+ PowerShellGet

사전 설치되지 않은 PowerShell Core 모듈을 사용하려면 스크립트에서 다음 명령과 같이 `-Force` 플래그를 사용하여 모듈을 설치해야 합니다. `AWSPowerShell.NetCore` 모듈은 지원되지 않습니다. *ModuleName*을 설치하려는 모듈로 바꿉니다.

```
Install-Module ModuleName -Force
```

스크립트에서 PowerShell Core cmdlet을 사용하려면 다음 명령과 같이 `AWS.Tools` 모듈을 사용하는 것이 좋습니다. 각 *example resource placeholder*를 사용자의 정보로 바꿉니다.
+ Amazon S3 cmdlet입니다.

  ```
  Install-Module AWS.Tools.S3 -Force
  Get-S3Bucket -BucketName amzn-s3-demo-bucket
  ```
+ Amazon EC2 cmdlet.

  ```
  Install-Module AWS.Tools.EC2 -Force
  Get-EC2InstanceStatus -InstanceId instance-id
  ```
+ 공통 또는 서비스 독립적 AWS Tools for Windows PowerShell cmdlet입니다.

  ```
  Install-Module AWS.Tools.Common -Force
  Get-AWSRegion
  ```

스크립트에서 PowerShell Core cmdlet을 사용하는 것 외에 새 객체를 초기화하는 경우 다음 명령과 같이 모듈도 가져와야 합니다.

```
Install-Module AWS.Tools.EC2 -Force
Import-Module AWS.Tools.EC2

$tag = New-Object Amazon.EC2.Model.Tag
$tag.Key = "Tag"
$tag.Value = "TagValue"

New-EC2Tag -Resource i-02573cafcfEXAMPLE -Tag $tag
```

`AWS.Tools` 모듈 설치와 가져오기 및 실행서의 PowerShell Core cmdlet 사용 예는 [Automation 런북의 시각적 디자인 경험](automation-visual-designer.md) 섹션을 참조하세요.

**Input**  
스크립트를 실행하는 데 필요한 정보를 입력합니다. 각 *example resource placeholder*를 사용자의 정보로 바꿉니다.

**참고**  
Python 스크립트의 첨부 파일은 스크립트가 포함된 .py 파일 또는 .zip 파일일 수 있습니다. PowerShell 스크립트는.zip 파일에 저장해야 합니다.

------
#### [ YAML ]

```
action: "aws:executeScript"
inputs: 
 Runtime: runtime
 Handler: "functionName"
 InputPayload: 
  scriptInput: '{{parameterValue}}'
 Script: |-
   def functionName(events, context):
   ...
 Attachment: "scriptAttachment.zip"
```

------
#### [ JSON ]

```
{
    "action": "aws:executeScript",
    "inputs": {
        "Runtime": "runtime",
        "Handler": "functionName",
        "InputPayload": {
            "scriptInput": "{{parameterValue}}"
        },
        "Attachment": "scriptAttachment.zip"
    }
}
```

------

런타임  
제공된 스크립트를 실행하는 데 사용할 런타임 언어입니다. `aws:executeScript`는 다음 표의 런타임을 지원합니다.      
[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/systems-manager/latest/userguide/automation-action-executeScript.html)
유형: 문자열  
필수 항목 여부: 예  
Python 런타임의 경우 이 환경은 512MB의 메모리와 512MB의 디스크 공간을 제공합니다. PowerShell 런타임의 경우 이 환경은 1,024MB의 메모리와 512MB의 디스크 공간을 제공합니다.

핸들러  
함수의 이름입니다. 핸들러에 정의된 함수에 두 개의 파라미터 `events`과 `context`가 있는지 확인해야 합니다. PowerShell 런타임은 이 파라미터를 지원하지 않습니다.  
유형: 문자열  
필수: 예(Python) \$1 지원되지 않음(PowerShell)

InputPayload  
핸들러의 첫 번째 파라미터로 전달되는 JSON 또는 YAML 객체입니다. 이 스크립트에 입력 데이터를 전달하는 데 사용할 수 있습니다.  
유형: 문자열  
필수 여부: 아니요  

```
description: Tag an instance
schemaVersion: '0.3'
assumeRole: '{{AutomationAssumeRole}}'
parameters:
    AutomationAssumeRole:
        type: String
        description: '(Required) The Amazon Resource Name (ARN) of the IAM role that allows Automation to perform the actions on your behalf. If no role is specified, Systems Manager Automation uses your IAM permissions to operate this runbook.'
    InstanceId:
        type: String
        description: (Required) The ID of the EC2 instance you want to tag.
mainSteps:
  - name: tagInstance
    action: 'aws:executeScript'
    inputs:
        Runtime: "python3.11"
        Handler: tagInstance
        InputPayload:
            instanceId: '{{InstanceId}}'
        Script: |-
          def tagInstance(events,context):
            import boto3

            #Initialize client
            ec2 = boto3.client('ec2')
            instanceId = events['instanceId']
            tag = {
                "Key": "Env",
                "Value": "ExamplePython"
            }
            print(f"Adding tag {tag} to instance id {instanceId}")
            ec2.create_tags(
                Resources=[instanceId],
                Tags=[tag]
            )
            return tag
    outputs:
      - Type: String
        Name: TagKey
        Selector: $.Payload.Key
outputs:
  - tagInstance.TagKey
```

```
description: Tag an instance
schemaVersion: '0.3'
assumeRole: '{{AutomationAssumeRole}}'
parameters:
  AutomationAssumeRole:
    type: String
    description: (Required) The Amazon Resource Name (ARN) of the IAM role that allows Automation to perform the actions on your behalf. If no role is specified, Systems Manager Automation uses your IAM permissions to operate this runbook.
  InstanceId:
    type: String
    description: (Required) The ID of the EC2 instance you want to tag.
mainSteps:
  - name: tagInstance
    action: aws:executeScript
    isEnd: true
    inputs:
      Runtime: PowerShell 7.4
      InputPayload:
        instanceId: '{{InstanceId}}'
      Script: |-
        Install-Module AWS.Tools.EC2 -Force
        Import-Module AWS.Tools.EC2

        $input = $env:InputPayload | ConvertFrom-Json

        $tag = New-Object Amazon.EC2.Model.Tag
        $tag.Key = "Env"
        $tag.Value = "ExamplePowerShell"

        Write-Information "Adding tag key: $($tag.Key) and value: $($tag.Value) to instance id $($input.instanceId)"
        New-EC2Tag -Resource $input.instanceId -Tag $tag

        return $tag
    outputs:
      - Type: String
        Name: TagKey
        Selector: $.Payload.Key
outputs:
  - tagInstance.TagKey
```

Script  
자동화 중 실행할 기본 제공 스크립트입니다.  
유형: 문자열  
필수: 아니오(Python) \$1 예(PowerShell)

연결  
작업에서 호출될 수 있는 독립형 스크립트 파일 또는.zip 파일의 이름입니다. `Attachments` 요청 파라미터에서 지정한 문서 첨부 파일의 `Name`과 동일한 값을 지정합니다. 자세한 내용은 *AWS Systems Manager API 참조*의 [첨부 파일](https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_CreateDocument.html#systemsmanager-CreateDocument-request-Attachments)을 참조하세요. 첨부 파일을 사용하여 스크립트를 제공하는 경우 런북의 최상위 수준 요소에서 `files` 섹션 또한 정의해야 합니다. 자세한 내용은 [스키마 버전 0.3](documents-schemas-features.md#automation-doc-syntax-examples) 섹션을 참조하세요.  
Python용 파일을 호출하려면 `Handler`에서 `filename.method_name` 형식을 사용합니다.  
Python 스크립트의 첨부 파일은 스크립트가 포함된 .py 파일 또는 .zip 파일일 수 있습니다. PowerShell 스크립트는.zip 파일에 저장해야 합니다.
첨부 파일에 Python 라이브러리를 포함할 때 각 모듈 디렉터리에 빈 `__init__.py` 파일을 추가하는 것이 좋습니다. 이를 통해 스크립트 내용 내 첨부 파일의 라이브러리에서 모듈을 가져올 수 있습니다. 예: `from library import module`  
유형: 문자열  
필수 여부: 아니요출력

페이로드  
함수에서 반환된 객체의 JSON 표현입니다. 최대 100KB가 반환됩니다. 목록을 출력하는 경우 최대 100개의 항목이 반환됩니다.

## aws:executeScript에서 첨부 파일 사용
<a name="automation-action-executeScript-attachments"></a>

첨부 파일은 복잡한 스크립트, 여러 모듈 및 외부 종속 항목을 `aws:executeScript` 작업에서 패키징하고 재사용할 수 있는 강력한 방법을 제공합니다. 다음을 수행해야 경우 첨부 파일을 사용합니다.
+ 여러 Python 모듈 또는 PowerShell 스크립트를 함께 패키징합니다.
+ 여러 런북에서 동일한 스크립트 로직을 재사용합니다.
+ 스크립트에 외부 라이브러리 또는 종속 항목을 포함합니다.
+ 복잡한 스크립트 로직을 분리하여 런북 정의를 정리합니다.
+ 여러 팀 또는 자동화 워크플로에서 스크립트 패키지를 공유합니다.

### 첨부 파일 구조 및 패키징
<a name="automation-action-executeScript-attachment-structure"></a>

단일 파일 또는 여러 파일이 포함된 zip 패키지를 첨부할 수 있습니다. 구조는 사용 사례에 따라 달라집니다.

**단일 파일의 첨부 파일**  
간단한 스크립트의 경우 단일 `.py` 파일(Python) 또는 단일 PowerShell 스크립트가 포함된 `.zip` 파일을 첨부할 수 있습니다.

**다중 모듈 패키지**  
여러 모듈이 필요한 복잡한 자동화의 경우 다음과 같은 권장 구조의 zip 패키지를 생성합니다.

```
my-automation-package.zip
├── main.py                    # Entry point script
├── utils/
│   ├── __init__.py           # Required for Python module imports
│   ├── helper_functions.py   # Utility functions
│   └── aws_operations.py     # AWS-specific operations
├── config/
│   ├── __init__.py
│   └── settings.py           # Configuration settings
└── requirements.txt          # Optional: document dependencies
```

**중요**  
Python 패키지의 경우 Python 모듈이 포함된 각 디렉터리에 빈 `__init__.py` 파일을 포함해야 합니다. 이렇게 하면 표준 Python 가져오기 구문(예: `from utils import helper_functions`)을 사용하여 모듈을 가져올 수 있습니다.

**PowerShell 패키지 구조**  
PowerShell 첨부 파일은 다음과 같은 구조의 zip 파일로 패키징되어야 합니다.

```
my-powershell-package.zip
├── Main.ps1                  # Entry point script
├── Modules/
│   ├── HelperFunctions.ps1   # Utility functions
│   └── AWSOperations.ps1     # AWS-specific operations
└── Config/
    └── Settings.ps1          # Configuration settings
```

### 첨부 파일을 사용하여 런북 생성
<a name="automation-action-executeScript-attachment-workflow"></a>

다음 단계에 따라 첨부 파일을 사용하는 런북을 생성합니다.

1. **Amazon S3에 첨부 파일 업로드**

   자동화 역할이 액세스할 수 있는 S3 버킷에 스크립트 파일 또는 zip 패키지를 업로드하세요. 다음 단계에서 사용할 수 있도록 S3 URI를 기록하세요.

   ```
   aws s3 cp my-automation-package.zip s3://my-automation-bucket/scripts/
   ```

1. **첨부 파일 체크섬 계산**

   보안 확인을 위해 첨부 파일의 SHA-256 체크섬을 계산하세요.

   ```
   # Linux/macOS
   shasum -a 256 my-automation-package.zip
   
   # Windows PowerShell
   Get-FileHash -Algorithm SHA256 my-automation-package.zip
   ```

1. **런북에서 파일 섹션 정의**

   런북의 최상위에 `files` 섹션을 추가하여 첨부 파일을 참조하세요.

   ```
   files:
     my-automation-package.zip:
       checksums:
         sha256: "your-calculated-checksum-here"
   ```

1. **executeScript 단계에서 첨부 파일 참조**

   `Attachment` 파라미터를 사용하여 업로드된 파일을 참조하세요.

   ```
   - name: runMyScript
     action: aws:executeScript
     inputs:
       Runtime: python3.11
       Handler: main.process_data
       Attachment: my-automation-package.zip
       InputPayload:
         inputData: "{{InputParameter}}"
   ```

## aws:executeScript 첨부 파일 예제
<a name="automation-action-executeScript-examples"></a>

다음 예제에서는 `aws:executeScript` 작업에서 첨부 파일을 사용하는 다양한 방법을 보여줍니다.

### 예제 1: 단일 파일 연결
<a name="automation-action-executeScript-single-file-example"></a>

이 예제에서는 단일 Python 파일을 첨부 파일로 사용하여 EC2 인스턴스 데이터를 처리하는 방법을 보여줍니다.

**첨부 파일: process\$1instance.py**  
다음 콘텐츠가 포함된 Python 파일을 생성합니다.

```
import boto3
import json

def process_instance_data(events, context):
    """Process EC2 instance data and return formatted results."""
    try:
        instance_id = events.get('instanceId')
        if not instance_id:
            raise ValueError("instanceId is required")
        
        ec2 = boto3.client('ec2')
        
        # Get instance details
        response = ec2.describe_instances(InstanceIds=[instance_id])
        instance = response['Reservations'][0]['Instances'][0]
        
        # Format the response
        result = {
            'instanceId': instance_id,
            'instanceType': instance['InstanceType'],
            'state': instance['State']['Name'],
            'availabilityZone': instance['Placement']['AvailabilityZone'],
            'tags': {tag['Key']: tag['Value'] for tag in instance.get('Tags', [])}
        }
        
        print(f"Successfully processed instance {instance_id}")
        return result
        
    except Exception as e:
        print(f"Error processing instance: {str(e)}")
        raise
```

**런북 완료**  
다음은 단일 파일의 첨부 파일을 사용하는 전체 런북입니다.

```
description: Process EC2 instance data using single file attachment
schemaVersion: '0.3'
assumeRole: '{{AutomationAssumeRole}}'
parameters:
  AutomationAssumeRole:
    type: String
    description: (Required) IAM role for automation execution
  InstanceId:
    type: String
    description: (Required) EC2 instance ID to process

files:
  process_instance.py:
    checksums:
      sha256: "abc123def456..."

mainSteps:
  - name: processInstance
    action: aws:executeScript
    inputs:
      Runtime: python3.11
      Handler: process_instance.process_instance_data
      Attachment: process_instance.py
      InputPayload:
        instanceId: '{{InstanceId}}'
    outputs:
      - Type: StringMap
        Name: InstanceData
        Selector: $.Payload

outputs:
  - processInstance.InstanceData
```

### 예제 2: 다중 모듈 패키지
<a name="automation-action-executeScript-multi-module-example"></a>

이 예제에서는 복잡한 S3 버킷 작업을 위해 여러 Python 모듈을 포함하는 zip 패키지를 사용하는 방법을 보여줍니다.

**패키지 구조**  
다음 구조의 zip 패키지를 생성합니다.

```
s3-operations.zip
├── main.py
├── utils/
│   ├── __init__.py
│   ├── s3_helper.py
│   └── validation.py
└── config/
    ├── __init__.py
    └── settings.py
```

**main.py(진입 지점)**  
작업을 오케스트레이션하는 기본 스크립트:

```
from utils.s3_helper import S3Operations
from utils.validation import validate_bucket_name
from config.settings import get_default_settings

def cleanup_s3_bucket(events, context):
    """Clean up S3 bucket based on specified criteria."""
    try:
        bucket_name = events.get('bucketName')
        max_age_days = events.get('maxAgeDays', 30)
        
        # Validate inputs
        if not validate_bucket_name(bucket_name):
            raise ValueError(f"Invalid bucket name: {bucket_name}")
        
        # Initialize S3 operations
        s3_ops = S3Operations()
        settings = get_default_settings()
        
        # Perform cleanup
        deleted_objects = s3_ops.delete_old_objects(
            bucket_name, 
            max_age_days,
            settings['dry_run']
        )
        
        result = {
            'bucketName': bucket_name,
            'deletedCount': len(deleted_objects),
            'deletedObjects': deleted_objects[:10],  # Return first 10 for brevity
            'dryRun': settings['dry_run']
        }
        
        print(f"Cleanup completed for bucket {bucket_name}")
        return result
        
    except Exception as e:
        print(f"Error during S3 cleanup: {str(e)}")
        raise
```

## aws:executeScript 첨부 파일 문제 해결
<a name="automation-action-executeScript-troubleshooting"></a>

다음 지침을 사용하여 `aws:executeScript` 첨부 파일과 관련된 일반적인 문제를 해결합니다.

**모듈 가져오기 오류**  
다중 모듈 패키지를 사용할 때 가져오기 오류를 수신하는 경우:
+ Python 모듈을 포함하는 각 디렉터리에 빈 `__init__.py` 파일이 포함되어 있는지 확인합니다.
+ import 문이 zip 패키지의 실제 파일 및 디렉터리 구조와 일치하는지 확인합니다.
+ 상대적 가져오기(예: `from .utils import helper`) 또는 절대적 가져오기(예: `from utils import helper`)를 일관되게 사용합니다.

**첨부 파일 찾을 수 없음 오류**  
자동화에서 첨부 파일을 찾지 못하는 경우:
+ `Attachment` 파라미터 값이 `files` 섹션의 키와 정확히 일치하는지 확인합니다.
+ `files` 섹션에서 S3 버킷 경로 및 파일 이름이 올바른지 확인합니다.
+ 자동화 역할에 첨부 파일의 S3 위치에 대한 `s3:GetObject` 권한이 있는지 확인합니다.
+ 런북의 체크섬이 실제 파일 체크섬과 일치하는지 확인합니다.

**핸들러 함수 오류**  
핸들러 관련 오류를 수신하는 경우:
+ Python의 경우: `Handler` 파라미터에서 `filename.function_name` 형식을 사용합니다(예: `main.process_data`).
+ 핸들러 함수가 정확히 두 개의 파라미터(`events` 및 `context`)를 수락하는지 확인합니다.
+ PowerShell의 경우: `Handler` 파라미터를 지정하지 마세요. 스크립트는 직접 실행됩니다.

**스크립트 실행 실패**  
실행 중에 스크립트가 실패하는 경우:
+ 자동화 실행 기록에서 자세한 오류 메시지 및 스택 추적을 확인합니다.
+ `print()` 문(Python) 또는 `Write-Information`(PowerShell)을 사용하여 디버깅 출력을 추가합니다.
+ 자동화 역할에 필요한 모든 AWS 권한이 부여되었는지 확인합니다.
+ 첨부 파일로 패키징하기 전에 스크립트 로직을 로컬로 테스트합니다.

**종료 코드 및 오류 처리**  
오류를 올바르게 처리하고 종료 코드를 반환하는 방법:
+ Python의 경우: `raise Exception("error message")`를 사용하여 스크립트 실패를 나타냅니다.
+ PowerShell의 경우: `throw "error message"` 또는 `Write-Error`를 사용하여 실패를 나타냅니다.
+ 함수에서 구조화된 데이터를 반환하여 성공 또는 실패에 대한 세부 정보를 제공합니다.
+ try-catch 블록을 사용하여 예외를 정상적으로 처리하고 유용한 오류 메시지를 제공합니다.

# `aws:executeStateMachine` - AWS Step Functions 상태 시스템을 실행합니다.
<a name="automation-action-executeStateMachine"></a>

AWS Step Functions 상태 시스템을 실행합니다.

**참고**  
`aws:executeStateMachine` 작업은 자동 스로틀링 재시도를 지원합니다. 자세한 내용은 [스로틀링된 작업에 대한 자동 재시도 구성](automation-throttling-retry.md) 섹션을 참조하세요.

**입력**

이 작업은 Step Functions [StartExecution](https://docs.aws.amazon.com/step-functions/latest/apireference/API_StartExecution.html) API 작업에서 대부분의 파라미터를 지원합니다.

**필요한 AWS Identity and Access Management(IAM) 권한**
+ `states:DescribeExecution`
+ `states:StartExecution`
+ `states:StopExecution`

------
#### [ YAML ]

```
name: executeTheStateMachine
action: aws:executeStateMachine
inputs:
  stateMachineArn: StateMachine_ARN
  input: '{"parameters":"values"}'
  name: name
```

------
#### [ JSON ]

```
{
    "name": "executeTheStateMachine",
    "action": "aws:executeStateMachine",
    "inputs": {
        "stateMachineArn": "StateMachine_ARN",
        "input": "{\"parameters\":\"values\"}",
        "name": "name"
    }
}
```

------

stateMachineArn  
Step Functions 상태 시스템의 Amazon 리소스 이름(ARN)입니다.  
유형: 문자열  
필수 항목 여부: 예

이름  
실행의 이름입니다.  
유형: 문자열  
필수 여부: 아니요

입력  
실행을 위한 JSON 입력 문자를 포함하는 문자열입니다.  
유형: 문자열  
필수 여부: 아니요

**출력**  
이 작업의 경우 다음과 같은 출력이 사전 정의되어 있습니다.

executionArn  
실행의 ARN입니다.  
유형: 문자열

입력  
실행의 JSON 입력 데이터를 포함하는 문자열입니다. 길이 제한은 페이로드 크기에 적용되며 UTF-8 인코딩에서 바이트로 표시됩니다.  
유형: 문자열

이름  
실행의 이름입니다.  
유형: 문자열

output  
실행의 JSON 출력 데이터입니다. 길이 제한은 페이로드 크기에 적용되며 UTF-8 인코딩에서 바이트로 표시됩니다.  
유형: 문자열

startDate  
실행이 시작된 날짜입니다.  
유형: 문자열

stateMachineArn  
실행된 상태 시스템의 ARN입니다.  
유형: 문자열

status  
실행의 현재 상태입니다.  
유형: 문자열

stopDate  
실행이 이미 종료된 경우, 실행이 중지된 날짜입니다.  
유형: 문자열

# `aws:invokeWebhook` - Automation 웹후크 통합 호출
<a name="invoke-webhook"></a>

지정된 Automation 웹후크 통합을 호출합니다. Automation 통합 생성에 대한 자세한 내용은 [Automation을 위한 웹후크 통합 생성](creating-webhook-integrations.md) 섹션을 참조하세요.

**참고**  
`aws:invokeWebhook` 작업은 자동 스로틀링 재시도를 지원합니다. 자세한 내용은 [스로틀링된 작업에 대한 자동 재시도 구성](automation-throttling-retry.md) 섹션을 참조하세요.

**참고**  
`aws:invokeWebhook` 작업을 사용하려면 사용자 또는 서비스 역할이 다음 작업을 허용해야 합니다.  
ssm:GetParameter
kms:Decrypt
AWS Key Management Service(AWS KMS) `Decrypt` 작업에 대한 권한은 고객 관리형 키를 사용하여 통합을 위한 파라미터를 암호화하는 경우에만 필요합니다.

**Input**  
호출하려는 Automation 통합에 대한 정보를 제공합니다.

------
#### [ YAML ]

```
action: "aws:invokeWebhook"
inputs: 
 IntegrationName: "exampleIntegration"
 Body: "Request body"
```

------
#### [ JSON ]

```
{
    "action": "aws:invokeWebhook",
    "inputs": {
        "IntegrationName": "exampleIntegration",
        "Body": "Request body"
    }
}
```

------

IntegrationName  
Automation 통합의 이름입니다. 예를 들어 `exampleIntegration`입니다. 지정하는 통합은 이미 존재해야 합니다.  
유형: 문자열  
필수 항목 여부: 예

바디  
웹후크 통합이 호출될 때 전송하려는 페이로드입니다.  
유형: 문자열  
필수 여부: 아니요출력

응답  
웹후크 공급자 응답에서 받은 텍스트입니다.

ResponseCode  
웹후크 공급자 응답에서 받은 HTTP 상태 코드입니다.

# `aws:invokeLambdaFunction` - AWS Lambda 함수 호출
<a name="automation-action-lamb"></a>

지정된 AWS Lambda 함수를 호출합니다.

**참고**  
각 `aws:invokeLambdaFunction` 작업은 최대 300초(5분)까지 실행할 수 있습니다. `aws:invokeLambdaFunction` 단계에서 `timeoutSeconds` 파라미터를 지정하여 시간 제한을 제한할 수 있습니다.

**참고**  
`aws:invokeLambdaFunction` 작업은 자동 스로틀링 재시도를 지원합니다. 자세한 내용은 [스로틀링된 작업에 대한 자동 재시도 구성](automation-throttling-retry.md) 섹션을 참조하세요.

**Input**  
이 작업은 Lambda 서비스에 대한 대부분의 호출된 파라미터를 지원합니다. 자세한 내용은 [Invoke](https://docs.aws.amazon.com/lambda/latest/dg/API_Invoke.html)를 참조하세요.

------
#### [ YAML ]

```
name: invokeMyLambdaFunction
action: aws:invokeLambdaFunction
maxAttempts: 3
timeoutSeconds: 120
onFailure: Abort
inputs:
  FunctionName: MyLambdaFunction
```

------
#### [ JSON ]

```
{
    "name": "invokeMyLambdaFunction",
    "action": "aws:invokeLambdaFunction",
    "maxAttempts": 3,
    "timeoutSeconds": 120,
    "onFailure": "Abort",
    "inputs": {
        "FunctionName": "MyLambdaFunction"
    }
}
```

------

FunctionName  
Lambda 함수의 이름입니다. 이 함수가 존재해야 합니다.  
유형: 문자열  
필수 항목 여부: 예

Qualifier  
함수 버전 또는 별칭 이름.  
유형: 문자열  
필수 여부: 아니요

InvocationType  
호출 유형. 기본 값은 `RequestResponse`입니다.  
유형: 문자열  
유효한 값: `Event` \$1 `RequestResponse` \$1 `DryRun`  
필수 여부: 아니요

LogType  
기본값이 `Tail`인 경우 호출 유형은 `RequestResponse`여야 합니다. Lambda는 base64로 인코딩된 Lambda 함수에 의해 생성된 로그 데이터의 마지막 4KB를 반환합니다.  
유형: 문자열  
유효한 값: `None` \$1 `Tail`  
필수 여부: 아니요

ClientContext  
클라이언트 지정 정보.  
필수 여부: 아니요

InputPayload  
핸들러의 첫 번째 파라미터로 전달되는 YAML 또는 JSON 객체입니다. 이 입력을 사용하여 함수에 데이터를 전달할 수 있습니다. 이 입력은 기존 `Payload` 입력보다 더 많은 유연성과 지원을 제공합니다. 작업에 대해 `InputPayload`와 `Payload`를 모두 정의하는 경우 `InputPayload`가 우선하며 `Payload` 값은 사용되지 않습니다.  
유형: StringMap  
필수 여부: 아니요

페이로드  
핸들러의 첫 번째 파라미터에 전달되는 JSON 문자열입니다. 함수에 입력 데이터를 전달하는 데 사용할 수 있습니다. 추가된 기능에는 `InputPayload` 입력을 사용하는 것이 좋습니다.  
유형: 문자열  
필수 여부: 아니요출력

StatusCode  
HTTP 상태 코드.

FunctionError  
존재하는 경우 함수 실행 중에 오류가 발생했음을 나타냅니다. 오류에 대한 세부 정보가 응답 페이로드에 포함됩니다.

LogResult  
Lambda 함수 호출에 대한 base64 인코딩 로그입니다. 로그는 호출 유형이 `RequestResponse`이고 로그가 요청된 경우에만 표시됩니다.

페이로드  
Lambda 함수에서 반환된 객체의 JSON 표현입니다. 호출 유형이 `RequestResponse`인 경우에만 페이로드가 있습니다.

다음은 `aws:invokeLambdaFunction` 작업의 출력을 참조하는 방법을 보여주는 `AWS-PatchInstanceWithRollback` 실행서의 일부입니다.

------
#### [ YAML ]

```
- name: IdentifyRootVolume
  action: aws:invokeLambdaFunction
  inputs:
    FunctionName: "IdentifyRootVolumeLambda-{{automation:EXECUTION_ID}}"
    Payload: '{"InstanceId": "{{InstanceId}}"}'
- name: PrePatchSnapshot
  action: aws:executeAutomation
  inputs:
    DocumentName: "AWS-CreateSnapshot"
    RuntimeParameters:
      VolumeId: "{{IdentifyRootVolume.Payload}}"
      Description: "ApplyPatchBaseline restoration case contingency"
```

------
#### [ JSON ]

```
{
    "name": "IdentifyRootVolume",
    "action": "aws:invokeLambdaFunction",
    "inputs": {
      "FunctionName": "IdentifyRootVolumeLambda-{{automation:EXECUTION_ID}}",
      "Payload": "{\"InstanceId\": \"{{InstanceId}}\"}"
    }
  },
  {
    "name": "PrePatchSnapshot",
    "action": "aws:executeAutomation",
    "inputs": {
      "DocumentName": "AWS-CreateSnapshot",
      "RuntimeParameters": {
        "VolumeId": "{{IdentifyRootVolume.Payload}}",
        "Description": "ApplyPatchBaseline restoration case contingency"
      }
    }
  }
```

------

# `aws:loop`- 자동화의 여러 단계를 반복
<a name="automation-action-loop"></a>

이 작업은 Automation 런북의 일부 하위 단계를 반복합니다. `do while` 또는 `for each` 스타일 루프를 선택할 수 있습니다. `do while` 루프를 구성하려면 `LoopCondition` 입력 파라미터를 사용합니다. `for each` 루프를 구성하려면 `Iterators` 및 `IteratorDataType` 입력 파라미터를 사용합니다. `aws:loop` 작업을 사용할 때는 `Iterators` 또는 `LoopCondition` 입력 파라미터 중 하나만 지정하십시오. 최대 반복 횟수는 100회입니다.

`onCancel` 속성은 루프 내에 정의된 단계에 대해서만 사용할 수 있습니다. 해당 `onCancel` 속성은 `aws:loop` 작업에 지원되지 않습니다. `onFailure` 속성은 `aws:loop` 작업에 사용할 수 있지만 예상치 못한 오류가 발생하여 단계가 실패하는 경우에만 사용됩니다. 루프 내 단계에 대해 `onFailure` 속성을 정의하는 경우 `aws:loop` 작업이 이러한 속성을 상속하고 오류가 발생할 경우 적절하게 반응합니다.

**예제**  
다음은 다양한 유형의 루프 작업을 구성하는 방법의 예시입니다.

------
#### [ do while ]

```
name: RepeatMyLambdaFunctionUntilOutputIsReturned
action: aws:loop
inputs:
    Steps:
    - name: invokeMyLambda
        action: aws:invokeLambdaFunction
        inputs:
        FunctionName: LambdaFunctionName
        outputs:
        - Name: ShouldRetry
            Selector: $.Retry
            Type: Boolean
    LoopCondition:
        Variable: "{{ invokeMyLambda.ShouldRetry }}"
        BooleanEquals: true
    MaxIterations: 3
```

------
#### [ for each ]

```
name: stopAllInstancesWithWaitTime
action: aws:loop
inputs:
    Iterators: "{{ DescribeInstancesStep.InstanceIds }}"
    IteratorDataType: "String"
    Steps:
    - name: stopOneInstance
        action: aws:changeInstanceState
        inputs:
        InstanceIds:
            - "{{stopAllInstancesWithWaitTime.CurrentIteratorValue}}"
        CheckStateOnly: false
        DesiredState: stopped
    - name: wait10Seconds
        action: aws:sleep
        inputs:
        Duration: PT10S
```

------

**Input**  
입력은 다음과 같습니다.

반복자  
반복할 단계의 항목 목록입니다. 최대 반복자 수는 100입니다.  
유형: StringList  
필수 여부: 아니요

IteratorDataType  
`Iterators`의 데이터 유형을 지정하는 선택적 파라미터입니다. 이 파라미터의 값은 `Iterators` 입력 파라미터와 함께 제공될 수 있습니다. 이 파라미터와 `Iterators` 값을 지정하지 않으면 `LoopCondition` 파라미터의 값을 지정해야 합니다.  
유형: 문자열  
유효한 값: Boolean \$1 Integer \$1 String \$1 StringMap  
기본값: 문자열  
필수 여부: 아니요

LoopCondition  
평가할 `Variable` 및 연산자 조건으로 구성됩니다. 이 파라미터의 값을 지정하지 않으면 `Iterators` 및 `IteratorDataType` 파라미터의 값을 지정해야 합니다. `And`, `Not`, `Or` 연산자를 조합하여 복잡한 연산자 평가를 사용할 수 있습니다. 조건은 루프의 단계가 완료된 후에 평가됩니다. 조건이 `true`에 해당하고 `MaxIterations` 값에 도달하지 않은 경우 루프의 단계가 다시 실행됩니다. 연산자 조건은 다음과 같습니다.  

**문자열 연산**
+ StringEquals
+ EqualsIgnoreCase
+ StartsWith
+ EndsWith
+ 포함

**수치 연산**
+ NumericEquals
+ NumericGreater
+ NumericLesser
+ NumericGreaterOrEquals
+ NumericLesser
+ NumericLesserOrEquals

**부울 연산**
+ BooleanEquals
유형: StringMap  
필수 여부: 아니요

MaxIterations  
루프의 최대 단계 실행 횟수입니다. 이 입력값에 지정된 값에 도달하면 `LoopCondition` 항목이 여전히 `true`에 해당하거나 `Iterators` 파라미터에 객체가 남아 있더라도 루프 실행이 중지됩니다.  
유형: 정수  
유효한 값은 1\$1100입니다.  
필수 여부: 아니요

단계  
루프에서 실행할 단계 목록입니다. 이들은 중첩된 런북처럼 작동합니다. 이 단계에서 `{{loopStepName.CurrentIteratorValue}}` 구문을 사용하여 `for each` 루프의 현재 반복자 값에 액세스할 수 있습니다. `{{loopStepName.CurrentIteration}}` 구문을 사용하여 두 루프 유형에 대한 현재 반복의 정수 값에 액세스할 수도 있습니다.  
유형: 단계 목록  
필수 여부: 예출력

CurrentIteration  
현재 루프 반복을 정수로 나타낸 값입니다. 반복 값은 1에서 시작합니다.  
유형: 정수

CurrentIteratorValue  
문자열인 현재 반복자 값입니다. 이 출력은 `for each` 루프에만 표시됩니다.  
유형: 문자열

# `aws:pause` - 자동화 일시 중지
<a name="automation-action-pause"></a>

이 작업은 자동화를 일시 중지합니다. 자동화가 일시 중지되면 상태가 [*대기 중(Waiting)*]이 됩니다. 자동화를 계속하려면 신호 유형이 `Resume`인 [SendAutomationSignal](https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_SendAutomationSignal.html) API 작업을 사용합니다. 작업 워크플로를 보다 세밀하게 제어할 수 있는 `aws:sleep` 또는`aws:approve` 작업을 사용하는 것이 좋습니다.

**참고**  
이 작업에 대한 기본 제한 시간은 7일(604800초)이고 최대 값은 30일(2592000초)입니다. `aws:pause` 단계에서 `timeoutSeconds` 파라미터를 지정하여 제한 시간을 제한 또는 연장할 수 있습니다.

**Input**  
입력은 다음과 같습니다.

------
#### [ YAML ]

```
name: pauseThis
action: aws:pause
timeoutSeconds: 1209600
inputs: {}
```

------
#### [ JSON ]

```
{
    "name": "pauseThis",
    "action": "aws:pause",
    "timeoutSeconds": "1209600",
    "inputs": {}
}
```

------출력

없음  


# `aws:runCommand` - 관리형 인스턴스에서 명령 실행
<a name="automation-action-runcommand"></a>

지정된 명령을 실행합니다.

**참고**  
Automation은 하나의 AWS Systems Manager Run Command 작업의 *Output*만 지원합니다. 런북에는 Run Command 작업이 여러 개 포함될 수 있지만 Output은 한 번에 한 작업에서만 지원됩니다.

**Input**  
이 작업은 대부분의 send-command parameters를 지원합니다. 자세한 내용은 [SendCommand](https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_SendCommand.html)를 참조하십시오.

------
#### [ YAML ]

```
- name: checkMembership
  action: 'aws:runCommand'
  inputs:
    DocumentName: AWS-RunPowerShellScript
    InstanceIds:
      - '{{InstanceIds}}'
    Parameters:
      commands:
        - (Get-WmiObject -Class Win32_ComputerSystem).PartOfDomain
```

------
#### [ JSON ]

```
{
    "name": "checkMembership",
    "action": "aws:runCommand",
    "inputs": {
        "DocumentName": "AWS-RunPowerShellScript",
        "InstanceIds": [
            "{{InstanceIds}}"
        ],
        "Parameters": {
            "commands": [
                "(Get-WmiObject -Class Win32_ComputerSystem).PartOfDomain"
            ]
        }
    }
}
```

------

DocumentName  
명령 유형 문서가 사용자 또는 AWS의 소유인 경우 문서의 이름을 지정합니다. 다른 AWS 계정이 공유한 문서를 사용하는 경우 문서의 Amazon 리소스 이름(ARN)을 지정합니다. 공유 문서 사용에 대한 자세한 내용은 [공유 SSM 문서 사용](documents-ssm-sharing.md#using-shared-documents) 섹션을 참조하세요.  
유형: 문자열  
필수 항목 여부: 예

InstanceIds  
명령을 실행할 인스턴스 ID입니다. 최대 50개 ID를 지정할 수 있습니다.  
또한 인스턴스 ID 대신 의사 파라미터 `{{RESOURCE_ID}}`를 사용하여 대상 그룹의 모든 인스턴스에서 명령을 실행할 수 있습니다. 가상 parameters에 대한 자세한 내용은 [유지 관리 기간 작업 등록 시 의사 파라미터 사용](maintenance-window-tasks-pseudo-parameters.md) 단원을 참조하십시오.  
또 다른 대안은 `Targets` 파라미터를 사용하여 인스턴스 플릿에 명령을 보내는 것입니다. `Targets` 파라미터는 Amazon Elastic Compute Cloud(Amazon EC2) 태그를 허용합니다. `Targets` 파라미터 사용 방법에 대한 자세한 내용은 [대규모로 명령 실행](send-commands-multiple.md) 섹션을 참조하세요.  
유형: StringList  
필수 여부: 아니요(InstanceId를 지정하지 않거나 `{{RESOURCE_ID}}` 의사 파라미터를 사용하지 않는 경우 `Targets` 파라미터를 지정해야 함)

Targets  
지정한 키, 값 조합을 사용하여 인스턴스를 targets 하는 검색 기준의 배열입니다. `Targets`는 호출에 하나 이상의 인스턴스 ID를 제공하지 않는 경우 필요합니다. `Targets` 파라미터 사용 방법에 대한 자세한 내용은 [대규모로 명령 실행](send-commands-multiple.md) 섹션을 참조하세요.  
형식: MapList(목록의 맵 스키마가 객체와 일치해야 합니다.) 자세한 내용은 *AWS Systems Manager API Reference*의 [Target](https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_Target.html)을 참조하세요.  
필수 여부: 아니요(`Targets`를 지정하지 않는 경우 InstanceId를 지정하거나 `{{RESOURCE_ID}}` 의사 파라미터를 사용해야 함)  
다음은 한 예입니다.  

```
- name: checkMembership
  action: aws:runCommand
  inputs:
    DocumentName: AWS-RunPowerShellScript
    Targets:
      - Key: tag:Stage
        Values:
          - Gamma
          - Beta
      - Key: tag-key
        Values:
          - Suite
    Parameters:
      commands:
        - (Get-WmiObject -Class Win32_ComputerSystem).PartOfDomain
```

```
{
    "name": "checkMembership",
    "action": "aws:runCommand",
    "inputs": {
        "DocumentName": "AWS-RunPowerShellScript",
        "Targets": [                   
            {
                "Key": "tag:Stage",
                "Values": [
                    "Gamma", "Beta"
                ]
            },
            {
                "Key": "tag:Application",
                "Values": [
                    "Suite"
                ]
            }
        ],
        "Parameters": {
            "commands": [
                "(Get-WmiObject -Class Win32_ComputerSystem).PartOfDomain"
            ]
        }
    }
}
```

Parameters  
문서에서 지정된 필수 및 선택 Parameters.  
유형: 맵  
필수 여부: 아니요

CloudWatchOutputConfig  
명령 Output을 Amazon CloudWatch Logs로 전송하기 위한 구성 옵션입니다. CloutWatch Logs로 명령 Output 전송에 대한 자세한 내용은 [Run Command에 대한 Amazon CloudWatch Logs 구성](sysman-rc-setting-up-cwlogs.md) 섹션을 참조하세요.  
유형: StringMap(지도의 스키마는 객체와 일치해야 합니다. 자세한 내용은 *AWS Systems Manager API Reference*의 [CloudWatchOutputConfig](https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_CloudWatchOutputConfig.html)를 참조하세요.)  
필수 여부: 아니요  
다음은 한 예입니다.  

```
- name: checkMembership
  action: aws:runCommand
  inputs:
    DocumentName: AWS-RunPowerShellScript
    InstanceIds:
      - "{{InstanceIds}}"
    Parameters:
      commands:
        - "(Get-WmiObject -Class Win32_ComputerSystem).PartOfDomain"
    CloudWatchOutputConfig:
      CloudWatchLogGroupName: CloudWatchGroupForSSMAutomationService
      CloudWatchOutputEnabled: true
```

```
{
    "name": "checkMembership",
    "action": "aws:runCommand",
    "inputs": {
        "DocumentName": "AWS-RunPowerShellScript",
        "InstanceIds": [
            "{{InstanceIds}}"
        ],
        "Parameters": {
            "commands": [
                "(Get-WmiObject -Class Win32_ComputerSystem).PartOfDomain"
            ]
        },
        "CloudWatchOutputConfig" : { 
                "CloudWatchLogGroupName": "CloudWatchGroupForSSMAutomationService",
                "CloudWatchOutputEnabled": true
        }
    }
}
```

Comment  
명령에 관한 사용자 정의 정보.  
유형: 문자열  
필수 여부: 아니요

DocumentHash  
문서에 대한 해시.  
유형: 문자열  
필수 여부: 아니요

DocumentHashType  
해시의 유형.  
유형: 문자열  
유효한 값: `Sha256` \$1 `Sha1`  
필수 여부: 아니요

NotificationConfig  
알림 전송에 대한 구성.  
필수 여부: 아니요

OutputS3BucketName  
명령 Output 응답에 대한 S3 버킷의 이름. S3 버킷이 Output을 성공적으로 로깅하려면 관리형 노드에 권한이 있어야 합니다.  
유형: 문자열  
필수 여부: 아니요

OutputS3KeyPrefix  
 접두사입니다.  
유형: 문자열  
필수 여부: 아니요

ServiceRoleArn  
AWS Identity and Access Management(IAM) 역할의 ARN.  
유형: 문자열  
필수 여부: 아니요

TimeoutSeconds  
명령이 인스턴스의 AWS Systems Manager SSM Agent에 전송될 때까지 대기하는 시간(초)입니다. 지정된 값에 도달하기 전에 인스턴스의 SSM Agent에서 명령을 수신하지 않으면 명령 Status가 `Delivery Timed Out`으로 변경됩니다.  
유형: 정수  
필수 여부: 아니요  
유효한 값: 30\$12592000Output

CommandId  
명령의 ID.

Status  
명령 Status.

ResponseCode  
명령의 응답 코드입니다. 실행하는 문서의 단계가 두 개 이상인 경우 이 Output에는 값이 반환되지 않습니다.

Output  
명령의 Output입니다. 명령으로 태그 또는 여러 인스턴스를 대상으로 지정하는 경우 Output 값이 반환되지 않습니다. `GetCommandInvocation` 및 `ListCommandInvocations` API 작업을 사용하여 개별 인스턴스의 Output을 검색할 수 있습니다.

# `aws:runInstances` - Amazon EC2 인스턴스 시작
<a name="automation-action-runinstance"></a>

새로운 Amazon Elastic Compute Cloud(Amazon EC2) 인스턴스를 시작합니다.

**참고**  
`aws:runInstances` 작업은 자동 스로틀링 재시도를 지원합니다. 자세한 내용은 [스로틀링된 작업에 대한 자동 재시도 구성](automation-throttling-retry.md) 섹션을 참조하세요.

**Input**  
이 작업은 대다수 API 파라미터를 지원합니다. 자세한 내용은 [RunInstances](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_RunInstances.html) API 문서를 참조하세요.

------
#### [ YAML ]

```
name: launchInstance
action: aws:runInstances
maxAttempts: 3
timeoutSeconds: 1200
onFailure: Abort
inputs:
  ImageId: ami-12345678
  InstanceType: t2.micro
  MinInstanceCount: 1
  MaxInstanceCount: 1
  IamInstanceProfileName: myRunCmdRole
  TagSpecifications:
  - ResourceType: instance
    Tags:
    - Key: LaunchedBy
      Value: SSMAutomation
    - Key: Category
      Value: HighAvailabilityFleetHost
```

------
#### [ JSON ]

```
{
   "name":"launchInstance",
   "action":"aws:runInstances",
   "maxAttempts":3,
   "timeoutSeconds":1200,
   "onFailure":"Abort",
   "inputs":{
      "ImageId":"ami-12345678",
      "InstanceType":"t2.micro",
      "MinInstanceCount":1,
      "MaxInstanceCount":1,
      "IamInstanceProfileName":"myRunCmdRole",
      "TagSpecifications":[
         {
            "ResourceType":"instance",
            "Tags":[
               {
                  "Key":"LaunchedBy",
                  "Value":"SSMAutomation"
               },
               {
                  "Key":"Category",
                  "Value":"HighAvailabilityFleetHost"
               }
            ]
         }
      ]
   }
}
```

------

AdditionalInfo  
예약.  
유형: 문자열  
필수 여부: 아니요

BlockDeviceMappings  
해당 인스턴스용 블록 디바이스.  
유형: MapList  
필수 여부: 아니요

ClientToken  
요청의 멱등성을 보장하는 식별자.  
유형: 문자열  
필수 여부: 아니요

DisableApiTermination  
인스턴스 API 종료를 설정하거나 해제합니다.  
유형: 부울  
필수 여부: 아니요

EbsOptimized  
Amazon Elastic Block Store(Amazon EBS) 최적화를 설정하거나 해제합니다.  
유형: 부울  
필수 여부: 아니요

IamInstanceProfileArn  
인스턴스에 대한 AWS Identity and Access Management(IAM) 인스턴스 프로파일의 Amazon 리소스 이름(ARN)입니다.  
유형: 문자열  
필수 여부: 아니요

IamInstanceProfileName  
인스턴스용 IAM 인스턴스 프로파일의 이름입니다.  
유형: 문자열  
필수 여부: 아니요

ImageId  
Amazon Machine Image(AMI)의 ID입니다.  
유형: 문자열  
필수 항목 여부: 예

InstanceInitiatedShutdownBehavior  
시스템 종료 시 인스턴스를 중지할지 종료할지 나타냅니다.  
유형: 문자열  
필수 여부: 아니요

InstanceType  
인스턴스 유형.  
인스턴스 유형 값이 제공되지 않은 경우에는 m1 스몰 인스턴스 유형이 사용됩니다.
유형: 문자열  
필수 여부: 아니요

KernelId  
커널 ID.  
유형: 문자열  
필수 여부: 아니요

KeyName  
키 페어 이름.  
유형: 문자열  
필수 여부: 아니요

MaxInstanceCount  
시작되는 인스턴스의 최대 수.  
유형: 문자열  
필수 여부: 아니요

MetadataOptions  
인스턴스에 대한 메타데이터 옵션입니다. 자세한 내용은 [InstanceMetadataOptionsRequest](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_InstanceMetadataOptionsRequest.html)를 참조하세요.  
유형: StringMap  
필수 여부: 아니요

MinInstanceCount  
시작되는 인스턴스의 최소 수.  
유형: 문자열  
필수 여부: 아니요

모니터링  
세부 모니터링을 설정하거나 해제합니다.  
유형: 부울  
필수 여부: 아니요

NetworkInterfaces  
네트워크 인터페이스.  
유형: MapList  
필수 여부: 아니요

배치  
인스턴스 배치.  
유형: StringMap  
필수 여부: 아니요

PrivateIpAddress  
기본 IPv4 주소.  
유형: 문자열  
필수 여부: 아니요

RamdiskId  
RAM 디스크 ID.  
유형: 문자열  
필수 여부: 아니요

SecurityGroupIds  
인스턴스에 대한 보안 그룹의 ID.  
유형: StringList  
필수 여부: 아니요

SecurityGroups  
인스턴스에 대한 보안 그룹의 이름.  
유형: StringList  
필수 여부: 아니요

SubnetId  
서브넷 ID.  
유형: 문자열  
필수 여부: 아니요

TagSpecifications  
시작 시 리소스에 적용되는 태그. 시작 시에만 인스턴스와 볼륨에 태그를 지정할 수 있습니다. 지정된 태그는 시작 시 생성된 모든 인스턴스 또는 볼륨에 적용됩니다. 시작된 후 인스턴스에 태그를 지정하려면 [`aws:createTags` - AWS 리소스에 대한 태그 생성](automation-action-createtag.md) 작업을 사용합니다.  
형식: MapList. 자세한 내용은 [TagSpecification](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_TagSpecification.html)을 참조하세요.  
필수 여부: 아니요

UserData  
문자열 리터럴 값으로 제공된 스크립트입니다. 리터럴 값이 입력되면 Base64로 인코딩되어야 합니다.  
유형: 문자열  
필수 여부: 아니요출력

InstanceIds  
인스턴스의 ID.

InstanceStates  
인스턴스의 현재 상태입니다.

# `aws:sleep` - 자동화 지연
<a name="automation-action-sleep"></a>

지정된 시간 동안 자동화를 지연시킵니다. 이 작업은 ISO(국제 표준화 기구) 8601 날짜 및 시간 형식을 사용합니다. 이 날짜 및 시간 형식에 대한 자세한 내용은 [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html)을 참조하십시오.

**Input**  
지정된 기간 동안 자동화를 지연시킬 수 있습니다.

------
#### [ YAML ]

```
name: sleep
action: aws:sleep
inputs:
  Duration: PT10M
```

------
#### [ JSON ]

```
{
   "name":"sleep",
   "action":"aws:sleep",
   "inputs":{
      "Duration":"PT10M"
   }
}
```

------

또한 지정된 날짜와 시간까지 자동화를 지연시킬 수 있습니다. 지정된 날짜와 시간이 경과하면 작업이 즉시 진행됩니다.

------
#### [ YAML ]

```
name: sleep
action: aws:sleep
inputs:
  Timestamp: '2020-01-01T01:00:00Z'
```

------
#### [ JSON ]

```
{
    "name": "sleep",
    "action": "aws:sleep",
    "inputs": {
        "Timestamp": "2020-01-01T01:00:00Z"
    }
}
```

------

**참고**  
Automation은 최대 지연을 604,799초(7일)까지 지원합니다.

지속 시간  
ISO 8601 기간. 음의 기간을 지정할 수 없습니다.  
유형: 문자열  
필수 여부: 아니요

타임스탬프  
ISO 8601 타임스탬프. 이 파라미터의 값을 지정하지 않으면 `Duration` 파라미터의 값을 지정해야 합니다.  
유형: 문자열  
필수 여부: 아니요출력

없음  


# `aws:updateVariable` - 런북 변수 값을 업데이트
<a name="automation-action-update-variable"></a>

이 작업은 런북 변수 값을 업데이트합니다. 값의 데이터 유형은 업데이트하려는 변수의 데이터 유형과 일치해야 합니다. 데이터 유형 변환은 지원되지 않습니다. 해당 `onCancel` 속성은 `aws:updateVariable` 작업에 지원되지 않습니다.

**Input**  
입력은 다음과 같습니다.

------
#### [ YAML ]

```
name: updateStringList
action: aws:updateVariable
inputs:
    Name: variable:variable name
    Value:
    - "1"
    - "2"
```

------
#### [ JSON ]

```
{
    "name": "updateStringList",
    "action": "aws:updateVariable",
    "inputs": {
        "Name": "variable:variable name",
        "Value": ["1","2"]
    }
}
```

------

이름  
값을 업데이트할 변수의 이름입니다. `variable:variable name` 형식을 사용해야 합니다.  
유형: 문자열  
필수 항목 여부: 예

값  
변수에 할당할 새 값입니다. 값은 변수의 데이터 유형과 일치해야 합니다. 데이터 유형 변환은 지원되지 않습니다.  
형식: Boolean \$1 Integer \$1 MapList \$1 String \$1 StringList \$1 StringMap  
필수 여부: 예  
제약 조건:  
+ MapList는 최대 200개의 항목을 포함할 수 있습니다.
+ 키 길이는 최소 1자이고 최대 길이는 50자입니다.
+ StringList는 최소 0개 항목에서 최대 50개 항목일 수 있습니다.
+ 문자열의 최소 길이는 1자이고 최대 길이는 512자입니다.출력

없음  


# `aws:waitForAwsResourceProperty` - AWS 리소스 속성 대기
<a name="automation-action-waitForAwsResourceProperty"></a>

`aws:waitForAwsResourceProperty` 작업을 사용하면 자동화를 계속 진행하기 전에 자동화에서 특정 리소스 상태나 이벤트 상태를 대기할 수 있습니다. 이 작업을 사용하는 방법에 관한 자세한 내용은 [추가 런북 예제](automation-document-examples.md) 섹션을 참조하세요.

**참고**  
이 작업의 기본 제한 시간 값은 3,600초(1시간)입니다. `aws:waitForAwsResourceProperty` 단계에서 `timeoutSeconds` 파라미터를 지정하여 제한 시간을 제한 또는 연장할 수 있습니다. 이 작업을 사용하는 방법에 관한 자세한 내용과 예제는 [실행서에서 시간 제한 처리](automation-handling-timeouts.md) 섹션을 참조하세요.

**참고**  
`aws:waitForAwsResourceProperty` 작업은 자동 스로틀링 재시도를 지원합니다. 자세한 내용은 [스로틀링된 작업에 대한 자동 재시도 구성](automation-throttling-retry.md) 섹션을 참조하세요.

**Input**  
입력은 선택하는 API 작업에 의해 정의됩니다.

------
#### [ YAML ]

```
action: aws:waitForAwsResourceProperty
inputs:
  Service: The official namespace of the service
  Api: The API operation or method name
  API operation inputs or parameters: A value
  PropertySelector: Response object
  DesiredValues:
  - Desired property value
```

------
#### [ JSON ]

```
{
  "action": "aws:waitForAwsResourceProperty",
  "inputs": {
    "Service":"The official namespace of the service",
    "Api":"The API operation or method name",
    "API operation inputs or parameters":"A value",
    "PropertySelector": "Response object",
    "DesiredValues": [
      "Desired property value"
    ]
  }
}
```

------

서비스  
실행하려는 API 작업을 포함하는 AWS 서비스 네임스페이스입니다. 예를 들면 AWS Systems Manager의 네임스페이스는 `ssm`입니다. Amazon Elastic Compute Cloud(Amazon EC2)의 네임스페이스는 `ec2`입니다. *AWS CLI 명령 참조*의 [사용 가능한 서비스](https://docs.aws.amazon.com/cli/latest/reference/#available-services) 섹션에서 지원되는 AWS 서비스 네임스페이스 목록을 볼 수 있습니다.  
유형: 문자열  
필수 항목 여부: 예

Api  
실행할 API 작업의 이름입니다. 다음 [[서비스 참조(Services Reference)](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/index.html)] 페이지의 왼쪽 탐색 영역에서 서비스를 선택하여 API 작업(메서드라고도 함)을 볼 수 있습니다. 호출할 서비스에 대한 **클라이언트** 섹션에서 메서드를 선택합니다. 예를 들어 Amazon Relational Database Service(Amazon RDS)에 대한 모든 API 작업(메서드)이 [Amazon RDS 메서드](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/rds.html) 페이지에 나열됩니다.  
유형: 문자열  
필수 항목 여부: 예

API 작업 입력  
하나 이상의 API 작업 입력입니다. 다음 [서비스 참조](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/index.html) 페이지의 왼쪽 탐색 영역에서 서비스를 선택하여 사용할 수 있는 입력(파라미터)을 볼 수 있습니다. 호출할 서비스에 대한 **클라이언트** 섹션에서 메서드를 선택합니다. 예를 들어 Amazon RDS에 대한 모든 메서드는 [Amazon RDS 메서드](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/rds.html) 페이지에 나열됩니다. [describe\$1db\$1instances](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/rds.html#RDS.Client.describe_db_instances) 메서드를 선택하고 아래로 스크롤하여 **DBInstanceIdentifier**, **Name** 및 **Values** 같은 사용할 수 있는 파라미터를 볼 수 있습니다.  

```
inputs:
  Service: The official namespace of the service
  Api: The API operation name
  API input 1: A value
  API Input 2: A value
  API Input 3: A value
```

```
"inputs":{
      "Service":"The official namespace of the service",
      "Api":"The API operation name",
      "API input 1":"A value",
      "API Input 2":"A value",
      "API Input 3":"A value"
}
```
형식: 선택한 API 작업에 의해 결정됨  
필수 여부: 예

PropertySelector  
응답 객체의 특정 속성에 대한 JSONPath입니다. 다음 [서비스 참조](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/index.html) 페이지의 왼쪽 탐색 영역에서 서비스를 선택하여 응답 객체를 볼 수 있습니다. 호출할 서비스에 대한 **클라이언트** 섹션에서 메서드를 선택합니다. 예를 들어 Amazon RDS에 대한 모든 메서드는 [Amazon RDS 메서드](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/rds.html) 페이지에 나열됩니다. [describe\$1db\$1instances](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/rds.html#RDS.Client.describe_db_instances) 메서드를 선택하고 **Response Structure(응답 구조)** 섹션이 있는 아래쪽으로 스크롤합니다. **DBInstances**가 응답 객체로 나열됩니다.  
유형: 문자열  
필수 항목 여부: 예

DesiredValues  
필요한 상태 또는 자동화를 계속 진행하기 위해 충족되어야 할 상태입니다.  
유형: MapList, StringList  
필수 여부: 예

# Automation 시스템 변수
<a name="automation-variables"></a>

AWS Systems Manager Automation 실행서는 다음 변수를 사용합니다. 이러한 변수를 사용하는 방법의 예는 `AWS-UpdateWindowsAmi` 실행서의 JSON 원본을 참조하세요.

**`AWS-UpdateWindowsAmi` 실행서의 JSON 소스를 보려면**

1. AWS Systems Manager 콘솔([https://console.aws.amazon.com/systems-manager/](https://console.aws.amazon.com/systems-manager/))을 엽니다.

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

1. 문서 목록에서 검색 창을 사용하거나 검색 창 오른쪽의 숫자를 사용하여 실행서 `AWS-UpdateWindowsAmi`를 선택합니다.

1. **콘텐츠** 탭을 선택합니다.

**시스템 변수**  
Automation 실행서는 다음 시스템 변수를 지원합니다.


****  

| 변수 | Details | 
| --- | --- | 
|  `global:ACCOUNT_ID`  |  Automation이 실행되는 사용자 또는 역할의 AWS 계정 ID입니다.  | 
|  `global:DATE`  |  yyyy-MM-dd 형식의 날짜(런타임 시).  | 
|  `global:DATE_TIME`  |  yyyy-MM-dd\$1HH.mm.ss 형식의 날짜와 시간(런타임 시).  | 
|  `global:AWS_PARTITION`  |  리소스가 있는 파티션. 표준 AWS 리전에서 파티션은 `aws`입니다. 다른 파티션에 있는 리소스의 경우 파티션은 `aws-partitionname`입니다. 예를 들어 AWS GovCloud(미국 서부) 리전의 리소스 파티션은 `aws-us-gov`입니다.  | 
|  `global:REGION`  |  실행서가 실행되는 리전입니다. 예: us-east-2.  | 

**Automation 변수**  
Automation 실행서는 다음 자동화 변수를 지원합니다.


****  

| 변수 | Details | 
| --- | --- | 
|  `automation:EXECUTION_ID`  |  현재 자동화에 할당된 고유 식별자입니다. 예: `1a2b3c-1a2b3c-1a2b3c-1a2b3c1a2b3c1a2b3c`.  | 

**Topics**
+ [

## 용어
](#automation-terms)
+ [

## 지원되는 시나리오
](#automation-variables-support)
+ [

## 지원되지 않는 시나리오
](#automation-variables-unsupported)

## 용어
<a name="automation-terms"></a>

다음 용어는 변수 및 파라미터 확인 방식을 설명합니다.


****  

| 용어 | 정의 | 예 | 
| --- | --- | --- | 
|  Constant ARN  |  변수가 없는 유효한 Amazon 리소스 이름(ARN)입니다.  |  `arn:aws:iam::123456789012:role/roleName`  | 
|  실행서 파라미터  |  실행서 수준에서 정의된 파라미터(예:`instanceId`)입니다. 파라미터는 기본 문자열 대체 항목으로 사용됩니다. 값은 실행 시작 시점에 제공됩니다.  |  <pre>{ <br />   "description": "Create Image Demo",<br />   "version": "0.3",<br />   "assumeRole": "Your_Automation_Assume_Role_ARN",<br />   "parameters":{ <br />      "instanceId": { <br />         "type": "String",<br />         "description": "Instance to create image from"<br />   }<br />}</pre>  | 
|  시스템 변수  |  실행서의 일부를 평가할 때 실행서에 대체 항목으로 제공되는 일반 변수입니다.  |  <pre>"activities": [ <br />   { <br />      "id": "copyImage",<br />      "activityType": "AWS-CopyImage",<br />      "maxAttempts": 1,<br />      "onFailure": "Continue",<br />      "inputs": { <br />         "ImageName": "{{imageName}}",<br />         "SourceImageId": "{{sourceImageId}}",<br />         "SourceRegion": "{{sourceRegion}}",<br />         "Encrypted": true,<br />         "ImageDescription": "Test CopyImage Description created on {{global:DATE}}"<br />      }<br />   }<br />]</pre>  | 
|  자동화 변수  |  실행서의 일부를 평가할 때 실행서에 대체 항목으로 제공되는 자동화 관련 변수입니다.  |  <pre>{ <br />   "name": "runFixedCmds",<br />   "action": "aws:runCommand",<br />   "maxAttempts": 1,<br />   "onFailure": "Continue",<br />   "inputs": { <br />      "DocumentName": "AWS-RunPowerShellScript",<br />      "InstanceIds": [ <br />         "{{LaunchInstance.InstanceIds}}"<br />      ],<br />      "Parameters": { <br />         "commands": [ <br />            "dir",<br />            "date",<br />            "“{{outputFormat}}” -f “left”,”right”,”{{global:DATE}}”,”{{automation:EXECUTION_ID}}”<br />         ]<br />      }<br />   }<br />}</pre>  | 
|  Systems Manager 파라미터  |  AWS Systems Manager Parameter Store에서 정의된 변수입니다. 단계 입력에서는 직접 참조할 수 없습니다. 파라미터에 액세스하려면 권한이 필요할 수 있습니다.  |  <pre><br />description: Launch new Windows test instance<br />schemaVersion: '0.3'<br />assumeRole: '{{AutomationAssumeRole}}'<br />parameters:<br />  AutomationAssumeRole:<br />    type: String<br />    default: ''<br />    description: >-<br />      (Required) The ARN of the role that allows Automation to perform the<br />      actions on your behalf. If no role is specified, Systems Manager<br />      Automation uses your IAM permissions to run this runbook.<br />  LatestAmi:<br />    type: String<br />    default: >-<br />      {{ssm:/aws/service/ami-windows-latest/Windows_Server-2016-English-Full-Base}}<br />    description: The latest Windows Server 2016 AMI queried from the public parameter.<br />mainSteps:<br />  - name: launchInstance<br />    action: 'aws:runInstances'<br />    maxAttempts: 3<br />    timeoutSeconds: 1200<br />    onFailure: Abort<br />    inputs:<br />      ImageId: '{{LatestAmi}}'<br />...</pre>  | 

## 지원되는 시나리오
<a name="automation-variables-support"></a>


****  

| 시나리오 | 설명 | 예 | 
| --- | --- | --- | 
|  생성 시 상수 ARN `assumeRole`.  |  호출 사용자가 지정된 `assumeRole`을 전달하도록 허용되는지 확인하는 권한 부여 확인이 수행됩니다.  |  <pre>{<br />  "description": "Test all Automation resolvable parameters",<br />  "schemaVersion": "0.3",<br />  "assumeRole": "arn:aws:iam::123456789012:role/roleName",<br />  "parameters": { <br />  ...</pre>  | 
|  자동화가 시작될 때 `AssumeRole`에 제공되는 실행서 파라미터입니다.  |  실행서의 파라미터 목록에서 정의되어야 합니다.  |  <pre>{<br />  "description": "Test all Automation resolvable parameters",<br />  "schemaVersion": "0.3",<br />  "assumeRole": "{{dynamicARN}}",<br />  "parameters": {<br /> ...</pre>  | 
|  시작 시 실행서 파라미터에 제공된 값입니다.  |  고객이 파라미터에 사용할 값을 제공합니다. 시작 시 제공된 입력이 실행서의 파라미터 목록에 정의되어야 합니다.  |  <pre>...<br />"parameters": {<br />    "amiId": {<br />      "type": "String",<br />      "default": "ami-12345678",<br />      "description": "list of commands to run as part of first step"<br />    },<br />...</pre> 자동화 실행 시작에 입력되는 항목: `{"amiId" : ["ami-12345678"] }`  | 
|  실행서 내용 내에서 참조되는 Systems Manager 파라미터입니다.  |  변수는 고객의 계정 내에 존재하거나 공개적으로 액세스 가능한 파라미터이며 실행서의 `AssumeRole`은 변수에 액세스할 수 있습니다. 생성 시 `AssumeRole`에 액세스 권한이 있는지 확인이 이루어집니다. 이 파라미터는 단계 입력에서 직접 참조할 수 없습니다.  |  <pre><br />...<br />parameters:<br />    LatestAmi:<br />    type: String<br />    default: >-<br />      {{ssm:/aws/service/ami-windows-latest/Windows_Server-2016-English-Full-Base}}<br />    description: The latest Windows Server 2016 AMI queried from the public parameter.<br />mainSteps:<br />  - name: launchInstance<br />    action: 'aws:runInstances'<br />    maxAttempts: 3<br />    timeoutSeconds: 1200<br />    onFailure: Abort<br />    inputs:<br />      ImageId: '{{LatestAmi}}'<br />...</pre>  | 
|  단계 정의 내에서 참조되는 시스템 변수  |  자동화가 시작될 때 시스템 변수가 실행서로 대체됩니다. 실행서에 입력된 값은 대체가 이루어진 시점과 관련이 있습니다. 즉, 그 사이의 단계를 실행하는 데 걸리는 시간 때문에 1단계에 입력된 시간 변수의 값은 3단계에 입력된 값과 다릅니다. 시스템 변수를 실행서의 파라미터 목록에 설정할 필요가 없습니다.  |  <pre>...<br />  "mainSteps": [<br />    {<br />      "name": "RunSomeCommands",<br />      "action": "aws:runCommand",<br />      "maxAttempts": 1,<br />      "onFailure": "Continue",<br />      "inputs": {<br />        "DocumentName": "AWS:RunPowerShell",<br />        "InstanceIds": ["{{LaunchInstance.InstanceIds}}"],<br />        "Parameters": {<br />            "commands" : [<br />                "echo {The time is now {{global:DATE_TIME}}}"<br />            ]<br />        }<br />    }<br />}, ... </pre>  | 
|  단계 정의 내에서 참조되는 자동화 변수.  |  자동화 변수를 실행서의 파라미터 목록에 설정할 필요가 없습니다. 지원되는 유일한 자동화 변수는 **automation:EXECUTION\$1ID**입니다.  |  <pre>...<br />"mainSteps": [<br />    {<br />      "name": "invokeLambdaFunction",<br />      "action": "aws:invokeLambdaFunction",<br />      "maxAttempts": 1,<br />      "onFailure": "Continue",<br />      "inputs": {<br />        "FunctionName": "Hello-World-LambdaFunction",<br /><br />"Payload" : "{ "executionId" : "{{automation:EXECUTION_ID}}" }"<br />      }<br />    }<br />... </pre>  | 
|  다음 단계 정의에 포함된 이전 단계의 출력을 참조하십시오.  |  이는 파라미터 리디렉션입니다. 이전 단계의 출력은 구문 `{{stepName.OutputName}}`을 이용해 참조됩니다. 고객은 이 구문을 실행서 파라미터에 사용할 수 없습니다. 이것은 참조 단계가 실행될 때 해결됩니다. 파라미터가 실행서의 파라미터에 열거되지 않습니다.  |  <pre>...<br />"mainSteps": [<br />    {<br />      "name": "LaunchInstance",<br />      "action": "aws:runInstances",<br />      "maxAttempts": 1,<br />      "onFailure": "Continue",<br />      "inputs": {<br />        "ImageId": "{{amiId}}",<br />        "MinInstanceCount": 1,<br />        "MaxInstanceCount": 2<br />      }<br />    },<br />    {<br />      "name":"changeState",<br />      "action": "aws:changeInstanceState",<br />      "maxAttempts": 1,<br />      "onFailure": "Continue",<br />      "inputs": {<br />        "InstanceIds": ["{{LaunchInstance.InstanceIds}}"],<br />        "DesiredState": "terminated"<br />      }<br />    }<br /><br />... </pre>  | 

## 지원되지 않는 시나리오
<a name="automation-variables-unsupported"></a>


****  

| 시나리오 | 설명 | 예 | 
| --- | --- | --- | 
|  생성 시 `assumeRole`에 제공되는 Systems Manager 파라미터입니다.  |  지원하지 않음.  |  <pre>...<br /><br />{<br />  "description": "Test all Automation resolvable parameters",<br />  "schemaVersion": "0.3",<br />  "assumeRole": "{{ssm:administratorRoleARN}}",<br />  "parameters": {<br /><br />... </pre>  | 
|  Systems Manager 파라미터는 단계 입력에서 직접 참조할 수 있습니다.  |  생성 시 `InvalidDocumentContent` 예외를 반환합니다.  |  <pre><br />...<br />mainSteps:<br />  - name: launchInstance<br />    action: 'aws:runInstances'<br />    maxAttempts: 3<br />    timeoutSeconds: 1200<br />    onFailure: Abort<br />    inputs:<br />      ImageId: '{{ssm:/aws/service/ami-windows-latest/Windows_Server-2016-English-Full-Base}}'<br />...</pre>  | 
|  변수 단계 정의  |  실행서에서 단계의 정의는 변수에 의해 구성됩니다.  |  <pre>...<br /><br />"mainSteps": [<br />    {<br />      "name": "LaunchInstance",<br />      "action": "aws:runInstances",<br />      "{{attemptModel}}": 1,<br />      "onFailure": "Continue",<br />      "inputs": {<br />        "ImageId": "ami-12345678",<br />        "MinInstanceCount": 1,<br />        "MaxInstanceCount": 2<br />      }<br /><br />...<br /><br />User supplies input : { "attemptModel" : "minAttempts" } </pre>  | 
|  실행서 파라미터 상호 참조  |  시작 시 사용자가 실행서 내 다른 파라미터에 대한 참조인 입력 파라미터를 제공합니다.  |  <pre>...<br />"parameters": {<br />    "amiId": {<br />      "type": "String",<br />      "default": "ami-7f2e6015",<br />      "description": "list of commands to run as part of first step"<br />    },<br />    "alternateAmiId": {<br />      "type": "String",<br />      "description": "The alternate AMI to try if this first fails".<br /><br />"default" : "{{amiId}}"<br />    },<br /><br />... </pre>  | 
|  다중 확장  |  실행서가 변수의 이름으로 평가되는 변수를 정의합니다. 이는 변수 구분 기호(즉 *\$1\$1 \$1\$1*) 내에 포함되고 해당 변수/파라미터의 값으로 확장됩니다.  |  <pre>...<br />  "parameters": {<br />    "firstParameter": {<br />      "type": "String",<br />      "default": "param2",<br />      "description": "The parameter to reference"<br />    },<br />    "secondParameter": {<br />      "type": "String",<br />      "default" : "echo {Hello world}",<br />      "description": "What to run"<br />    }<br />  },<br />  "mainSteps": [{<br />      "name": "runFixedCmds",<br />      "action": "aws:runCommand",<br />      "maxAttempts": 1,<br />      "onFailure": "Continue",<br />      "inputs": {<br />        "DocumentName": "AWS-RunPowerShellScript",<br /><br />"InstanceIds" : "{{LaunchInstance.InstanceIds}}",<br />        "Parameters": {<br />          "commands": [ "{{ {{firstParameter}} }}"]<br /><br />}<br /><br />...<br /><br />Note: The customer intention here would be to run a command of "echo {Hello world}" </pre>  | 
|  변수 유형이 다른 실행서 단계의 출력을 참조  |  사용자가 이후 단계에서 이전 실행서 단계의 출력을 참조합니다. 출력이 이후 단계 작업의 요구 사항을 충족하지 않는 변수 유형입니다.  |  <pre>...<br />mainSteps:<br />- name: getImageId<br />  action: aws:executeAwsApi<br />  inputs:<br />    Service: ec2<br />    Api: DescribeImages<br />    Filters:  <br />    - Name: "name"<br />      Values: <br />      - "{{ImageName}}"<br />  outputs:<br />  - Name: ImageIdList<br />    Selector: "$.Images"<br />    Type: "StringList"<br />- name: copyMyImages<br />  action: aws:copyImage<br />  maxAttempts: 3<br />  onFailure: Abort<br />  inputs:<br />    SourceImageId: {{getImageId.ImageIdList}}<br />    SourceRegion: ap-northeast-2<br />    ImageName: Encrypted Copies of LAMP base AMI in ap-northeast-2<br />    Encrypted: true <br />... <br />Note: You must provide the type required by the Automation action. <br />In this case, aws:copyImage requires a "String" type variable but the preceding step outputs a "StringList" type variable.<br />                                        </pre>  | 

# 사용자 런북 생성
<a name="automation-documents"></a>

Automation 실행서는 자동화가 실행될 때 Systems Manager가 관리형 인스턴스 및 기타 AWS 리소스에 대해 수행하는 *작업*을 정의합니다. Automation은 AWS Systems Manager의 도구입니다. 실행서에는 순차적으로 실행되는 하나 이상의 단계가 포함되어 있습니다. 각 단계는 단일 작업을 중심으로 구축됩니다. 한 단계의 출력을 이후 단계에서 입력으로 사용할 수 있습니다.

이러한 작업과 해당 단계를 실행하는 프로세스를 *자동화*라고 합니다.

실행서에 지원되는 작업 유형을 사용하면 AWS 환경에서 다양한 작업을 자동화할 수 있습니다. 예를 들어 `executeScript` 작업 유형을 사용하면 실행서에 Python 또는 PowerShell 스크립트를 직접 포함할 수 있습니다. 사용자 정의 실행서를 만들 때 스크립트를 인라인으로 추가하거나 S3 버킷 또는 로컬 시스템에서 첨부할 수 있습니다. `createStack` 및 `deleteStack` 작업 유형을 사용하여 AWS CloudFormation 리소스 관리를 자동화할 수 있습니다. 또한 단계는 `executeAwsApi` 작업 유형을 사용하여 AWS 리소스 생성 또는 삭제, 다른 프로세스 시작, 알림 트리거 등 모든 AWS 서비스에서 *모든* API 작업을 실행할 수 있습니다.

Automation에서 지원되는 20가지 작업 유형의 목록은 [Systems Manager Automation 작업 참조](automation-actions.md) 섹션을 참조하세요.

AWS Systems Manager Automation은 Amazon Elastic Compute Cloud(Amazon EC2) 인스턴스를 하나 이상 다시 시작하거나 Amazon Machine Image(AMI)를 생성하는 등 일반적인 태스크를 수행할 수 있는 단계가 사전 정의 되어 있는 몇 가지 실행서를 제공합니다. 자체 실행서를 생성하여 다른 AWS 계정와 공유하거나 모든 Automation 사용자에게 이를 공개할 수도 있습니다.

실행서는 YAML 또는 JSON을 사용하여 작성됩니다. 그러나 Systems Manager Automation 콘솔에서 [**문서 빌더(Document Builder)**]를 사용하면 기본 JSON 또는 YAML로 작성하지 않고도 실행서를 생성할 수 있습니다.

**중요**  
AWS Identity and Access Management(IAM) 서비스 역할을 사용하여 다른 서비스를 호출하는 자동화 워크플로를 실행하는 경우 해당 서비스 역할이 다른 서비스를 호출할 권한이 있도록 구성되어야 합니다. 이 요구 사항은 `AWS-ConfigureS3BucketLogging`, `AWS-CreateDynamoDBBackup`, `AWS-RestartEC2Instance` 실행서 등의 모든 AWS Automation 실행서(`AWS-*` 실행서)에 적용됩니다. 또한 다른 서비스를 호출하는 작업을 사용하여 다른 AWS 서비스을(를) 호출하는 사용자 정의 Automation 실행서를 생성하는 경우에도 이 요구 사항이 항상 적용됩니다. 예를 들어 `aws:executeAwsApi`, `aws:createStack` 또는 `aws:copyImage` 작업을 사용하는 경우 이러한 서비스를 호출할 수 있는 권한을 포함하여 서비스 역할을 구성합니다. 역할에 IAM 인라인 정책을 추가하여 다른 AWS 서비스에 대한 권한을 부여할 수 있습니다. 자세한 내용은 [(선택 사항) 다른 AWS 서비스를 간접적으로 호출할 Automation 인라인 정책과 고객 관리형 정책 추가](automation-setup-iam.md#add-inline-policy) 섹션을 참조하세요.

실행서에서 지정할 수 있는 작업에 대한 자세한 내용은 [Systems Manager Automation 작업 참조](automation-actions.md) 섹션을 참조하세요.

AWS Toolkit for Visual Studio Code를 사용하여 실행서 생성에 대한 자세한 내용은 *AWS Toolkit for Visual Studio Code User Guide*의 [Working with Systems Manager Automation documents](https://docs.aws.amazon.com/toolkit-for-vscode/latest/userguide/systems-manager-automation-docs.html)를 참조하세요.

비주얼 디자이너를 사용하여 사용자 정의 런북을 생성하는 방법에 대한 자세한 내용은 [Automation 런북의 시각적 디자인 경험](automation-visual-designer.md) 섹션을 참조하세요.

**Contents**
+ [

# Automation 런북의 시각적 디자인 경험
](automation-visual-designer.md)
  + [

# 시각적 디자인 경험 인터페이스 개요
](visual-designer-interface-overview.md)
    + [

## 작업 브라우저
](visual-designer-interface-overview.md#visual-designer-actions)
    + [

## Canvas
](visual-designer-interface-overview.md#visual-designer-canvas)
    + [

## 양식
](visual-designer-interface-overview.md#visual-designer-form)
    + [

## 키보드 바로 가기
](visual-designer-interface-overview.md#visual-designer-keyboard-shortcuts)
  + [

# 시각적 디자인 경험 사용
](visual-designer-use.md)
    + [

## 런북 워크플로 생성
](visual-designer-use.md#visual-designer-create-runbook-workflow)
    + [

## 런북 디자인
](visual-designer-use.md#visual-designer-build)
    + [

## 런북 업데이트
](visual-designer-use.md#visual-designer-update-runbook)
    + [

## 런북 내보내기
](visual-designer-use.md#visual-designer-export-runbook)
  + [

# 작업에 대한 입력 및 출력 구성
](visual-designer-action-inputs-outputs.md)
    + [

## 작업에 대한 입력 데이터 제공
](visual-designer-action-inputs-outputs.md#providing-input)
    + [

## 작업의 출력 데이터 정의
](visual-designer-action-inputs-outputs.md#defining-output)
  + [

# 시각적 디자인 경험을 통한 오류 처리
](visual-designer-error-handling.md)
    + [

## 오류 발생 시 조치 재시도
](visual-designer-error-handling.md#retry-actions)
    + [

## 시간 초과
](visual-designer-error-handling.md#timeout-seconds)
    + [

## 실패한 작업
](visual-designer-error-handling.md#failure-actions)
    + [

## 취소된 작업
](visual-designer-error-handling.md#cancel-actions)
    + [

## 중요 작업
](visual-designer-error-handling.md#critical-actions)
    + [

## 종료 작업
](visual-designer-error-handling.md#end-actions)
  + [

# 자습서: 시각적 디자인 환경을 사용하여 런북을 생성합니다.
](visual-designer-tutorial.md)
    + [

## 1단계: 시각적 디자인 환경으로 이동
](visual-designer-tutorial.md#navigate-console)
    + [

## 2단계: 워크플로 생성
](visual-designer-tutorial.md#create-workflow)
    + [

## 3단계: 자동 생성 코드 검토
](visual-designer-tutorial.md#view-generated-code)
    + [

## 4단계: 새 런북 실행
](visual-designer-tutorial.md#use-tutorial-runbook)
    + [

## 5단계: 정리
](visual-designer-tutorial.md#cleanup-tutorial-runbook)
+ [

# Automation 실행서 작성
](automation-authoring-runbooks.md)
  + [

## 사용 사례 식별
](automation-authoring-runbooks.md#automation-authoring-runbooks-use-case)
  + [

## 개발 환경 설정
](automation-authoring-runbooks.md#automation-authoring-runbooks-environment)
  + [

## 실행서 콘텐츠 개발
](automation-authoring-runbooks.md#automation-authoring-runbooks-developing-content)
  + [

# 예 1: 상위-하위 실행서 생성
](automation-authoring-runbooks-parent-child-example.md)
    + [

## 하위 실행서 생성
](automation-authoring-runbooks-parent-child-example.md#automation-authoring-runbooks-child-runbook)
    + [

## 상위 실행서 생성
](automation-authoring-runbooks-parent-child-example.md#automation-authoring-runbooks-parent-runbook)
  + [

# 예제 2: 스크립팅된 실행서
](automation-authoring-runbooks-scripted-example.md)
  + [

# 추가 런북 예제
](automation-document-examples.md)
    + [

# VPC 아키텍처 및 Microsoft Active Directory 도메인 컨트롤러 배포
](automation-document-architecture-deployment-example.md)
    + [

# 최신 스냅샷에서 루트 볼륨 복원
](automation-document-instance-recovery-example.md)
    + [

# AMI 및 크로스 리전 복사본 생성
](automation-document-backup-maintenance-example.md)
+ [

# AWS 리소스를 채우는 입력 파라미터 생성
](populating-input-parameters.md)
+ [

# 문서 빌더를 사용하여 런북 생성
](automation-document-builder.md)
  + [

## 문서 빌더를 사용하여 런북 생성
](automation-document-builder.md#create-runbook)
  + [

## 스크립트를 실행하는 런북 생성
](automation-document-builder.md#create-runbook-scripts)
+ [

# 런북에서 스크립트 사용
](automation-document-script-considerations.md)
  + [

## 실행서 사용 권한
](automation-document-script-considerations.md#script-permissions)
  + [

## 실행서에 스크립트 추가
](automation-document-script-considerations.md#adding-scripts)
  + [

## 실행서에 대한 스크립트 제약 조건
](automation-document-script-considerations.md#script-constraints)
+ [

# 런북에서 조건문 사용
](automation-branch-condition.md)
  + [

## `aws:branch` 작업 수행
](automation-branch-condition.md#branch-action-explained)
    + [

### 실행서에서 `aws:branch` 단계 생성
](automation-branch-condition.md#create-branch-action)
      + [

#### 출력 변수 생성 정보
](automation-branch-condition.md#branch-action-output)
    + [

### 예제 `aws:branch` 실행서
](automation-branch-condition.md#branch-runbook-examples)
    + [

### 연산자를 사용하여 복합 분기 자동화 생성
](automation-branch-condition.md#branch-operators)
  + [

## 조건 옵션 사용 방법의 예
](automation-branch-condition.md#conditional-examples)
+ [

# 작업 출력을 입력으로 사용
](automation-action-outputs-inputs.md)
  + [

## 런북에서 JSONPath 사용
](automation-action-outputs-inputs.md#automation-action-json-path)
+ [

# Automation을 위한 웹후크 통합 생성
](creating-webhook-integrations.md)
  + [

## 통합 생성(콘솔)
](creating-webhook-integrations.md#creating-integrations-console)
  + [

## 통합 생성(명령줄)
](creating-webhook-integrations.md#creating-integrations-commandline)
  + [

## 통합을 위한 웹후크 생성
](creating-webhook-integrations.md#creating-webhooks)
+ [

# 실행서에서 시간 제한 처리
](automation-handling-timeouts.md)

# Automation 런북의 시각적 디자인 경험
<a name="automation-visual-designer"></a>

AWS Systems Manager Automation은 Automation 런북을 만드는 데 도움이 되는 코드가 적은 시각적 디자인 환경을 제공합니다. 시각적 디자인 환경은 자체 코드를 추가할 수 있는 옵션이 포함된 드래그 앤 드롭 인터페이스를 제공하므로 런북을 더 쉽게 만들고 편집할 수 있습니다. 시각적 디자인 환경을 사용하여 다음 작업을 할 수 있습니다.
+ 조건문 제어.
+ 각 동작에 대해 입력과 출력이 필터링되거나 변환되는 방식을 제어할 수 있습니다.
+ 오류 처리를 구성합니다.
+ 새 런북의 프로토타입을 제작하십시오.
+ AWS Toolkit for Visual Studio Code를 사용하여 프로토타입 런북을 로컬 개발의 출발점으로 활용하십시오.

런북을 만들거나 편집할 때 [자동화 콘솔](https://console.aws.amazon.com/systems-manager/automation/home?region=us-east-1#/)에서 시각적 디자인 환경에 액세스할 수 있습니다. 런북을 만들면 시각적 디자인 경험이 작업을 검증하고 코드를 자동으로 생성합니다. 생성된 코드를 검토하거나 로컬 개발을 위해 내보낼 수 있습니다. 작업을 마치면 Systems Manager Automation 콘솔에서 런북을 저장하고 실행하고 결과를 검토할 수 있습니다.

**Topics**
+ [인터페이스 개요](visual-designer-interface-overview.md)
+ [

# 시각적 디자인 경험 사용
](visual-designer-use.md)
+ [입력 및 출력 구성](visual-designer-action-inputs-outputs.md)
+ [

# 시각적 디자인 경험을 통한 오류 처리
](visual-designer-error-handling.md)
+ [

# 자습서: 시각적 디자인 환경을 사용하여 런북을 생성합니다.
](visual-designer-tutorial.md)

# 시각적 디자인 경험 인터페이스 개요
<a name="visual-designer-interface-overview"></a>

Systems Manager Automation의 시각적 디자인 환경은 Automation 런북을 만드는 데 도움이 되는 코드가 적은 시각적 워크플로 디자이너입니다.

인터페이스 구성 요소의 개요를 통해 시각적 디자인 경험에 대해 알아보십시오.

![\[비주얼 디자인 경험 구성 요소\]](http://docs.aws.amazon.com/ko_kr/systems-manager/latest/userguide/images/visual_designer_overview.png)

+ **작업** 브라우저에는 **작업**, **AWS API** 및 **런북** 탭이 있습니다.
+ 캔버스에서는 작업을 워크플로 그래프로 끌어서 놓고, 작업 순서를 변경하고, 구성하거나 볼 작업을 선택할 수 있습니다.
+ **양식** 패널에서는 캔버스에서 선택한 작업의 속성을 보고 편집할 수 있습니다. **콘텐츠** 토글을 선택하면 현재 선택한 작업이 강조 표시된 상태로 런북의 YAML 또는 JSON을 볼 수 있습니다.

도움이 필요할 때 **정보** 링크를 클릭하면 컨텍스트 정보가 포함된 패널이 열립니다. 이 패널에는 Systems Manager Automation 설명서의 관련 항목으로 연결되는 링크도 포함되어 있습니다.

## 작업 브라우저
<a name="visual-designer-actions"></a>

**작업** 브라우저에서 워크플로 그래프로 드래그 앤 드롭할 작업을 선택할 수 있습니다. **작업** 브라우저 상단의 검색 필드를 사용하여 모든 작업을 검색할 수 있습니다. **작업** 브라우저에는 다음과 같은 탭이 있습니다.
+ **작업** 탭은 캔버스에 있는 런북의 워크플로 그래프로 끌어서 놓을 수 있는 자동화 작업 목록을 제공합니다.
+ **AWS API 탭**은 캔버스에 있는 런북의 워크플로 그래프로 드래그 앤 드롭할 수 있는 AWS API 목록을 제공합니다.
+ **런북** 탭에서는 다양한 사용 사례에 사용할 수 있는 구성 요소로 바로 사용할 수 있고 재사용이 가능한 여러 런북을 제공합니다. 예를 들어, 동일한 작업을 다시 생성할 필요 없이 런북을 사용하여 워크플로의 Amazon EC2 인스턴스에 대한 일반적인 수정 작업을 수행할 수 있습니다.

![\[비주얼 디자인 경험 작업 브라우저\]](http://docs.aws.amazon.com/ko_kr/systems-manager/latest/userguide/images/visual_designer_actions_multi_view.png)


## Canvas
<a name="visual-designer-canvas"></a>

자동화에 추가할 작업을 선택한 후 캔버스로 드래그하여 워크플로 그래프에 놓습니다. 작업을 드래그 앤 드롭하여 런북 워크플로의 다른 위치로 이동시킬 수도 있습니다. 작업 과정이 복잡하면 캔버스 패널에서 전체 항목이 보이지 않을 수 있습니다. 캔버스 상단의 컨트롤을 사용하여 확대하거나 축소할 수 있습니다. 워크플로의 다른 부분을 보려면 캔버스에서 워크플로 그래프를 드래그하면 됩니다.

**작업** 브라우저에서 작업을 드래그하여 런북의 워크플로 그래프에 놓습니다. 선이 워크플로에서 배치될 위치를 표시해 줍니다. 작업 순서를 변경하려면 작업 순서를 워크플로의 다른 위치로 드래그할 수 있습니다. 새 작업이 워크플로에 추가되었으며 해당 코드가 자동으로 생성됩니다.

![\[비주얼 디자인 경험 캔버스\]](http://docs.aws.amazon.com/ko_kr/systems-manager/latest/userguide/images/visual_designer_canvas.png)


## 양식
<a name="visual-designer-form"></a>

런북 워크플로에 작업을 추가한 후 사용 사례에 맞게 구성할 수 있습니다. 구성하려는 작업을 선택하면 **양식** 패널에 해당 파라미터와 옵션이 표시됩니다. **콘텐츠** 토글을 선택하여 YAML 또는 JSON 코드를 볼 수도 있습니다. 선택한 작업과 관련된 코드가 강조 표시됩니다.

![\[비주얼 디자인 경험 양식 패널\]](http://docs.aws.amazon.com/ko_kr/systems-manager/latest/userguide/images/visual_designer_form.png)


![\[비주얼 디자인 경험 콘텐츠 패널\]](http://docs.aws.amazon.com/ko_kr/systems-manager/latest/userguide/images/visual_designer_content.png)


## 키보드 바로 가기
<a name="visual-designer-keyboard-shortcuts"></a>

시각적 디자인 환경은 다음 표에 표시된 키보드 단축키를 지원합니다.


| 키보드 바로 가기 | 함수 | 
| --- | --- | 
| Ctrl\$1Z | 마지막 작업의 실행을 취소합니다. | 
| Ctrl\$1Shift\$1Z | 마지막 작업을 다시 실행합니다. | 
| Alt\$1C | 캔버스에서 워크플로를 중앙에 배치합니다. | 
| 백스페이스 | 선택한 모든 상태를 제거합니다. | 
| 삭제 | 선택한 모든 상태를 제거합니다. | 
| Ctrl\$1D | 선택한 상태를 복제합니다. | 

# 시각적 디자인 경험 사용
<a name="visual-designer-use"></a>

시각적 디자인 경험을 사용하여 런북 워크플로를 만들고 편집하고 실행하는 방법을 알아봅니다. 워크플로가 준비되면 저장하거나 내보낼 수 있습니다. 또한 시각적 디자인 환경을 사용하여 프로토타입을 빠르게 만들 수 있습니다.

## 런북 워크플로 생성
<a name="visual-designer-create-runbook-workflow"></a>

1. [Systems Manager Automation 콘솔](https://console.aws.amazon.com/systems-manager/automation/home?region=us-east-1#/)에 로그인합니다.

1. **런북 생성**을 선택합니다.

1. **이름** 상자에 런북 이름을 입력합니다(예: `MyNewRunbook`).

1. **디자인** 및 **코드** 토글 옆의 연필 아이콘을 선택하고 런북의 이름을 입력합니다.

이제 새 런북의 워크플로를 디자인할 수 있습니다.

## 런북 디자인
<a name="visual-designer-build"></a>

 시각적 디자인 경험을 사용하여 런북 워크플로를 디자인하려면 **작업** 브라우저에서 캔버스로 자동화 작업을 드래그하여 런북의 워크플로에서 원하는 위치에 배치합니다. 워크플로에서 작업을 다른 위치로 드래그하여 작업을 재정렬할 수도 있습니다. 작업을 캔버스로 드래그하면 워크플로에서 작업을 놓을 수 있는 모든 위치에 선이 나타납니다. 작업을 캔버스에 놓으면 해당 코드가 자동 생성되어 런북의 콘텐츠에 추가됩니다.

추가하려는 작업의 이름을 알고 있는 경우 **작업** 브라우저 상단의 검색 상자를 사용하여 작업을 찾으세요.

캔버스에 작업을 드롭한 후 오른쪽에 있는 **양식** 패널을 사용하여 작업을 구성합니다. 이 패널에는 캔버스에 배치하는 각 자동화 작업 또는 API 작업에 대한 **일반**, **입력**, **출력** 및 **구성** 탭이 있습니다. 예를 들어 **일반** 탭은 다음 섹션을 포함합니다.
+ **단계 이름**은 단계를 식별합니다. 단계 이름에 고유한 값을 지정합니다.
+ **설명**은 런북의 워크플로에서 작업이 수행하는 작업을 설명하는 데 도움이 됩니다.

**입력** 탭에는 작업에 따라 달라지는 필드가 있습니다. 예를 들어, `aws:executeScript` automation 작업은 다음 섹션을 포함합니다.
+ **런타임**은 제공된 스크립트를 실행하는 데 사용하는 언어입니다.
+ **핸들러**는 함수의 이름입니다. 핸들러에 정의된 함수에 `events` 및 `context`의 두 개의 파라미터가 있는지 확인해야 합니다. PowerShell 런타임은 이 파라미터를 지원하지 않습니다.
+ **스크립트**는 워크플로 중에 실행할 기본 제공 스크립트입니다.
+ (선택 사항) **첨부 파일**은 작업에 의해 호출될 수 있는 독립형 스크립트 또는 .zip 파일용입니다. 이 파라미터는 JSON 런북에서 필수 항목입니다.

**출력** 탭에서는 작업에서 출력할 값을 지정할 수 있습니다. 워크플로의 이후 작업에서 출력 값을 참조하거나 로깅 목적으로 작업의 출력을 생성할 수 있습니다. 모든 작업이 출력을 지원하는 것은 아니므로 모든 작업에 **출력** 탭이 있는 것은 아닙니다. 예를 들어 `aws:pause` 작업은 출력을 지원하지 않습니다. 출력을 지원하는 작업의 경우 **출력** 탭은 다음 섹션으로 구성됩니다.
+ **이름**은 출력 값에 사용할 이름입니다. 워크플로의 이후 작업에서 출력을 참조할 수 있습니다.
+ **선택기**는 JSONPath 표현식 문자열로 JSON 요소 안에서 한 가지 이상의 구성 요소를 선택하는 데 사용되는 `"$."`로 시작됩니다.
+ **유형**은 출력 값의 데이터 유형입니다. 예를 들어 `String` 또는 `Integer` 데이터 유형입니다.

**구성** 탭에는 모든 자동화 작업에서 사용할 수 있는 속성과 옵션이 포함되어 있습니다. 이 템플릿은 다음 섹션으로 구성됩니다.
+ **Max attempts** 속성은 작업이 실패할 경우 작업을 재시도하는 횟수입니다.
+ **Timeout seconds** 속성은 작업의 제한 시간 값을 지정합니다.
+ **Is critical** 속성은 작업 실패로 인해 전체 자동화가 중지되는지 여부를 결정합니다.
+ **Next step** 속성은 런북에서 자동화가 다음으로 진행될 작업을 결정합니다.
+ **On failure** 속성은 작업이 실패할 경우 자동화가 런북에서 다음으로 진행할 작업을 결정합니다.
+ **On cancel** 속성은 사용자가 작업을 취소한 경우 자동화가 런북에서 다음 단계로 넘어갈 작업을 결정합니다.

작업을 삭제하려면 캔버스 위의 도구 모음인 백스페이스를 사용하거나 마우스 오른쪽 버튼을 클릭하고 **작업 삭제**를 선택하면 됩니다.

워크플로가 커지면 캔버스에 맞지 않을 수 있습니다. 워크플로를 캔버스에 맞게 만들려면 다음 옵션 중 하나를 시도할 수 있습니다.
+ 측면 패널의 컨트롤을 사용하여 패널의 크기를 조정하거나 패널을 닫습니다.
+ 캔버스 상단의 툴바를 사용하여 워크플로 그래프를 확대하거나 축소할 수 있습니다.

## 런북 업데이트
<a name="visual-designer-update-runbook"></a>

새 버전의 런북을 생성하여 기존 런북 워크플로를 업데이트할 수 있습니다. 시각적 디자인 환경을 사용하거나 코드를 직접 편집하여 런북을 업데이트할 수 있습니다. 기존 런북을 업데이트하려면 다음 절차를 따르십시오.

1. [Systems Manager Automation 콘솔](https://console.aws.amazon.com/systems-manager/automation/home?region=us-east-1#/)에 로그인합니다.

1. 업데이트할 런북을 선택합니다.

1. **새로운 버전 생성**을 선택합니다.

1. 시각적 디자인 환경에는 코드 창과 시각적 워크플로 창이라는 두 개의 창이 있습니다. 시각적 워크플로 창에서 **디자인**을 선택하여 시각적 디자인 경험으로 워크플로를 편집합니다. 작업을 마쳤으면 **새 버전 생성**을 선택하여 변경 사항을 저장하고 종료합니다.

1. (선택 사항) 코드 패널을 사용하여 YAML 또는 JSON에서 런북 콘텐츠를 편집합니다.

## 런북 내보내기
<a name="visual-designer-export-runbook"></a>

런북의 워크플로 YAML 또는 JSON 코드와 워크플로 그래프를 내보내려면 다음 절차를 사용하십시오.

1. **문서** 콘솔에서 런북을 선택합니다.

1. **새로운 버전 생성**을 선택합니다.

1. **작업** 드롭다운에서 그래프 또는 런북을 내보낼지 여부와 원하는 형식을 선택합니다.

# 작업에 대한 입력 및 출력 구성
<a name="visual-designer-action-inputs-outputs"></a>

각 자동화 작업은 수신한 입력에 따라 응답합니다. 대부분의 경우 출력을 후속 작업에 전달합니다. 시각적 디자인 환경에서는 **양식** 패널의 **입력** 및 **출력** 탭에서 작업의 입력 및 출력 데이터를 구성할 수 있습니다.

자동화 작업의 출력을 정의하고 사용하는 방법에 대한 자세한 내용은 [작업 출력을 입력으로 사용](automation-action-outputs-inputs.md) 단원을 참조하십시오.

## 작업에 대한 입력 데이터 제공
<a name="providing-input"></a>

자동화 작업마다 값을 제공해야 하는 한 가지 이상의 입력이 있습니다. 작업 입력에 제공하는 값은 작업에 허용되는 데이터 유형 및 형식에 따라 결정됩니다. 예를 들어 `aws:sleep` 작업의 `Duration` 입력에는 ISO 8601 형식의 문자열 값이 필요합니다.

일반적으로 런북의 워크플로에서는 후속 작업에서 사용하려는 출력을 반환하는 작업을 사용합니다. 런북 워크플로에서 오류가 발생하지 않도록 입력 값이 올바른지 확인하는 것이 중요합니다. 입력 값은 작업이 예상 출력을 반환하는지 여부를 결정하므로 중요합니다. 예를 들어 `aws:executeAwsApi` 작업을 사용할 때는 API 작업에 적합한 값을 제공하고 있는지 확인해야 합니다.

## 작업의 출력 데이터 정의
<a name="defining-output"></a>

일부 자동화 동작은 정의된 작업을 수행한 후 출력을 반환합니다. 출력을 반환하는 작업에는 사전 정의된 출력이 있거나 사용자가 직접 출력을 정의할 수 있습니다. 예를 들어, `aws:createImage` 작업에는 `ImageId` 및 `ImageState`를 반환하는 사전 정의된 출력이 있습니다. 이에 비해 `aws:executeAwsApi` 작업을 사용하면 지정된 API 작업에서 원하는 출력을 정의할 수 있습니다. 따라서 단일 API 작업에서 하나 이상의 값을 반환하여 후속 작업에 사용할 수 있습니다.

자동화 작업에 대한 자체 출력을 정의하려면 출력 이름, 데이터 유형 및 출력 값을 지정해야 합니다. `aws:executeAwsApi` 작업을 계속 예로 들어 Amazon EC2에서 `DescribeInstances` API 작업을 직접적으로 호출한다고 가정해 보겠습니다. 이 예제에서는 `State` Amazon EC2 인스턴스를 반환하거나 출력하고 출력을 기반으로 런북의 워크플로를 분기하려고 합니다. **InstanceState** 출력의 이름을 지정하고 **String** 데이터 유형을 사용하도록 선택합니다.  

출력의 실제 값을 정의하는 프로세스는 작업에 따라 다릅니다. 예를 들어 `aws:executeScript` 작업을 사용하는 경우 함수에 `return` 명령문을 사용하여 출력값에 데이터를 제공해야 합니다. `aws:executeAwsApi`, `aws:waitForAwsResourceProperty` 및 `aws:assertAwsResourceProperty`과 같은 다른 작업에서는 `Selector`가 필수입니다. `Selector` 또는 일부 작업에서 참조하는 `PropertySelector`는 JSONPath 문자열로 API 작업의 JSON 응답을 처리하는 데 사용되는 문자열입니다. 출력에 적합한 값을 선택할 수 있으려면 API 작업의 JSON 응답 객체가 어떻게 구조화되는지 이해하는 것이 중요합니다. 앞서 언급한 `DescribeInstances` API 작업을 사용하는 방법은 다음 JSON 응답 예시를 참조하십시오.

```
{
  "reservationSet": {
    "item": {
      "reservationId": "r-1234567890abcdef0",
      "ownerId": 123456789012,
      "groupSet": "",
      "instancesSet": {
        "item": {
          "instanceId": "i-1234567890abcdef0",
          "imageId": "ami-bff32ccc",
          "instanceState": {
            "code": 16,
            "name": "running"
          },
          "privateDnsName": "ip-192-168-1-88.eu-west-1.compute.internal",
          "dnsName": "ec2-54-194-252-215.eu-west-1.compute.amazonaws.com",
          "reason": "",
          "keyName": "my_keypair",
          "amiLaunchIndex": 0,
          "productCodes": "",
          "instanceType": "t2.micro",
          "launchTime": "2018-05-08T16:46:19.000Z",
          "placement": {
            "availabilityZone": "eu-west-1c",
            "groupName": "",
            "tenancy": "default"
          },
          "monitoring": {
            "state": "disabled"
          },
          "subnetId": "subnet-56f5f000",
          "vpcId": "vpc-11112222",
          "privateIpAddress": "192.168.1.88",
          "ipAddress": "54.194.252.215",
          "sourceDestCheck": true,
          "groupSet": {
            "item": {
              "groupId": "sg-e4076000",
              "groupName": "SecurityGroup1"
            }
          },
          "architecture": "x86_64",
          "rootDeviceType": "ebs",
          "rootDeviceName": "/dev/xvda",
          "blockDeviceMapping": {
            "item": {
              "deviceName": "/dev/xvda",
              "ebs": {
                "volumeId": "vol-1234567890abcdef0",
                "status": "attached",
                "attachTime": "2015-12-22T10:44:09.000Z",
                "deleteOnTermination": true
              }
            }
          },
          "virtualizationType": "hvm",
          "clientToken": "xMcwG14507example",
          "tagSet": {
            "item": {
              "key": "Name",
              "value": "Server_1"
            }
          },
          "hypervisor": "xen",
          "networkInterfaceSet": {
            "item": {
              "networkInterfaceId": "eni-551ba000",
              "subnetId": "subnet-56f5f000",
              "vpcId": "vpc-11112222",
              "description": "Primary network interface",
              "ownerId": 123456789012,
              "status": "in-use",
              "macAddress": "02:dd:2c:5e:01:69",
              "privateIpAddress": "192.168.1.88",
              "privateDnsName": "ip-192-168-1-88.eu-west-1.compute.internal",
              "sourceDestCheck": true,
              "groupSet": {
                "item": {
                  "groupId": "sg-e4076000",
                  "groupName": "SecurityGroup1"
                }
              },
              "attachment": {
                "attachmentId": "eni-attach-39697adc",
                "deviceIndex": 0,
                "status": "attached",
                "attachTime": "2018-05-08T16:46:19.000Z",
                "deleteOnTermination": true
              },
              "association": {
                "publicIp": "54.194.252.215",
                "publicDnsName": "ec2-54-194-252-215.eu-west-1.compute.amazonaws.com",
                "ipOwnerId": "amazon"
              },
              "privateIpAddressesSet": {
                "item": {
                  "privateIpAddress": "192.168.1.88",
                  "privateDnsName": "ip-192-168-1-88.eu-west-1.compute.internal",
                  "primary": true,
                  "association": {
                    "publicIp": "54.194.252.215",
                    "publicDnsName": "ec2-54-194-252-215.eu-west-1.compute.amazonaws.com",
                    "ipOwnerId": "amazon"
                  }
                }
              },
              "ipv6AddressesSet": {
                "item": {
                  "ipv6Address": "2001:db8:1234:1a2b::123"
                }
              }
            }
          },
          "iamInstanceProfile": {
            "arn": "arn:aws:iam::123456789012:instance-profile/AdminRole",
            "id": "ABCAJEDNCAA64SSD123AB"
          },
          "ebsOptimized": false,
          "cpuOptions": {
            "coreCount": 1,
            "threadsPerCore": 1
          }
        }
      }
    }
  }
}
```

JSON 응답 객체에서 `State` 인스턴스는 `Instances` 객체에 중첩되며, 해당 객체는 `Reservations` 객체에 중첩됩니다. `State` 인스턴스의 값을 반환하려면 출력에 해당 값을 사용할 수 있도록 `Selector`에 다음 문자열을 사용하십시오. **\$1.Reservations[0].Instances[0].State.Name** 

런북 워크플로의 후속 작업에서 출력 값을 참조하려면 `{{ StepName.NameOfOutput }}` 형식이 사용됩니다. 예를 들어 **\$1\$1 GetInstanceState.InstanceState \$1\$1**입니다. 시각적 디자인 환경에서는 입력용 드롭다운을 사용하여 후속 작업에 사용할 출력 값을 선택할 수 있습니다. 후속 작업에서 출력을 사용할 때는 출력의 데이터 유형이 입력의 데이터 유형과 일치해야 합니다. 이 예시에서 `InstanceState`​​ 출력은 `String`입니다. 따라서 후속 작업의 입력에서 값을 사용하려면 입력에서 `String`을 받아야 합니다.

# 시각적 디자인 경험을 통한 오류 처리
<a name="visual-designer-error-handling"></a>

기본적으로 작업에서 오류가 보고되면 Automation은 런북의 워크플로를 완전히 중지합니다. 이는 모든 작업의 `onFailure` 속성 기본값이 `Abort`이기 때문입니다. Automation이 런북 워크플로의 오류를 처리하는 방법을 구성할 수 있습니다. 오류 처리를 구성했더라도 일부 오류로 인해 자동화가 실패할 수 있습니다. 자세한 내용은 [Systems Manager Automation 문제 해결](automation-troubleshooting.md) 섹션을 참조하세요. 시각적 디자인 환경에서는 **구성** 패널에서 오류 처리를 구성합니다.

![\[오류 처리 옵션\]](http://docs.aws.amazon.com/ko_kr/systems-manager/latest/userguide/images/visual_designer_error_handling.png)


## 오류 발생 시 조치 재시도
<a name="retry-actions"></a>

오류가 발생한 경우 작업을 재시도하려면 **Max attempts** 속성 값을 지정하십시오. 기본값은 1입니다. 지정된 값이 1보다 크면 모든 재시도가 실패할 때까지 해당 단계는 실패한 것으로 간주되지 않습니다.

## 시간 초과
<a name="timeout-seconds"></a>

작업 제한 시간을 구성하여 작업이 실패하기 전에 실행할 수 있는 최대 시간(초)을 설정할 수 있습니다. 제한 시간을 구성하려면 **Timeout seconds** 속성에 작업이 실패하기 전에 작업이 기다려야 하는 시간을 초로 입력합니다. 시간 제한에 도달했지만 작업의 `Max attempts` 값이 1보다 큰 경우 단계는 모든 재시도 횟수가 시도될 때까지 시간이 초과된 것으로 간주되지 않습니다.

## 실패한 작업
<a name="failure-actions"></a>

기본적으로 작업이 실패하면 Automation은 런북의 워크플로를 완전히 중지합니다. 런북에 있는 작업의 **On failure** 속성에 대체 값을 지정하여 이 동작을 수정할 수 있습니다. 워크플로를 런북의 다음 단계로 계속 진행하려면 **계속**을 선택합니다. 워크플로를 런북의 다른 후속 단계로 바로 이동시키려면 **단계**를 선택한 다음 단계 이름을 입력합니다.

## 취소된 작업
<a name="cancel-actions"></a>

기본적으로 사용자가 작업을 취소하면 Automation은 런북의 워크플로를 완전히 중지합니다. 런북에 있는 작업의 **On cancel** 속성에 대체 값을 지정하여 이 동작을 수정할 수 있습니다. 워크플로를 런북의 다른 후속 단계로 바로 이동시키려면 **단계**를 선택한 다음 단계 이름을 입력합니다.

## 중요 작업
<a name="critical-actions"></a>

조치를 중요 조치로 지정할 수 있습니다. 즉, 해당 조치가 자동화의 전체 보고 상태를 결정합니다. 이 지정이 있는 단계 중 하나가 실패하면 Automation은 다른 작업의 성공 여부와 관계없이 `Failed` 상태로 최종 상태를 보고합니다. 작업을 중요한 작업으로 구성하려면 **Is critical** 속성의 기본값을 **True**로 그대로 두십시오.

## 종료 작업
<a name="end-actions"></a>

**Is end** 속성은 지정된 작업 종료 시 자동화를 적절히 중지합니다. 이 속성의 기본값은 `false`입니다. 작업에 대해 이 속성을 구성하면 작업의 성공 여부에 관계없이 자동화가 중지됩니다. 이 속성은 예상치 못한 입력값이나 정의되지 않은 입력값을 처리하기 위한 `aws:branch` 작업과 함께 가장 자주 사용됩니다. 다음 예제는 인스턴스 상태가`running`, `stopping` 또는 `stopped`일 것으로 예상되는 런북을 보여줍니다. 인스턴스의 상태가 다른 경우 자동화가 종료됩니다.

![\[시각적 디자인 경험이 그 예입니다.\]](http://docs.aws.amazon.com/ko_kr/systems-manager/latest/userguide/images/visual_designer_is_end_example.png)


# 자습서: 시각적 디자인 환경을 사용하여 런북을 생성합니다.
<a name="visual-designer-tutorial"></a>

이 자습서에서는 Systems Manager Automation에서 제공하는 시각적 디자인 환경을 사용하여 작업하는 기본 사항을 학습합니다. 시각적 디자인 환경에서 여러 작업을 사용하는 런북을 만들 수 있습니다. 드래그 앤 드롭 기능을 사용하여 캔버스에 작업을 정렬할 수 있습니다. 또한 이러한 작업을 검색, 선택 및 구성할 수 있습니다. 그런 다음 런북의 워크플로에 대해 자동 생성된 YAML 코드를 확인하고, 시각적 디자인 환경을 종료하고, 런북을 실행하고, 실행 세부 정보를 검토할 수 있습니다.

이 자습서에서는 런북을 업데이트하고 새 버전을 보는 방법도 보여줍니다. 자습서가 끝나면 정리 단계를 수행하고 런북을 삭제하게 됩니다.

이 자습서를 완료하면 시각적 디자인 경험을 사용하여 런북을 만드는 방법을 알게 됩니다. 또한 런북을 업데이트, 실행 및 삭제하는 방법도 알게 됩니다.

**참고**  
이 자습서를 시작하기 전에 [Automation 설정](automation-setup.md) 항목을 완료했는지 확인하세요.

**Topics**
+ [

## 1단계: 시각적 디자인 환경으로 이동
](#navigate-console)
+ [

## 2단계: 워크플로 생성
](#create-workflow)
+ [

## 3단계: 자동 생성 코드 검토
](#view-generated-code)
+ [

## 4단계: 새 런북 실행
](#use-tutorial-runbook)
+ [

## 5단계: 정리
](#cleanup-tutorial-runbook)

## 1단계: 시각적 디자인 환경으로 이동
<a name="navigate-console"></a>

1. [Systems Manager Automation 콘솔](https://console.aws.amazon.com/systems-manager/automation/home?region=us-east-1#/)에 로그인합니다.

1. **자동화 생성**을 선택합니다.

## 2단계: 워크플로 생성
<a name="create-workflow"></a>

시각적 디자인 환경에서 워크플로는 캔버스에 런북을 그래픽으로 표현한 것입니다. 시각적 디자인 경험을 사용하여 런북의 개별 작업을 정의, 구성 및 검토할 수 있습니다.

**워크플로 생성 방법**

1. **디자인** 및 **코드** 토글 옆의 연필 아이콘을 선택하고 런북의 이름을 입력합니다. 이 자습서에서는 **VisualDesignExperienceTutorial**을 입력합니다.  
![\[비주얼 디자인 경험: 런북 이름 정하기\]](http://docs.aws.amazon.com/ko_kr/systems-manager/latest/userguide/images/visual_designer_tutorial_name.png)

1. **양식** 패널의 **문서 속성** 섹션에서 **입력 파라미터** 드롭다운을 펼치고 **파라미터 추가**를 선택합니다.

   1. **파라미터 이름** 필드에 **InstanceId**를 입력합니다.

   1. **유형** 드롭다운에서 **AWS::EC2::인스턴스**를 선택합니다.

   1. **필수** 토글을 선택합니다.  
![\[런북용 파라미터 생성\]](http://docs.aws.amazon.com/ko_kr/systems-manager/latest/userguide/images/visual_designer_actions_tutorial_parameter.png)

1. **AWS API** 브라우저의 검색 창에 **DescribeInstances**를 입력합니다.

1. **Amazon EC2 — DescribeInstances** 작업을 빈 캔버스로 드래그하십시오.

1. **단계 이름**에 값을 입력합니다. 본 자습서에서는 **GetInstanceState** 이름을 사용할 수 있습니다.  
![\[Amazon EC2 describe 인스턴스 API 작업을 선택합니다.\]](http://docs.aws.amazon.com/ko_kr/systems-manager/latest/userguide/images/visual_designer_tutorial_api_action.png)

   1. **추가 입력** 드롭다운을 확장하고 **입력 이름** 필드에 **InstanceIds**를 입력합니다.

   1. **입력** 탭을 선택합니다.

   1. **입력 값** 필드에서 **InstanceId** 문서 입력을 선택합니다. 이 값은 프로시저를 시작할 때 생성한 입력 파라미터의 값을 참조합니다. `DescribeInstances` 작업에 대한 **InstanceIds** 입력은 `StringList` 값을 허용하므로 **InstanceId** 입력을 대괄호로 묶어야 합니다. **입력 값**의 YAML은 다음과 일치해야 합니다. **['\$1\$1 InstanceId \$1\$1']** 

   1. **출력** 탭에서 **출력 추가**를 선택하고 **이름** 필드에 **InstanceState**를 입력합니다.

   1. **선택기** 필드에 **\$1.Reservations[0].Instances[0].State.Name** 항목을 입력합니다.

   1. **유형** 드롭다운에서 **문자열**을 선택합니다.

1. **작업** 브라우저에서 **분기** 작업을 드래그하여 **`GetInstanceState`**단계 아래에 놓습니다.

1. **단계 이름**에 값을 입력합니다. 본 튜토리얼에서는 `BranchOnInstanceState`의 이름을 사용합니다.

   분기 로직을 정의하려면 다음을 수행합니다.

   1. 캔버스에서 **`Branch`**상태를 선택합니다. 그런 다음 **입력** 및 **선택**에서 연필 아이콘을 선택하여 **규칙 \$11** 를 편집합니다.

   1. **조건 추가**를 선택합니다.

   1. **규칙 \$11 조건** 대화 상자의 **변수** 드롭다운에서 **GetInstanceState.InstanceState** 단계 출력을 선택합니다.

   1. **연산자**에서 **같음**을 선택합니다.

   1. **값**의 경우. 드롭다운 목록에서 **문자열**을 선택합니다. **stopped**을 입력합니다.  
![\[분기 작업의 조건을 정의합니다.\]](http://docs.aws.amazon.com/ko_kr/systems-manager/latest/userguide/images/visual_designer_tutorial_condition.png)

   1. **조건 저장**을 선택합니다.

   1. **새 선택 규칙 추가**를 선택합니다.

   1. **규칙 \$12** **조건 추가**를 선택합니다.

   1. **규칙 \$12 조건** 대화 상자의 **변수** 드롭다운에서 **GetInstanceState.InstanceState**단계 출력을 선택합니다.

   1. **연산자**에서 **같음**을 선택합니다.

   1. **값**의 경우. 드롭다운 목록에서 **문자열**을 선택합니다. **stopping**을 입력합니다.

   1. **조건 저장**을 선택합니다.

   1. **새 선택 규칙 추가**를 선택합니다.

   1. **규칙 \$13** 에서는 **조건 추가**를 선택합니다.

   1. **규칙 \$13 조건** 대화 상자의 **변수** 드롭다운에서 **GetInstanceState.InstanceState**단계 출력을 선택합니다.

   1. **연산자**에서 **같음**을 선택합니다.

   1. **값**의 경우. 드롭다운 목록에서 **문자열**을 선택합니다. **running**을 입력합니다.

   1. **조건 저장**을 선택합니다.

   1. **기본 규칙**에서 **기본 단계**로 **Go to end**를 선택합니다.

1. **인스턴스 상태 변경** 작업을 **\$1\$1 GetInstanceState.InstanceState \$1\$1 == "stopped"** 조건 아래의 비어 있는 **이곳으로 작업 드래그** 상자로 드래그하십시오.

   1. **단계 이름**에는 **StartInstance**를 입력합니다.

   1. **입력** 탭의 **인스턴스 ID** 아래에 있는 드롭다운에서 **InstanceID** 문서 입력 값을 선택합니다.

   1. **원하는 상태**에는 **`running`** 항목을 지정합니다.

1. **AWS 리소스 대기** 작업을 **\$1\$1 GetInstanceState.InstanceState \$1\$1 == "stopping"** 조건 아래의 비어 있는 **이곳으로 작업 드래그**로 드래그하십시오.

1. **단계 이름**에 값을 입력합니다. 본 튜토리얼에서는 `WaitForInstanceStop`의 이름을 사용합니다.

   1. **서비스** 필드에서 **Amazon EC2**를 선택합니다.

   1. **API** 필드에서 **DescribeInstances**를 선택합니다.

   1. **속성 선택기** 필드에 **\$1.Reservations[0].Instances[0].State.Name**를 입력합니다.

   1. **원하는 값** 파라미터의 경우 **`["stopped"]`**를 입력합니다.

   1. **WaitForInstanceStop 작업의 **구성** 탭에 있는 다음 단계 드롭다운에서 인스턴스** ****시작을** 선택합니다.**

1. **인스턴스에서 명령 실행** 작업을 **\$1\$1 GetInstanceState.InstanceState \$1\$1 == "running"** 조건의 비어 있는 **이곳으로 작업 드래그** 박스로 드래그하십시오.

1. **단계 이름**에는 **SayHello**를 입력합니다.

   1. **입력** 탭에서 **문서 이름** 파라미터로 **AWS-RunShellScript**를 입력합니다.

   1. **InstanceID의** 경우 드롭다운에서 **InstanceID** 문서 입력 값을 선택합니다.

   1. **추가 입력** 드롭다운을 확장하고 **이름 입력** 드롭다운에서 **파라미터**를 선택합니다.

   1. **입력 값** 필드에 **`{"commands": "echo 'Hello World'"}`**를 입력합니다.

1. 캔버스에서 완성된 런북을 검토하고 **런북 생성**을 선택하여 튜토리얼 런북을 저장합니다.  
![\[검토하고 런북을 생성합니다.\]](http://docs.aws.amazon.com/ko_kr/systems-manager/latest/userguide/images/visual_designer_tutorial_complete.png)

## 3단계: 자동 생성 코드 검토
<a name="view-generated-code"></a>

**작업** 브라우저에서 캔버스로 작업을 드래그 앤 드롭하면 시각적 디자인 경험이 런북의 YAML 또는 JSON 콘텐츠를 실시간으로 자동으로 작성합니다. 이 코드를 보고 편집할 수 있습니다. 자동 생성된 코드를 보려면 **디자인**용 **코드** 및 **코드** 토글을 선택합니다.

## 4단계: 새 런북 실행
<a name="use-tutorial-runbook"></a>

런북을 만든 후 자동화를 실행할 수 있습니다.

**새 Automation 런북 실행 방법**

1. AWS Systems Manager 콘솔[https://console.aws.amazon.com/systems-manager/](https://console.aws.amazon.com/systems-manager/)을 엽니다.

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

1. [**Automation 문서(Automation document)**] 목록에서 실행서를 선택합니다. **문서 카테고리** 창에서 옵션을 1개 이상 선택하여 SSM 문서를 목적에 따라 필터링합니다. 자신이 소유한 실행서를 보려면 [**내 소유(Owned by me)**] 탭을 선택합니다. 자신의 계정과 공유하고 있는 실행서를 보려면 [**나와 공유됨(Shared with me)**] 탭을 선택합니다. 모든 실행서를 보려면 [**모든 문서(All documents)**] 탭을 선택합니다.
**참고**  
실행서 이름을 선택하여 실행서에 대한 정보를 볼 수 있습니다.

1. **문서 세부 정보** 섹션에서 **문서 버전**이 실행할 버전으로 설정되었는지 확인합니다. 이 시스템에는 다음 버전 옵션이 포함되어 있습니다.
   + **런타임 시 기본 버전** - Automation 런북이 정기적으로 업데이트되며 새 기본 버전이 할당된 경우 이 옵션을 선택합니다.
   + **런타임 시 최신 버전** - Automation 런북이 정기적으로 업데이트되며 최근에 업데이트된 버전을 실행하려는 경우 이 옵션을 선택합니다.
   + **1(기본값)** - 문서의 최초 버전을 실행하려면 이 옵션을 선택합니다(기본값).

1. **다음**을 선택합니다.

1. **자동화 문서 실행** 섹션에서 **단순 실행**을 선택합니다.

1. **입력 파라미터** 섹션에서 필수 입력을 지정합니다. 필요에 따라 **AutomationAssumeRole** 목록에서 IAM 서비스 역할을 선택합니다.

1. (선택 사항) 모니터링을 위해 자동화에 적용할 Amazon CloudWatch 경보를 선택합니다. CloudWatch 경보를 자동화에 연결하려면 자동화를 시작하는 IAM 보안 주체에 `iam:createServiceLinkedRole` 작업에 대한 권한이 있어야 합니다. CloudWatch 경보에 대한 자세한 내용은 [Amazon CloudWatch 경보 사용](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/AlarmThatSendsEmail.html)을 참조하세요. 경보가 활성화되면 자동화가 중지됩니다. AWS CloudTrail을 사용하면 추적에 API 호출이 표시됩니다.

1. **실행**을 선택합니다.

## 5단계: 정리
<a name="cleanup-tutorial-runbook"></a>

**런북 삭제 방법**

1. AWS Systems Manager 콘솔([https://console.aws.amazon.com/systems-manager/](https://console.aws.amazon.com/systems-manager/))을 엽니다.

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

1. **내 소유** 탭을 선택합니다.

1. **VisualDesignExperienceTutorial** 런북을 찾습니다.

1. 문서 카드 페이지에서 버튼을 선택한 다음 **작업** 드롭다운에서 **문서 삭제**를 선택합니다.

# Automation 실행서 작성
<a name="automation-authoring-runbooks"></a>

AWS Systems Manager의 도구인 Automation의 각 런북은 자동화를 정의합니다. Automation 실행서는 자동화 중 수행되는 작업을 정의합니다. 실행서 내용에 Systems Manager가 관리형 인스턴스 및 AWS 리소스에 대해 수행하는 입력 파라미터, 출력 및 작업을 정의합니다.

Automation에는 사전 정의된 실행서가 몇 가지 포함되며, 이들 실행서를 사용하여 Amazon Elastic Compute Cloud(Amazon EC2) 인스턴스를 하나 이상 다시 시작하거나 Amazon Machine Image(AMI)를 생성하는 등 일반적인 태스크를 수행할 수 있습니다. 그러나 사용 사례가 미리 정의된 실행서의 기능 이상으로 확장될 수 있습니다. 이 경우 사용자 고유의 실행서를 생성하고 필요에 맞게 수정할 수 있습니다.

실행서는 자동화 작업, 이러한 작업에 대한 파라미터 및 사용자가 지정하는 입력 파라미터로 구성됩니다. 실행서의 내용은 YAML 또는 JSON으로 작성됩니다. YAML 또는 JSON에 익숙하지 않은 경우 비주얼 디자이너를 사용하거나 자체 런북을 작성하기 전에 마크업 언어를 자세히 알아보는 것이 좋습니다. 비주얼 디자이너에 대한 자세한 내용은 [Automation 런북의 시각적 디자인 경험](automation-visual-designer.md) 섹션을 참조하세요.

다음 섹션은 첫 번째 실행서를 작성하는 데 도움이 됩니다.

## 사용 사례 식별
<a name="automation-authoring-runbooks-use-case"></a>

실행서 작성의 첫 번째 단계는 사용 사례를 식별하는 것입니다. 예를 들어 모든 프로덕션 Amazon EC2 인스턴스에서 매일 실행되도록 `AWS-CreateImage` 실행서를 예약했습니다. 월말에 복구 지점에 필요한 것보다 많은 이미지가 있다고 판단됩니다. 앞으로 새로운 AMI가 생성될 때 Amazon EC2 인스턴스의 가장 오래된 AMI를 자동으로 삭제하려고 합니다. 이를 위해 다음을 수행하는 새 실행서를 생성합니다.

1. `aws:createImage` 작업을 실행하고 이미지 설명에 인스턴스 ID를 지정합니다.

1. `aws:waitForAwsResourceProperty` 작업을 실행하여 `available` 상태가 될 때까지 이미지의 상태를 폴링합니다.

1. 이미지 상태가 `available`이면 `aws:executeScript` 작업은 Amazon EC2 인스턴스와 연결된 모든 이미지의 ID를 수집하는 사용자 정의 Python 스크립트를 실행합니다. 스크립트는 생성 시 지정한 이미지 설명의 인스턴스 ID로 필터링하여 이를 수행합니다. 그런 다음 스크립트는 이미지의 `creationDate`를 기준으로 이미지 ID 목록을 정렬하고 가장 오래된 AMI의 ID를 출력합니다.

1. 마지막으로 `aws:deleteImage` 작업이 실행되어 이전 단계의 출력에서 ID를 사용하여 가장 오래된 AMI를 삭제합니다.

이 시나리오에서는 이미 `AWS-CreateImage` 실행서를 사용하고 있었지만 사용 사례에 더 큰 유연성이 필요함을 알게 되었습니다. 이는 실행서와 자동화 작업 간에 겹칠 수 있기 때문에 일반적인 상황입니다. 따라서 사용 사례를 해결하기 위해 사용하는 실행서 또는 작업을 조정해야 할 수 있습니다.

예를 들어 `aws:executeScript` 및 `aws:invokeLambdaFunction` 작업을 모두 사용하면 자동화의 일부로 사용자 정의 스크립트를 실행할 수 있습니다. 추가로 지원되는 런타임 언어 때문에 `aws:invokeLambdaFunction`을 선호할 수 있습니다. 그러나 YAML 실행서에서 직접 스크립트 콘텐츠를 작성하고 JSON 콘텐츠에 대한 첨부 파일로 스크립트 콘텐츠를 제공할 수 있으므로 `aws:executeScript`를 선호할 수 있습니다. AWS Identity and Access Management(IAM) 설정 측면에서 `aws:executeScript`가 더 간단하다고 생각할 수도 있습니다. `AutomationAssumeRole`에서 제공하는 권한을 사용하기 때문에 `aws:executeScript`는 추가적인 AWS Lambda 기능 실행 역할이 필요하지 않습니다.

주어진 시나리오에서 한 작업은 다른 작업보다 더 많은 유연성을 제공하거나 기능을 추가할 수 있습니다. 따라서 사용 사례 및 기본 설정에 가장 적합한 것을 결정하기 위해 사용하려는 실행서 또는 작업에 사용 가능한 입력 파라미터를 검토하는 것이 좋습니다.

## 개발 환경 설정
<a name="automation-authoring-runbooks-environment"></a>

실행서에서 사용하려는 사용 사례와 미리 정의된 실행서 또는 자동화 작업을 식별한 후에는 실행서의 콘텐츠에 대한 개발 환경을 설정할 차례입니다. 실행서 콘텐츠를 개발하려면 Systems Manager Documents 콘솔 대신 AWS Toolkit for Visual Studio Code를 사용하는 것이 좋습니다.

Toolkit for VS Code는 Systems Manager Documents 콘솔보다 더 많은 기능을 제공하는 Visual Studio Code(VS Code)용 오픈 소스 확장입니다. 유용한 기능에는 YAML 및 JSON 모두에 대한 스키마 검증, 자동화 작업 유형에 대한 코드 조각, YAML 및 JSON 모두의 다양한 옵션에 대한 자동 완성 지원이 있습니다.

Toolkit for VS Code 설치에 대한 자세한 내용은 [AWS Toolkit for Visual Studio Code 설치](https://docs.aws.amazon.com/toolkit-for-vscode/latest/userguide/setup-toolkit.html)를 참조하세요. 실행서 개발에 Toolkit for VS Code 사용에 대한 자세한 내용은 *AWS Toolkit for Visual Studio Code User Guide*의 [Working with Systems Manager Automation documents](https://docs.aws.amazon.com/toolkit-for-vscode/latest/userguide/systems-manager-automation-docs.html)를 참조하세요.

## 실행서 콘텐츠 개발
<a name="automation-authoring-runbooks-developing-content"></a>

사용 사례가 식별되고 환경이 설정되면 실행서용 콘텐츠를 개발할 준비가 된 것입니다. 사용 사례와 기본 설정에 따라 실행서 콘텐츠에서 사용하는 자동화 작업 또는 실행서가 주로 결정됩니다. 일부 작업은 유사한 태스크를 수행할 수 있는 다른 작업과 비교할 때 입력 파라미터의 하위 집합만 지원합니다. 다른 작업에는 `aws:createImage`와 같은 특정 출력이 있으며, 일부 작업에서는 `aws:executeAwsApi`와 같이 고유한 출력을 정의할 수 있습니다.

실행서에서 특정 작업을 사용하는 방법을 잘 모르는 경우 [Systems Manager Automation 작업 참조](automation-actions.md)에서 작업에 대한 해당 항목을 검토하는 것이 좋습니다. 또한 미리 정의된 실행서의 콘텐츠를 검토하여 이러한 작업이 사용되는 실제 사례를 확인하는 것이 좋습니다. 실행서의 실제 적용에 대한 더 많은 예는 [추가 런북 예제](automation-document-examples.md) 섹션을 참조하세요.

실행서 콘텐츠가 제공하는 단순성과 유연성의 차이점을 보여주기 위해 다음 자습서에서는 Amazon EC2 인스턴스의 그룹에 단계별로 패치하는 방법의 예를 제공합니다.
+ [예 1: 상위-하위 실행서 생성](automation-authoring-runbooks-parent-child-example.md) - 이 예에서는 2개의 실행서가 상위-하위 관계로 사용됩니다. 상위 실행서는 하위 실행서의 속도 제어 자동화를 시작합니다.
+ [예제 2: 스크립팅된 실행서](automation-authoring-runbooks-scripted-example.md) - 이 예에서는 콘텐츠를 단일 실행서로 압축하고 실행서에서 스크립트를 사용하여 예 1과 동일한 태스크를 수행하는 방법을 보여줍니다.

# 예 1: 상위-하위 실행서 생성
<a name="automation-authoring-runbooks-parent-child-example"></a>

다음 예에서는 태그가 지정된 Amazon Elastic Compute Cloud(Amazon EC2) 인스턴스 그룹에 단계별로 패치하는 2개의 실행서를 생성하는 방법을 보여줍니다. 이러한 실행서는 하위 실행서의 속도 제어 자동화를 시작하는 데 사용되는 상위 실행서와의 상위-하위 관계에 사용됩니다. 속도 제어 자동화에 대한 자세한 내용은 [대규모로 자동화된 작업 실행](running-automations-scale.md) 섹션을 참조하세요. 이 예에 사용되는 자동화 작업에 대한 자세한 내용은 [Systems Manager Automation 작업 참조](automation-actions.md) 섹션을 참조하세요.

## 하위 실행서 생성
<a name="automation-authoring-runbooks-child-runbook"></a>

이 예제 실행서는 다음 시나리오를 다룹니다. Emily는 AnyCompany Consultants, LLC의 시스템 엔지니어입니다. 그녀는 기본 및 보조 데이터베이스를 호스팅하는 Amazon Elastic Compute Cloud(Amazon EC2) 인스턴스 그룹에 대한 패치를 구성해야 합니다. 애플리케이션은 하루 24시간 이러한 데이터베이스에 액세스하므로 데이터베이스 인스턴스 중 하나를 항상 사용할 수 있어야 합니다.

그녀는 인스턴스에 단계적으로 패치하는 것이 가장 좋은 방법이라고 결정합니다. 데이터베이스 인스턴스의 주 그룹이 먼저 패치되고 데이터베이스 인스턴스의 보조 그룹이 패치됩니다. 또한 이전에 중지된 인스턴스를 계속 실행하여 추가 비용이 발생하지 않도록 Emily는 패치된 인스턴스가 패치되기 전의 원래 상태로 돌아가기를 원합니다.

Emily는 인스턴스와 연결된 태그로 데이터베이스 인스턴스의 주 그룹과 보조 그룹을 식별합니다. 그녀는 하위 실행서의 속도 제어 자동화를 시작하는 상위 실행서를 생성하기로 결정합니다. 이를 통해 데이터베이스 인스턴스의 주 및 보조 그룹과 연결된 태그를 대상으로 지정하고 하위 자동화의 동시성을 관리할 수 있습니다. 패치에 사용할 수 있는 Systems Manager(SSM) 문서를 검토한 후 그녀는 `AWS-RunPatchBaseline` 문서를 선택합니다. 이 SSM 문서를 사용하여 동료는 패치 작업이 완료된 후 관련 패치 규정 준수 정보를 검토할 수 있습니다.

실행서 콘텐츠 생성을 시작하기 위해 Emily는 사용 가능한 자동화 작업을 검토하고 다음과 같이 하위 실행서에 대한 콘텐츠 작성을 시작합니다.

1. 먼저 실행서의 스키마 및 설명 값을 제공하고 하위 실행서에 대한 입력 파라미터를 정의합니다.

   Emily와 동료는 `AutomationAssumeRole` 파라미터를 사용하여 Automation이 대신 실행서에서 작업을 수행할 수 있도록 하는 기존 IAM 역할을 사용할 수 있습니다. Emily는 `InstanceId` 파라미터를 사용하여 패치해야 하는 인스턴스를 결정합니다. 필요에 따라 `Operation`, `RebootOption` 및 `SnapshotId` 파라미터를 사용하여 `AWS-RunPatchBaseline`에 대한 문서 파라미터에 값을 제공 할 수 있습니다. 잘못된 값이 해당 문서 파라미터에 제공되지 않도록 필요에 따라 `allowedValues`를 정의합니다.

------
#### [ YAML ]

   ```
   schemaVersion: '0.3'
   description: 'An example of an Automation runbook that patches groups of Amazon EC2 instances in stages.'
   assumeRole: '{{AutomationAssumeRole}}'
   parameters:
     AutomationAssumeRole:
       type: String
       description: >-
         '(Optional) The Amazon Resource Name (ARN) of the IAM role that allows Automation to perform the
         actions on your behalf. If no role is specified, Systems Manager
         Automation uses your IAM permissions to operate this runbook.'
       default: ''
     InstanceId:
       type: String
       description: >-
         '(Required) The instance you want to patch.'
     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
   ```

------
#### [ JSON ]

   ```
   {
      "schemaVersion":"0.3",
      "description":"An example of an Automation runbook that patches groups of Amazon EC2 instances in stages.",
      "assumeRole":"{{AutomationAssumeRole}}",
      "parameters":{
         "AutomationAssumeRole":{
            "type":"String",
            "description":"(Optional) The Amazon Resource Name (ARN) of the IAM role that allows Automation to perform the actions on your behalf. If no role is specified, Systems Manager Automation uses your IAM permissions to operate this runbook.",
            "default":""
         },
         "InstanceId":{
            "type":"String",
            "description":"(Required) The instance you want to patch."
         },
         "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"
         }
      }
   },
   ```

------

1. 최상위 요소가 정의되면 Emily는 실행서의 `mainSteps`를 구성하는 작업 작성을 진행합니다. 첫 번째 단계는 `aws:executeAwsApi` 작업을 사용하여 `InstanceId` 입력 파라미터에 지정된 대상 인스턴스의 현재 상태를 출력합니다. 이 작업의 출력은 이후 작업에 사용됩니다.

------
#### [ YAML ]

   ```
   mainSteps:
     - name: getInstanceState
       action: 'aws:executeAwsApi'
       onFailure: Abort
       inputs:
         inputs:
         Service: ec2
         Api: DescribeInstances
         InstanceIds:
           - '{{InstanceId}}'
       outputs:
         - Name: instanceState
           Selector: '$.Reservations[0].Instances[0].State.Name'
           Type: String
       nextStep: branchOnInstanceState
   ```

------
#### [ JSON ]

   ```
   "mainSteps":[
         {
            "name":"getInstanceState",
            "action":"aws:executeAwsApi",
            "onFailure":"Abort",
            "inputs":{
               "inputs":null,
               "Service":"ec2",
               "Api":"DescribeInstances",
               "InstanceIds":[
                  "{{InstanceId}}"
               ]
            },
            "outputs":[
               {
                  "Name":"instanceState",
                  "Selector":"$.Reservations[0].Instances[0].State.Name",
                  "Type":"String"
               }
            ],
            "nextStep":"branchOnInstanceState"
         },
   ```

------

1. Emily는 패치가 필요한 모든 인스턴스의 원래 상태를 수동으로 시작하고 추적하는 대신 이전 작업의 출력을 사용하여 대상 인스턴스의 상태를 기반으로 자동화를 분기합니다. 이를 통해 자동화는 `aws:branch` 작업에 정의된 조건에 따라 다른 단계를 실행할 수 있으며 수동 개입 없이 자동화의 전반적인 효율성이 향상됩니다.

   인스턴스 상태가 이미 `running`이면 자동화는 `aws:runCommand` 작업을 사용하여 `AWS-RunPatchBaseline` 문서로 인스턴스 패치를 진행합니다.

   인스턴스 상태가 `stopping`이면 자동화는 인스턴스가 `aws:waitForAwsResourceProperty` 작업을 사용하여 `stopped` 상태에 도달하도록 폴링하고, `executeAwsApi` 작업을 사용하여 인스턴스를 시작하고, 인스턴스를 패치하기 전에 인스턴스가 `running` 상태에 도달하도록 폴링합니다.

   인스턴스 상태가 `stopped`이면 자동화는 인스턴스를 시작하고 동일한 작업을 사용하여 인스턴스를 패치하기 전에 인스턴스가 `running` 상태에 도달하도록 폴링합니다.

------
#### [ YAML ]

   ```
   - name: branchOnInstanceState
       action: 'aws:branch'
       onFailure: Abort
       inputs:
         Choices:
           - NextStep: startInstance
              Variable: '{{getInstanceState.instanceState}}'
              StringEquals: stopped
            - NextStep: verifyInstanceStopped
              Variable: '{{getInstanceState.instanceState}}'
              StringEquals: stopping
            - NextStep: patchInstance
              Variable: '{{getInstanceState.instanceState}}'
              StringEquals: running
       isEnd: true
     - name: startInstance
       action: 'aws:executeAwsApi'
       onFailure: Abort
       inputs:
         Service: ec2
         Api: StartInstances
         InstanceIds:
           - '{{InstanceId}}'
       nextStep: verifyInstanceRunning
     - name: verifyInstanceRunning
       action: 'aws:waitForAwsResourceProperty'
       timeoutSeconds: 120
       inputs:
         Service: ec2
         Api: DescribeInstances
         InstanceIds:
           - '{{InstanceId}}'
         PropertySelector: '$.Reservations[0].Instances[0].State.Name'
         DesiredValues:
           - running
       nextStep: patchInstance
     - name: verifyInstanceStopped
       action: 'aws:waitForAwsResourceProperty'
       timeoutSeconds: 120
       inputs:
         Service: ec2
         Api: DescribeInstances
         InstanceIds:
           - '{{InstanceId}}'
         PropertySelector: '$.Reservations[0].Instances[0].State.Name'
         DesiredValues:
           - stopped
         nextStep: startInstance
     - name: patchInstance
       action: 'aws:runCommand'
       onFailure: Abort
       timeoutSeconds: 5400
       inputs:
         DocumentName: 'AWS-RunPatchBaseline'
         InstanceIds: 
         - '{{InstanceId}}'
         Parameters:
           SnapshotId: '{{SnapshotId}}'
           RebootOption: '{{RebootOption}}'
           Operation: '{{Operation}}'
   ```

------
#### [ JSON ]

   ```
   {
            "name":"branchOnInstanceState",
            "action":"aws:branch",
            "onFailure":"Abort",
            "inputs":{
               "Choices":[
                  {
                     "NextStep":"startInstance",
                     "Variable":"{{getInstanceState.instanceState}}",
                     "StringEquals":"stopped"
                  },
                  {
                     "Or":[
                        {
                           "Variable":"{{getInstanceState.instanceState}}",
                           "StringEquals":"stopping"
                        }
                     ],
                     "NextStep":"verifyInstanceStopped"
                  },
                  {
                     "NextStep":"patchInstance",
                     "Variable":"{{getInstanceState.instanceState}}",
                     "StringEquals":"running"
                  }
               ]
            },
            "isEnd":true
         },
         {
            "name":"startInstance",
            "action":"aws:executeAwsApi",
            "onFailure":"Abort",
            "inputs":{
               "Service":"ec2",
               "Api":"StartInstances",
               "InstanceIds":[
                  "{{InstanceId}}"
               ]
            },
            "nextStep":"verifyInstanceRunning"
         },
         {
            "name":"verifyInstanceRunning",
            "action":"aws:waitForAwsResourceProperty",
            "timeoutSeconds":120,
            "inputs":{
               "Service":"ec2",
               "Api":"DescribeInstances",
               "InstanceIds":[
                  "{{InstanceId}}"
               ],
               "PropertySelector":"$.Reservations[0].Instances[0].State.Name",
               "DesiredValues":[
                  "running"
               ]
            },
            "nextStep":"patchInstance"
         },
         {
            "name":"verifyInstanceStopped",
            "action":"aws:waitForAwsResourceProperty",
            "timeoutSeconds":120,
            "inputs":{
               "Service":"ec2",
               "Api":"DescribeInstances",
               "InstanceIds":[
                  "{{InstanceId}}"
               ],
               "PropertySelector":"$.Reservations[0].Instances[0].State.Name",
               "DesiredValues":[
                  "stopped"
               ],
               "nextStep":"startInstance"
            }
         },
         {
            "name":"patchInstance",
            "action":"aws:runCommand",
            "onFailure":"Abort",
            "timeoutSeconds":5400,
            "inputs":{
               "DocumentName":"AWS-RunPatchBaseline",
               "InstanceIds":[
                  "{{InstanceId}}"
               ],
               "Parameters":{
                  "SnapshotId":"{{SnapshotId}}",
                  "RebootOption":"{{RebootOption}}",
                  "Operation":"{{Operation}}"
               }
            }
         },
   ```

------

1. 패치 작업이 완료된 후 Emily는 자동화가 대상 인스턴스를 자동화가 시작되기 전과 동일한 상태로 되돌리기를 원합니다. 그녀는 첫 번째 작업의 출력을 다시 사용하여 이 작업을 수행합니다. `aws:branch` 작업을 사용하여 대상 인스턴스의 원래 상태를 기반으로 자동화가 분기합니다. 인스턴스가 이전에 `running`이 아닌 다른 상태에 있었다면 인스턴스가 중지됩니다. 그렇지 않고 인스턴스 상태가 `running`이면 자동화가 종료됩니다.

------
#### [ YAML ]

   ```
   - name: branchOnOriginalInstanceState
       action: 'aws:branch'
       onFailure: Abort
       inputs:
         Choices:
           - NextStep: stopInstance
             Not: 
               Variable: '{{getInstanceState.instanceState}}'
               StringEquals: running
       isEnd: true
     - name: stopInstance
       action: 'aws:executeAwsApi'
       onFailure: Abort
       inputs:
         Service: ec2
         Api: StopInstances
         InstanceIds:
           - '{{InstanceId}}'
   ```

------
#### [ JSON ]

   ```
   {
            "name":"branchOnOriginalInstanceState",
            "action":"aws:branch",
            "onFailure":"Abort",
            "inputs":{
               "Choices":[
                  {
                     "NextStep":"stopInstance",
                     "Not":{
                        "Variable":"{{getInstanceState.instanceState}}",
                        "StringEquals":"running"
                     }
                  }
               ]
            },
            "isEnd":true
         },
         {
            "name":"stopInstance",
            "action":"aws:executeAwsApi",
            "onFailure":"Abort",
            "inputs":{
               "Service":"ec2",
               "Api":"StopInstances",
               "InstanceIds":[
                  "{{InstanceId}}"
               ]
            }
         }
      ]
   }
   ```

------

1. Emily는 완성된 하위 실행서 콘텐츠를 검토하고 대상 인스턴스와 동일한 AWS 계정 및 AWS 리전에 실행서를 생성합니다. 이제 그녀는 계속해서 상위 실행서의 콘텐츠를 생성할 준비가 되었습니다. 다음은 완성된 하위 실행서 콘텐츠입니다.

------
#### [ YAML ]

   ```
   schemaVersion: '0.3'
   description: 'An example of an Automation runbook that patches groups of Amazon EC2 instances in stages.'
   assumeRole: '{{AutomationAssumeRole}}'
   parameters:
     AutomationAssumeRole:
       type: String
       description: >-
         '(Optional) The Amazon Resource Name (ARN) of the IAM role that allows Automation to perform the
         actions on your behalf. If no role is specified, Systems Manager
         Automation uses your IAM permissions to operate this runbook.'
       default: ''
     InstanceId:
       type: String
       description: >-
         '(Required) The instance you want to patch.'
     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: getInstanceState
       action: 'aws:executeAwsApi'
       onFailure: Abort
       inputs:
         inputs:
         Service: ec2
         Api: DescribeInstances
         InstanceIds:
           - '{{InstanceId}}'
       outputs:
         - Name: instanceState
           Selector: '$.Reservations[0].Instances[0].State.Name'
           Type: String
       nextStep: branchOnInstanceState
     - name: branchOnInstanceState
       action: 'aws:branch'
       onFailure: Abort
       inputs:
         Choices:
           - NextStep: startInstance
             Variable: '{{getInstanceState.instanceState}}'
             StringEquals: stopped
           - Or:
               - Variable: '{{getInstanceState.instanceState}}'
                 StringEquals: stopping
             NextStep: verifyInstanceStopped
           - NextStep: patchInstance
             Variable: '{{getInstanceState.instanceState}}'
             StringEquals: running
       isEnd: true
     - name: startInstance
       action: 'aws:executeAwsApi'
       onFailure: Abort
       inputs:
         Service: ec2
         Api: StartInstances
         InstanceIds:
           - '{{InstanceId}}'
       nextStep: verifyInstanceRunning
     - name: verifyInstanceRunning
       action: 'aws:waitForAwsResourceProperty'
       timeoutSeconds: 120
       inputs:
         Service: ec2
         Api: DescribeInstances
         InstanceIds:
           - '{{InstanceId}}'
         PropertySelector: '$.Reservations[0].Instances[0].State.Name'
         DesiredValues:
           - running
       nextStep: patchInstance
     - name: verifyInstanceStopped
       action: 'aws:waitForAwsResourceProperty'
       timeoutSeconds: 120
       inputs:
         Service: ec2
         Api: DescribeInstances
         InstanceIds:
           - '{{InstanceId}}'
         PropertySelector: '$.Reservations[0].Instances[0].State.Name'
         DesiredValues:
           - stopped
         nextStep: startInstance
     - name: patchInstance
       action: 'aws:runCommand'
       onFailure: Abort
       timeoutSeconds: 5400
       inputs:
         DocumentName: 'AWS-RunPatchBaseline'
         InstanceIds: 
         - '{{InstanceId}}'
         Parameters:
           SnapshotId: '{{SnapshotId}}'
           RebootOption: '{{RebootOption}}'
           Operation: '{{Operation}}'
     - name: branchOnOriginalInstanceState
       action: 'aws:branch'
       onFailure: Abort
       inputs:
         Choices:
           - NextStep: stopInstance
             Not: 
               Variable: '{{getInstanceState.instanceState}}'
               StringEquals: running
       isEnd: true
     - name: stopInstance
       action: 'aws:executeAwsApi'
       onFailure: Abort
       inputs:
         Service: ec2
         Api: StopInstances
         InstanceIds:
           - '{{InstanceId}}'
   ```

------
#### [ JSON ]

   ```
   {
      "schemaVersion":"0.3",
      "description":"An example of an Automation runbook that patches groups of Amazon EC2 instances in stages.",
      "assumeRole":"{{AutomationAssumeRole}}",
      "parameters":{
         "AutomationAssumeRole":{
            "type":"String",
            "description":"'(Optional) The Amazon Resource Name (ARN) of the IAM role that allows Automation to perform the actions on your behalf. If no role is specified, Systems Manager Automation uses your IAM permissions to operate this runbook.'",
            "default":""
         },
         "InstanceId":{
            "type":"String",
            "description":"'(Required) The instance you want to patch.'"
         },
         "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":"getInstanceState",
            "action":"aws:executeAwsApi",
            "onFailure":"Abort",
            "inputs":{
               "inputs":null,
               "Service":"ec2",
               "Api":"DescribeInstances",
               "InstanceIds":[
                  "{{InstanceId}}"
               ]
            },
            "outputs":[
               {
                  "Name":"instanceState",
                  "Selector":"$.Reservations[0].Instances[0].State.Name",
                  "Type":"String"
               }
            ],
            "nextStep":"branchOnInstanceState"
         },
         {
            "name":"branchOnInstanceState",
            "action":"aws:branch",
            "onFailure":"Abort",
            "inputs":{
               "Choices":[
                  {
                     "NextStep":"startInstance",
                     "Variable":"{{getInstanceState.instanceState}}",
                     "StringEquals":"stopped"
                  },
                  {
                     "Or":[
                        {
                           "Variable":"{{getInstanceState.instanceState}}",
                           "StringEquals":"stopping"
                        }
                     ],
                     "NextStep":"verifyInstanceStopped"
                  },
                  {
                     "NextStep":"patchInstance",
                     "Variable":"{{getInstanceState.instanceState}}",
                     "StringEquals":"running"
                  }
               ]
            },
            "isEnd":true
         },
         {
            "name":"startInstance",
            "action":"aws:executeAwsApi",
            "onFailure":"Abort",
            "inputs":{
               "Service":"ec2",
               "Api":"StartInstances",
               "InstanceIds":[
                  "{{InstanceId}}"
               ]
            },
            "nextStep":"verifyInstanceRunning"
         },
         {
            "name":"verifyInstanceRunning",
            "action":"aws:waitForAwsResourceProperty",
            "timeoutSeconds":120,
            "inputs":{
               "Service":"ec2",
               "Api":"DescribeInstances",
               "InstanceIds":[
                  "{{InstanceId}}"
               ],
               "PropertySelector":"$.Reservations[0].Instances[0].State.Name",
               "DesiredValues":[
                  "running"
               ]
            },
            "nextStep":"patchInstance"
         },
         {
            "name":"verifyInstanceStopped",
            "action":"aws:waitForAwsResourceProperty",
            "timeoutSeconds":120,
            "inputs":{
               "Service":"ec2",
               "Api":"DescribeInstances",
               "InstanceIds":[
                  "{{InstanceId}}"
               ],
               "PropertySelector":"$.Reservations[0].Instances[0].State.Name",
               "DesiredValues":[
                  "stopped"
               ],
               "nextStep":"startInstance"
            }
         },
         {
            "name":"patchInstance",
            "action":"aws:runCommand",
            "onFailure":"Abort",
            "timeoutSeconds":5400,
            "inputs":{
               "DocumentName":"AWS-RunPatchBaseline",
               "InstanceIds":[
                  "{{InstanceId}}"
               ],
               "Parameters":{
                  "SnapshotId":"{{SnapshotId}}",
                  "RebootOption":"{{RebootOption}}",
                  "Operation":"{{Operation}}"
               }
            }
         },
         {
            "name":"branchOnOriginalInstanceState",
            "action":"aws:branch",
            "onFailure":"Abort",
            "inputs":{
               "Choices":[
                  {
                     "NextStep":"stopInstance",
                     "Not":{
                        "Variable":"{{getInstanceState.instanceState}}",
                        "StringEquals":"running"
                     }
                  }
               ]
            },
            "isEnd":true
         },
         {
            "name":"stopInstance",
            "action":"aws:executeAwsApi",
            "onFailure":"Abort",
            "inputs":{
               "Service":"ec2",
               "Api":"StopInstances",
               "InstanceIds":[
                  "{{InstanceId}}"
               ]
            }
         }
      ]
   }
   ```

------

이 예에 사용되는 자동화 작업에 대한 자세한 내용은 [Systems Manager Automation 작업 참조](automation-actions.md) 섹션을 참조하세요.

## 상위 실행서 생성
<a name="automation-authoring-runbooks-parent-runbook"></a>

이 예제 실행서는 이전 섹션에서 설명한 시나리오를 계속합니다. 하위 실행서를 생성했으므로 이제 Emily는 다음과 같이 상위 실행서에 대한 콘텐츠 작성을 시작합니다.

1. 먼저 실행서의 스키마 및 설명 값을 제공하고 하위 실행서에 대한 입력 파라미터를 정의합니다.

   Emily와 동료는 `AutomationAssumeRole` 파라미터를 사용하여 Automation이 대신 실행서에서 작업을 수행할 수 있도록 하는 기존 IAM 역할을 사용할 수 있습니다. Emily는 `PatchGroupPrimaryKey` 및 `PatchGroupPrimaryValue` 파라미터를 사용하여 패치될 데이터베이스 인스턴스의 주 그룹과 연결된 태그를 지정합니다. 그녀는 `PatchGroupSecondaryKey` 및 `PatchGroupSecondaryValue` 파라미터를 사용하여 패치될 데이터베이스 인스턴스의 보조 그룹과 연결된 태그를 지정합니다.

------
#### [ YAML ]

   ```
   description: 'An example of an Automation runbook that patches groups of Amazon EC2 instances in stages.'
   schemaVersion: '0.3'
   assumeRole: '{{AutomationAssumeRole}}'
   parameters:
     AutomationAssumeRole:
       type: String
       description: '(Optional) The Amazon Resource Name (ARN) of the IAM role that allows Automation to perform the actions on your behalf. If no role is specified, Systems Manager Automation uses your IAM permissions to operate this runbook.'
       default: ''
     PatchGroupPrimaryKey:
       type: String
       description: '(Required) The key of the tag for the primary group of instances you want to patch.''
     PatchGroupPrimaryValue:
       type: String
       description: '(Required) The value of the tag for the primary group of instances you want to patch.'
     PatchGroupSecondaryKey:
       type: String
       description: '(Required) The key of the tag for the secondary group of instances you want to patch.'
     PatchGroupSecondaryValue:
       type: String
       description: '(Required) The value of the tag for the secondary group of instances you want to patch.'
   ```

------
#### [ JSON ]

   ```
   {
      "schemaVersion": "0.3",
      "description": "An example of an Automation runbook that patches groups of Amazon EC2 instances in stages.",
      "assumeRole": "{{AutomationAssumeRole}}",
      "parameters": {
         "AutomationAssumeRole": {
            "type": "String",
            "description": "(Optional) The Amazon Resource Name (ARN) of the IAM role that allows Automation to perform the actions on your behalf. If no role is specified, Systems Manager Automation uses your IAM permissions to operate this runbook.",
            "default": ""
         },
         "PatchGroupPrimaryKey": {
            "type": "String",
            "description": "(Required) The key of the tag for the primary group of instances you want to patch."
         },
         "PatchGroupPrimaryValue": {
            "type": "String",
            "description": "(Required) The value of the tag for the primary group of instances you want to patch."
         },
         "PatchGroupSecondaryKey": {
            "type": "String",
            "description": "(Required) The key of the tag for the secondary group of instances you want to patch."
         },
         "PatchGroupSecondaryValue": {
            "type": "String",
            "description": "(Required) The value of the tag for the secondary group of instances you want to patch."
         }
      }
   },
   ```

------

1. 최상위 요소가 정의되면 Emily는 실행서의 `mainSteps`를 구성하는 작업 작성을 진행합니다.

   첫 번째 작업은 `PatchGroupPrimaryKey` 및 `PatchGroupPrimaryValue` 입력 파라미터에 지정된 태그와 연결된 인스턴스를 대상으로 하는 방금 생성한 하위 실행서를 사용하여 속도 제어 자동화를 시작합니다. 그녀는 입력 파라미터에 제공된 값을 사용하여 패치하려는 데이터베이스 인스턴스의 주 그룹과 연결된 태그의 키와 값을 지정합니다.

   첫 번째 자동화가 완료된 후 두 번째 작업은 `PatchGroupSecondaryKey` 및 `PatchGroupSecondaryValue` 입력 파라미터에 지정된 태그와 연결된 인스턴스를 대상으로 하는 하위 실행서를 사용하여 다른 속도 제어 자동화를 시작합니다. 그녀는 입력 파라미터에 제공된 값을 사용하여 패치하려는 데이터베이스 인스턴스의 보조 그룹과 연결된 태그의 키와 값을 지정합니다.

------
#### [ YAML ]

   ```
   mainSteps:
     - name: patchPrimaryTargets
       action: 'aws:executeAutomation'
       onFailure: Abort
       timeoutSeconds: 7200
       inputs:
         DocumentName: RunbookTutorialChildAutomation
         Targets:
           - Key: 'tag:{{PatchGroupPrimaryKey}}'
             Values:
               - '{{PatchGroupPrimaryValue}}'
         TargetParameterName: 'InstanceId'
     - name: patchSecondaryTargets
       action: 'aws:executeAutomation'
       onFailure: Abort
       timeoutSeconds: 7200
       inputs:
         DocumentName: RunbookTutorialChildAutomation
         Targets:
           - Key: 'tag:{{PatchGroupSecondaryKey}}'
             Values:
               - '{{PatchGroupSecondaryValue}}'
         TargetParameterName: 'InstanceId'
   ```

------
#### [ JSON ]

   ```
   "mainSteps":[
         {
            "name":"patchPrimaryTargets",
            "action":"aws:executeAutomation",
            "onFailure":"Abort",
            "timeoutSeconds":7200,
            "inputs":{
               "DocumentName":"RunbookTutorialChildAutomation",
               "Targets":[
                  {
                     "Key":"tag:{{PatchGroupPrimaryKey}}",
                     "Values":[
                        "{{PatchGroupPrimaryValue}}"
                     ]
                  }
               ],
               "TargetParameterName":"InstanceId"
            }
         },
         {
            "name":"patchSecondaryTargets",
            "action":"aws:executeAutomation",
            "onFailure":"Abort",
            "timeoutSeconds":7200,
            "inputs":{
               "DocumentName":"RunbookTutorialChildAutomation",
               "Targets":[
                  {
                     "Key":"tag:{{PatchGroupSecondaryKey}}",
                     "Values":[
                        "{{PatchGroupSecondaryValue}}"
                     ]
                  }
               ],
               "TargetParameterName":"InstanceId"
            }
         }
      ]
   }
   ```

------

1. Emily는 완성된 상위 실행서 콘텐츠를 검토하고 대상 인스턴스와 동일한 AWS 계정 및 AWS 리전에 실행서를 생성합니다. 이제 프로덕션 환경에 구현하기 전 실행서를 테스트하여 자동화가 원하는 대로 작동하는지 확인할 준비가 되었습니다. 다음은 완성된 상위 실행서 콘텐츠입니다.

------
#### [ YAML ]

   ```
   description: An example of an Automation runbook that patches groups of Amazon EC2 instances in stages.
   schemaVersion: '0.3'
   assumeRole: '{{AutomationAssumeRole}}'
   parameters:
     AutomationAssumeRole:
       type: String
       description: '(Optional) The Amazon Resource Name (ARN) of the IAM role that allows Automation to perform the actions on your behalf. If no role is specified, Systems Manager Automation uses your IAM permissions to operate this runbook.'
       default: ''
     PatchGroupPrimaryKey:
       type: String
       description: (Required) The key of the tag for the primary group of instances you want to patch.
     PatchGroupPrimaryValue:
       type: String
       description: '(Required) The value of the tag for the primary group of instances you want to patch. '
     PatchGroupSecondaryKey:
       type: String
       description: (Required) The key of the tag for the secondary group of instances you want to patch.
     PatchGroupSecondaryValue:
       type: String
       description: '(Required) The value of the tag for the secondary group of instances you want to patch.  '
   mainSteps:
     - name: patchPrimaryTargets
       action: 'aws:executeAutomation'
       onFailure: Abort
       timeoutSeconds: 7200
       inputs:
         DocumentName: RunbookTutorialChildAutomation
         Targets:
           - Key: 'tag:{{PatchGroupPrimaryKey}}'
             Values:
               - '{{PatchGroupPrimaryValue}}'
         TargetParameterName: 'InstanceId'
     - name: patchSecondaryTargets
       action: 'aws:executeAutomation'
       onFailure: Abort
       timeoutSeconds: 7200
       inputs:
         DocumentName: RunbookTutorialChildAutomation
         Targets:
           - Key: 'tag:{{PatchGroupSecondaryKey}}'
             Values:
               - '{{PatchGroupSecondaryValue}}'
         TargetParameterName: 'InstanceId'
   ```

------
#### [ JSON ]

   ```
   {
      "description":"An example of an Automation runbook that patches groups of Amazon EC2 instances in stages.",
      "schemaVersion":"0.3",
      "assumeRole":"{{AutomationAssumeRole}}",
      "parameters":{
         "AutomationAssumeRole":{
            "type":"String",
            "description":"(Optional) The Amazon Resource Name (ARN) of the IAM role that allows Automation to perform the actions on your behalf. If no role is specified, Systems Manager Automation uses your IAM permissions to operate this runbook.",
            "default":""
         },
         "PatchGroupPrimaryKey":{
            "type":"String",
            "description":"(Required) The key of the tag for the primary group of instances you want to patch."
         },
         "PatchGroupPrimaryValue":{
            "type":"String",
            "description":"(Required) The value of the tag for the primary group of instances you want to patch. "
         },
         "PatchGroupSecondaryKey":{
            "type":"String",
            "description":"(Required) The key of the tag for the secondary group of instances you want to patch."
         },
         "PatchGroupSecondaryValue":{
            "type":"String",
            "description":"(Required) The value of the tag for the secondary group of instances you want to patch.  "
         }
      },
      "mainSteps":[
         {
            "name":"patchPrimaryTargets",
            "action":"aws:executeAutomation",
            "onFailure":"Abort",
            "timeoutSeconds":7200,
            "inputs":{
               "DocumentName":"RunbookTutorialChildAutomation",
               "Targets":[
                  {
                     "Key":"tag:{{PatchGroupPrimaryKey}}",
                     "Values":[
                        "{{PatchGroupPrimaryValue}}"
                     ]
                  }
               ],
               "TargetParameterName":"InstanceId"
            }
         },
         {
            "name":"patchSecondaryTargets",
            "action":"aws:executeAutomation",
            "onFailure":"Abort",
            "timeoutSeconds":7200,
            "inputs":{
               "DocumentName":"RunbookTutorialChildAutomation",
               "Targets":[
                  {
                     "Key":"tag:{{PatchGroupSecondaryKey}}",
                     "Values":[
                        "{{PatchGroupSecondaryValue}}"
                     ]
                  }
               ],
               "TargetParameterName":"InstanceId"
            }
         }
      ]
   }
   ```

------

이 예에 사용되는 자동화 작업에 대한 자세한 내용은 [Systems Manager Automation 작업 참조](automation-actions.md) 섹션을 참조하세요.

# 예제 2: 스크립팅된 실행서
<a name="automation-authoring-runbooks-scripted-example"></a>

이 예제 실행서는 다음 시나리오를 다룹니다. Emily는 AnyCompany Consultants, LLC의 시스템 엔지니어입니다. 그녀는 이전에 주 및 보조 데이터베이스를 호스팅하는 Amazon Elastic Compute Cloud(Amazon EC2) 인스턴스의 패치 그룹에 대한 상위-하위 관계에서 사용되는 2개의 실행서를 생성했습니다. 애플리케이션은 하루 24시간 이러한 데이터베이스에 액세스하므로 데이터베이스 인스턴스 중 하나를 항상 사용할 수 있어야 합니다.

이 요구 사항에 따라 그녀는 `AWS-RunPatchBaseline` Systems Manager(SSM) 문서를 사용하여 단계적으로 인스턴스를 패치하는 솔루션을 구축했습니다. 이 SSM 문서를 사용하여 동료는 패치 작업이 완료된 후 관련 패치 규정 준수 정보를 검토할 수 있습니다.

데이터베이스 인스턴스의 주 그룹이 먼저 패치된 다음 데이터베이스 인스턴스의 보조 그룹이 패치됩니다. 또한 이전에 중지된 인스턴스를 계속 실행하여 추가 비용이 발생하지 않도록 Emily는 자동화가 패치된 인스턴스를 패치되기 전의 원래 상태로 되돌리도록 했습니다. Emily는 데이터베이스 인스턴스의 주 및 보조 그룹과 연결된 태그를 사용하여 원하는 순서로 패치해야 하는 인스턴스를 식별했습니다.

기존 자동화 솔루션은 작동하지만 가능한 경우 솔루션을 개선하고자 합니다. 실행서 콘텐츠의 유지 관리를 지원하고 문제 해결을 용이하게 하기 위해 자동화를 단일 실행서로 축소하고 입력 파라미터의 수를 단순화하려고 합니다. 또한 여러 하위 자동화를 생성하지 않으려고 합니다.

Emily는 사용 가능한 자동화 작업을 검토한 후 `aws:executeScript` 작업으로 사용자 정의 Python 스크립트를 실행하여 솔루션을 개선할 수 있다고 판단합니다. 이제 다음과 같이 실행서의 콘텐츠를 작성하기 시작합니다.

1. 먼저 실행서의 스키마 및 설명 값을 제공하고 하위 실행서에 대한 입력 파라미터를 정의합니다.

   Emily와 동료는 `AutomationAssumeRole` 파라미터를 사용하여 Automation이 대신 실행서에서 작업을 수행할 수 있도록 하는 기존 IAM 역할을 사용할 수 있습니다. [예 1](automation-authoring-runbooks-parent-child-example.md)과 달리 `AutomationAssumeRole` 파라미터는 이제 옵션이 아닌 필수 항목입니다. 이 실행서에는 `aws:executeScript` 작업이 포함되어 있으므로 AWS Identity and Access Management(IAM) 서비스 역할(또는 수임 역할)이 항상 필요합니다. 이 요구 사항은 작업에 대해 지정된 일부 Python 스크립트가 AWS API 작업을 호출하기 때문에 필요합니다.

   Emily는 `PrimaryPatchGroupTag` 및 `SecondaryPatchGroupTag` 파라미터를 사용하여 패치될 데이터베이스 인스턴스의 주 및 보조 그룹과 연결된 태그를 지정합니다. 필요한 입력 파라미터를 단순화하기 위해 예제 1 실행서와 같이 `String` 파라미터를 여러 개 사용하는 대신 `StringMap` 파라미터를 사용하기로 결정했습니다. 필요에 따라 `Operation`, `RebootOption` 및 `SnapshotId` 파라미터를 사용하여 `AWS-RunPatchBaseline`에 대한 문서 파라미터에 값을 제공 할 수 있습니다. 잘못된 값이 해당 문서 파라미터에 제공되지 않도록 필요에 따라 `allowedValues`를 정의합니다.

------
#### [ YAML ]

   ```
   description: 'An example of an Automation runbook that patches groups of Amazon EC2 instances in stages.'
   schemaVersion: '0.3'
   assumeRole: '{{AutomationAssumeRole}}'
   parameters:
     AutomationAssumeRole:
       type: String
       description: '(Required) The Amazon Resource Name (ARN) of the IAM role that allows Automation to perform the actions on your behalf. If no role is specified, Systems Manager Automation uses your IAM permissions to operate this runbook.'
     PrimaryPatchGroupTag:
       type: StringMap
       description: '(Required) The tag for the primary group of instances you want to patch. Specify a key-value pair. Example: {"key" : "value"}'
     SecondaryPatchGroupTag:
       type: StringMap
       description: '(Required) The tag for the secondary group of instances you want to patch. Specify a key-value pair. Example: {"key" : "value"}'
     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
   ```

------
#### [ JSON ]

   ```
   {
      "description":"An example of an Automation runbook that patches groups of Amazon EC2 instances in stages.",
      "schemaVersion":"0.3",
      "assumeRole":"{{AutomationAssumeRole}}",
      "parameters":{
         "AutomationAssumeRole":{
            "type":"String",
            "description":"(Required) The Amazon Resource Name (ARN) of the IAM role that allows Automation to perform the actions on your behalf. If no role is specified, Systems Manager Automation uses your IAM permissions to operate this runbook."
         },
         "PrimaryPatchGroupTag":{
            "type":"StringMap",
            "description":"(Required) The tag for the primary group of instances you want to patch. Specify a key-value pair. Example: {\"key\" : \"value\"}"
         },
         "SecondaryPatchGroupTag":{
            "type":"StringMap",
            "description":"(Required) The tag for the secondary group of instances you want to patch. Specify a key-value pair. Example: {\"key\" : \"value\"}"
         },
         "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"
         }
      }
   },
   ```

------

1. 최상위 요소가 정의되면 Emily는 실행서의 `mainSteps`를 구성하는 작업 작성을 진행합니다. 첫 번째 단계는 `PrimaryPatchGroupTag` 파라미터에 지정된 태그와 연결된 모든 인스턴스의 ID를 수집하고 인스턴스 ID와 인스턴스의 현재 상태를 포함하는 `StringMap` 파라미터를 출력합니다. 이 작업의 출력은 이후 작업에 사용됩니다.

   참고: `script` 입력 파라미터는 JSON 실행서에서 지원되지 않습니다. JSON 실행서는 `attachment` 입력 파라미터를 사용하여 스크립트 콘텐츠를 제공해야 합니다.

------
#### [ YAML ]

   ```
   mainSteps:
     - name: getPrimaryInstanceState
       action: 'aws:executeScript'
       timeoutSeconds: 120
       onFailure: Abort
       inputs:
         Runtime: python3.11
         Handler: getInstanceStates
         InputPayload:
           primaryTag: '{{PrimaryPatchGroupTag}}'
         Script: |-
           def getInstanceStates(events,context):
             import boto3
   
             #Initialize client
             ec2 = boto3.client('ec2')
             tag = events['primaryTag']
             tagKey, tagValue = list(tag.items())[0]
             instanceQuery = ec2.describe_instances(
             Filters=[
                 {
                     "Name": "tag:" + tagKey,
                     "Values": [tagValue]
                 }]
             )
             if not instanceQuery['Reservations']:
                 noInstancesForTagString = "No instances found for specified tag."
                 return({ 'noInstancesFound' : noInstancesForTagString })
             else:
                 queryResponse = instanceQuery['Reservations']
                 originalInstanceStates = {}
                 for results in queryResponse:
                     instanceSet = results['Instances']
                     for instance in instanceSet:
                         instanceId = instance['InstanceId']
                         originalInstanceStates[instanceId] = instance['State']['Name']
                 return originalInstanceStates
       outputs:
         - Name: originalInstanceStates
           Selector: $.Payload
           Type: StringMap
       nextStep: verifyPrimaryInstancesRunning
   ```

------
#### [ JSON ]

   ```
   "mainSteps":[
         {
            "name":"getPrimaryInstanceState",
            "action":"aws:executeScript",
            "timeoutSeconds":120,
            "onFailure":"Abort",
            "inputs":{
               "Runtime":"python3.11",
               "Handler":"getInstanceStates",
               "InputPayload":{
                  "primaryTag":"{{PrimaryPatchGroupTag}}"
               },
               "Script":"..."
            },
            "outputs":[
               {
                  "Name":"originalInstanceStates",
                  "Selector":"$.Payload",
                  "Type":"StringMap"
               }
            ],
            "nextStep":"verifyPrimaryInstancesRunning"
         },
   ```

------

1. Emily는 다른 `aws:executeScript` 작업에서 이전 작업의 출력을 사용하여 `PrimaryPatchGroupTag` 파라미터에 지정된 태그와 연결된 모든 인스턴스가 `running` 상태인지 확인합니다.

   인스턴스 상태가 이미 `running` 또는 `shutting-down`인 경우 스크립트는 나머지 인스턴스를 계속 반복합니다.

   인스턴스 상태가 `stopping`이면 스크립트는 `stopped` 상태에 도달하기 위해 인스턴스를 폴링하고 인스턴스를 시작합니다.

   인스턴스 상태가 `stopped`이면 스크립트는 인스턴스를 시작합니다.

------
#### [ YAML ]

   ```
   - name: verifyPrimaryInstancesRunning
       action: 'aws:executeScript'
       timeoutSeconds: 600
       onFailure: Abort
       inputs:
         Runtime: python3.11
         Handler: verifyInstancesRunning
         InputPayload:
           targetInstances: '{{getPrimaryInstanceState.originalInstanceStates}}'
         Script: |-
           def verifyInstancesRunning(events,context):
             import boto3
   
             #Initialize client
             ec2 = boto3.client('ec2')
             instanceDict = events['targetInstances']
             for instance in instanceDict:
               if instanceDict[instance] == 'stopped':
                   print("The target instance " + instance + " is stopped. The instance will now be started.")
                   ec2.start_instances(
                       InstanceIds=[instance]
                       )
               elif instanceDict[instance] == 'stopping':
                   print("The target instance " + instance + " is stopping. Polling for instance to reach stopped state.")
                   while instanceDict[instance] != 'stopped':
                       poll = ec2.get_waiter('instance_stopped')
                       poll.wait(
                           InstanceIds=[instance]
                       )
                   ec2.start_instances(
                       InstanceIds=[instance]
                   )
               else:
                 pass
       nextStep: waitForPrimaryRunningInstances
   ```

------
#### [ JSON ]

   ```
   {
            "name":"verifyPrimaryInstancesRunning",
            "action":"aws:executeScript",
            "timeoutSeconds":600,
            "onFailure":"Abort",
            "inputs":{
               "Runtime":"python3.11",
               "Handler":"verifyInstancesRunning",
               "InputPayload":{
                  "targetInstances":"{{getPrimaryInstanceState.originalInstanceStates}}"
               },
               "Script":"..."
            },
            "nextStep":"waitForPrimaryRunningInstances"
         },
   ```

------

1. Emily는 `PrimaryPatchGroupTag` 파라미터에 지정된 태그와 연결된 모든 인스턴스가 시작되었거나 이미 `running` 상태인지 확인합니다. 그런 다음 다른 스크립트를 사용하여 이전 작업에서 시작된 인스턴스를 포함한 모든 인스턴스가 `running` 상태에 도달했는지 확인합니다.

------
#### [ YAML ]

   ```
   - name: waitForPrimaryRunningInstances
       action: 'aws:executeScript'
       timeoutSeconds: 300
       onFailure: Abort
       inputs:
         Runtime: python3.11
         Handler: waitForRunningInstances
         InputPayload:
           targetInstances: '{{getPrimaryInstanceState.originalInstanceStates}}'
         Script: |-
           def waitForRunningInstances(events,context):
             import boto3
   
             #Initialize client
             ec2 = boto3.client('ec2')
             instanceDict = events['targetInstances']
             for instance in instanceDict:
                 poll = ec2.get_waiter('instance_running')
                 poll.wait(
                     InstanceIds=[instance]
                 )
       nextStep: returnPrimaryTagKey
   ```

------
#### [ JSON ]

   ```
   {
            "name":"waitForPrimaryRunningInstances",
            "action":"aws:executeScript",
            "timeoutSeconds":300,
            "onFailure":"Abort",
            "inputs":{
               "Runtime":"python3.11",
               "Handler":"waitForRunningInstances",
               "InputPayload":{
                  "targetInstances":"{{getPrimaryInstanceState.originalInstanceStates}}"
               },
               "Script":"..."
            },
            "nextStep":"returnPrimaryTagKey"
         },
   ```

------

1. Emily는 2개의 스크립트를 더 사용하여 `PrimaryPatchGroupTag` 파라미터에 지정된 태그의 키와 값의 개별 `String` 값을 반환합니다. 이러한 작업에서 반환된 값을 통해 그녀는 `AWS-RunPatchBaseline` 문서의 `Targets` 파라미터에 직접 값을 제공할 수 있습니다. 그런 다음 자동화는 `aws:runCommand` 작업을 사용하여 `AWS-RunPatchBaseline` 문서로 인스턴스 패치를 진행합니다.

------
#### [ YAML ]

   ```
   - name: returnPrimaryTagKey
       action: 'aws:executeScript'
       timeoutSeconds: 120
       onFailure: Abort
       inputs:
         Runtime: python3.11
         Handler: returnTagValues
         InputPayload:
           primaryTag: '{{PrimaryPatchGroupTag}}'
         Script: |-
           def returnTagValues(events,context):
             tag = events['primaryTag']
             tagKey = list(tag)[0]
             stringKey = "tag:" + tagKey
             return {'tagKey' : stringKey}
       outputs:
         - Name: Payload
           Selector: $.Payload
           Type: StringMap
         - Name: primaryPatchGroupKey
           Selector: $.Payload.tagKey
           Type: String
       nextStep: returnPrimaryTagValue
     - name: returnPrimaryTagValue
       action: 'aws:executeScript'
       timeoutSeconds: 120
       onFailure: Abort
       inputs:
         Runtime: python3.11
         Handler: returnTagValues
         InputPayload:
           primaryTag: '{{PrimaryPatchGroupTag}}'
         Script: |-
           def returnTagValues(events,context):
             tag = events['primaryTag']
             tagKey = list(tag)[0]
             tagValue = tag[tagKey]
             return {'tagValue' : tagValue}
       outputs:
         - Name: Payload
           Selector: $.Payload
           Type: StringMap
         - Name: primaryPatchGroupValue
           Selector: $.Payload.tagValue
           Type: String
       nextStep: patchPrimaryInstances
     - name: patchPrimaryInstances
       action: 'aws:runCommand'
       onFailure: Abort
       timeoutSeconds: 7200
       inputs:
         DocumentName: AWS-RunPatchBaseline
         Parameters:
           SnapshotId: '{{SnapshotId}}'
           RebootOption: '{{RebootOption}}'
           Operation: '{{Operation}}'
         Targets:
           - Key: '{{returnPrimaryTagKey.primaryPatchGroupKey}}'
             Values:
               - '{{returnPrimaryTagValue.primaryPatchGroupValue}}'
         MaxConcurrency: 10%
         MaxErrors: 10%
       nextStep: returnPrimaryToOriginalState
   ```

------
#### [ JSON ]

   ```
   {
            "name":"returnPrimaryTagKey",
            "action":"aws:executeScript",
            "timeoutSeconds":120,
            "onFailure":"Abort",
            "inputs":{
               "Runtime":"python3.11",
               "Handler":"returnTagValues",
               "InputPayload":{
                  "primaryTag":"{{PrimaryPatchGroupTag}}"
               },
               "Script":"..."
            },
            "outputs":[
               {
                  "Name":"Payload",
                  "Selector":"$.Payload",
                  "Type":"StringMap"
               },
               {
                  "Name":"primaryPatchGroupKey",
                  "Selector":"$.Payload.tagKey",
                  "Type":"String"
               }
            ],
            "nextStep":"returnPrimaryTagValue"
         },
         {
            "name":"returnPrimaryTagValue",
            "action":"aws:executeScript",
            "timeoutSeconds":120,
            "onFailure":"Abort",
            "inputs":{
               "Runtime":"python3.11",
               "Handler":"returnTagValues",
               "InputPayload":{
                  "primaryTag":"{{PrimaryPatchGroupTag}}"
               },
               "Script":"..."
            },
            "outputs":[
               {
                  "Name":"Payload",
                  "Selector":"$.Payload",
                  "Type":"StringMap"
               },
               {
                  "Name":"primaryPatchGroupValue",
                  "Selector":"$.Payload.tagValue",
                  "Type":"String"
               }
            ],
            "nextStep":"patchPrimaryInstances"
         },
         {
            "name":"patchPrimaryInstances",
            "action":"aws:runCommand",
            "onFailure":"Abort",
            "timeoutSeconds":7200,
            "inputs":{
               "DocumentName":"AWS-RunPatchBaseline",
               "Parameters":{
                  "SnapshotId":"{{SnapshotId}}",
                  "RebootOption":"{{RebootOption}}",
                  "Operation":"{{Operation}}"
               },
               "Targets":[
                  {
                     "Key":"{{returnPrimaryTagKey.primaryPatchGroupKey}}",
                     "Values":[
                        "{{returnPrimaryTagValue.primaryPatchGroupValue}}"
                     ]
                  }
               ],
               "MaxConcurrency":"10%",
               "MaxErrors":"10%"
            },
            "nextStep":"returnPrimaryToOriginalState"
         },
   ```

------

1. 패치 작업이 완료된 후 Emily는 자동화가 `PrimaryPatchGroupTag` 파라미터에 지정된 태그와 연결된 대상 인스턴스를 자동화가 시작되기 전과 동일한 상태로 되돌리기를 원합니다. 그녀는 스크립트의 첫 번째 작업의 출력을 다시 사용하여 이 작업을 수행합니다. 대상 인스턴스의 원래 상태를 기준으로 인스턴스가 이전에 `running` 이외의 상태였으면 인스턴스를 중지합니다. 그렇지 않고 인스턴스 상태가 `running`이면 스크립트는 나머지 인스턴스를 계속 반복합니다.

------
#### [ YAML ]

   ```
   - name: returnPrimaryToOriginalState
       action: 'aws:executeScript'
       timeoutSeconds: 600
       onFailure: Abort
       inputs:
         Runtime: python3.11
         Handler: returnToOriginalState
         InputPayload:
           targetInstances: '{{getPrimaryInstanceState.originalInstanceStates}}'
         Script: |-
           def returnToOriginalState(events,context):
             import boto3
   
             #Initialize client
             ec2 = boto3.client('ec2')
             instanceDict = events['targetInstances']
             for instance in instanceDict:
               if instanceDict[instance] == 'stopped' or instanceDict[instance] == 'stopping':
                   ec2.stop_instances(
                       InstanceIds=[instance]
                       )
               else:
                 pass
       nextStep: getSecondaryInstanceState
   ```

------
#### [ JSON ]

   ```
   {
            "name":"returnPrimaryToOriginalState",
            "action":"aws:executeScript",
            "timeoutSeconds":600,
            "onFailure":"Abort",
            "inputs":{
               "Runtime":"python3.11",
               "Handler":"returnToOriginalState",
               "InputPayload":{
                  "targetInstances":"{{getPrimaryInstanceState.originalInstanceStates}}"
               },
               "Script":"..."
            },
            "nextStep":"getSecondaryInstanceState"
         },
   ```

------

1. `PrimaryPatchGroupTag` 파라미터에 지정된 태그와 연결된 인스턴스에 대해 패치 작업이 완료됩니다. 이제 Emily는 `SecondaryPatchGroupTag` 파라미터에 지정된 태그와 연결된 인스턴스를 대상으로 하기 위해 실행서 콘텐츠의 모든 이전 작업을 복제합니다.

------
#### [ YAML ]

   ```
   - name: getSecondaryInstanceState
       action: 'aws:executeScript'
       timeoutSeconds: 120
       onFailure: Abort
       inputs:
         Runtime: python3.11
         Handler: getInstanceStates
         InputPayload:
           secondaryTag: '{{SecondaryPatchGroupTag}}'
         Script: |-
           def getInstanceStates(events,context):
             import boto3
   
             #Initialize client
             ec2 = boto3.client('ec2')
             tag = events['secondaryTag']
             tagKey, tagValue = list(tag.items())[0]
             instanceQuery = ec2.describe_instances(
             Filters=[
                 {
                     "Name": "tag:" + tagKey,
                     "Values": [tagValue]
                 }]
             )
             if not instanceQuery['Reservations']:
                 noInstancesForTagString = "No instances found for specified tag."
                 return({ 'noInstancesFound' : noInstancesForTagString })
             else:
                 queryResponse = instanceQuery['Reservations']
                 originalInstanceStates = {}
                 for results in queryResponse:
                     instanceSet = results['Instances']
                     for instance in instanceSet:
                         instanceId = instance['InstanceId']
                         originalInstanceStates[instanceId] = instance['State']['Name']
                 return originalInstanceStates
       outputs:
         - Name: originalInstanceStates
           Selector: $.Payload
           Type: StringMap
       nextStep: verifySecondaryInstancesRunning
     - name: verifySecondaryInstancesRunning
       action: 'aws:executeScript'
       timeoutSeconds: 600
       onFailure: Abort
       inputs:
         Runtime: python3.11
         Handler: verifyInstancesRunning
         InputPayload:
           targetInstances: '{{getSecondaryInstanceState.originalInstanceStates}}'
         Script: |-
           def verifyInstancesRunning(events,context):
             import boto3
   
             #Initialize client
             ec2 = boto3.client('ec2')
             instanceDict = events['targetInstances']
             for instance in instanceDict:
               if instanceDict[instance] == 'stopped':
                   print("The target instance " + instance + " is stopped. The instance will now be started.")
                   ec2.start_instances(
                       InstanceIds=[instance]
                       )
               elif instanceDict[instance] == 'stopping':
                   print("The target instance " + instance + " is stopping. Polling for instance to reach stopped state.")
                   while instanceDict[instance] != 'stopped':
                       poll = ec2.get_waiter('instance_stopped')
                       poll.wait(
                           InstanceIds=[instance]
                       )
                   ec2.start_instances(
                       InstanceIds=[instance]
                   )
               else:
                 pass
       nextStep: waitForSecondaryRunningInstances
     - name: waitForSecondaryRunningInstances
       action: 'aws:executeScript'
       timeoutSeconds: 300
       onFailure: Abort
       inputs:
         Runtime: python3.11
         Handler: waitForRunningInstances
         InputPayload:
           targetInstances: '{{getSecondaryInstanceState.originalInstanceStates}}'
         Script: |-
           def waitForRunningInstances(events,context):
             import boto3
   
             #Initialize client
             ec2 = boto3.client('ec2')
             instanceDict = events['targetInstances']
             for instance in instanceDict:
                 poll = ec2.get_waiter('instance_running')
                 poll.wait(
                     InstanceIds=[instance]
                 )
       nextStep: returnSecondaryTagKey
     - name: returnSecondaryTagKey
       action: 'aws:executeScript'
       timeoutSeconds: 120
       onFailure: Abort
       inputs:
         Runtime: python3.11
         Handler: returnTagValues
         InputPayload:
           secondaryTag: '{{SecondaryPatchGroupTag}}'
         Script: |-
           def returnTagValues(events,context):
             tag = events['secondaryTag']
             tagKey = list(tag)[0]
             stringKey = "tag:" + tagKey
             return {'tagKey' : stringKey}
       outputs:
         - Name: Payload
           Selector: $.Payload
           Type: StringMap
         - Name: secondaryPatchGroupKey
           Selector: $.Payload.tagKey
           Type: String
       nextStep: returnSecondaryTagValue
     - name: returnSecondaryTagValue
       action: 'aws:executeScript'
       timeoutSeconds: 120
       onFailure: Abort
       inputs:
         Runtime: python3.11
         Handler: returnTagValues
         InputPayload:
           secondaryTag: '{{SecondaryPatchGroupTag}}'
         Script: |-
           def returnTagValues(events,context):
             tag = events['secondaryTag']
             tagKey = list(tag)[0]
             tagValue = tag[tagKey]
             return {'tagValue' : tagValue}
       outputs:
         - Name: Payload
           Selector: $.Payload
           Type: StringMap
         - Name: secondaryPatchGroupValue
           Selector: $.Payload.tagValue
           Type: String
       nextStep: patchSecondaryInstances
     - name: patchSecondaryInstances
       action: 'aws:runCommand'
       onFailure: Abort
       timeoutSeconds: 7200
       inputs:
         DocumentName: AWS-RunPatchBaseline
         Parameters:
           SnapshotId: '{{SnapshotId}}'
           RebootOption: '{{RebootOption}}'
           Operation: '{{Operation}}'
         Targets:
           - Key: '{{returnSecondaryTagKey.secondaryPatchGroupKey}}'
             Values:
             - '{{returnSecondaryTagValue.secondaryPatchGroupValue}}'
         MaxConcurrency: 10%
         MaxErrors: 10%
       nextStep: returnSecondaryToOriginalState
     - name: returnSecondaryToOriginalState
       action: 'aws:executeScript'
       timeoutSeconds: 600
       onFailure: Abort
       inputs:
         Runtime: python3.11
         Handler: returnToOriginalState
         InputPayload:
           targetInstances: '{{getSecondaryInstanceState.originalInstanceStates}}'
         Script: |-
           def returnToOriginalState(events,context):
             import boto3
   
             #Initialize client
             ec2 = boto3.client('ec2')
             instanceDict = events['targetInstances']
             for instance in instanceDict:
               if instanceDict[instance] == 'stopped' or instanceDict[instance] == 'stopping':
                   ec2.stop_instances(
                       InstanceIds=[instance]
                       )
               else:
                 pass
   ```

------
#### [ JSON ]

   ```
   {
            "name":"getSecondaryInstanceState",
            "action":"aws:executeScript",
            "timeoutSeconds":120,
            "onFailure":"Abort",
            "inputs":{
               "Runtime":"python3.11",
               "Handler":"getInstanceStates",
               "InputPayload":{
                  "secondaryTag":"{{SecondaryPatchGroupTag}}"
               },
               "Script":"..."
            },
            "outputs":[
               {
                  "Name":"originalInstanceStates",
                  "Selector":"$.Payload",
                  "Type":"StringMap"
               }
            ],
            "nextStep":"verifySecondaryInstancesRunning"
         },
         {
            "name":"verifySecondaryInstancesRunning",
            "action":"aws:executeScript",
            "timeoutSeconds":600,
            "onFailure":"Abort",
            "inputs":{
               "Runtime":"python3.11",
               "Handler":"verifyInstancesRunning",
               "InputPayload":{
                  "targetInstances":"{{getSecondaryInstanceState.originalInstanceStates}}"
               },
               "Script":"..."
            },
            "nextStep":"waitForSecondaryRunningInstances"
         },
         {
            "name":"waitForSecondaryRunningInstances",
            "action":"aws:executeScript",
            "timeoutSeconds":300,
            "onFailure":"Abort",
            "inputs":{
               "Runtime":"python3.11",
               "Handler":"waitForRunningInstances",
               "InputPayload":{
                  "targetInstances":"{{getSecondaryInstanceState.originalInstanceStates}}"
               },
               "Script":"..."
            },
            "nextStep":"returnSecondaryTagKey"
         },
         {
            "name":"returnSecondaryTagKey",
            "action":"aws:executeScript",
            "timeoutSeconds":120,
            "onFailure":"Abort",
            "inputs":{
               "Runtime":"python3.11",
               "Handler":"returnTagValues",
               "InputPayload":{
                  "secondaryTag":"{{SecondaryPatchGroupTag}}"
               },
               "Script":"..."
            },
            "outputs":[
               {
                  "Name":"Payload",
                  "Selector":"$.Payload",
                  "Type":"StringMap"
               },
               {
                  "Name":"secondaryPatchGroupKey",
                  "Selector":"$.Payload.tagKey",
                  "Type":"String"
               }
            ],
            "nextStep":"returnSecondaryTagValue"
         },
         {
            "name":"returnSecondaryTagValue",
            "action":"aws:executeScript",
            "timeoutSeconds":120,
            "onFailure":"Abort",
            "inputs":{
               "Runtime":"python3.11",
               "Handler":"returnTagValues",
               "InputPayload":{
                  "secondaryTag":"{{SecondaryPatchGroupTag}}"
               },
               "Script":"..."
            },
            "outputs":[
               {
                  "Name":"Payload",
                  "Selector":"$.Payload",
                  "Type":"StringMap"
               },
               {
                  "Name":"secondaryPatchGroupValue",
                  "Selector":"$.Payload.tagValue",
                  "Type":"String"
               }
            ],
            "nextStep":"patchSecondaryInstances"
         },
         {
            "name":"patchSecondaryInstances",
            "action":"aws:runCommand",
            "onFailure":"Abort",
            "timeoutSeconds":7200,
            "inputs":{
               "DocumentName":"AWS-RunPatchBaseline",
               "Parameters":{
                  "SnapshotId":"{{SnapshotId}}",
                  "RebootOption":"{{RebootOption}}",
                  "Operation":"{{Operation}}"
               },
               "Targets":[
                  {
                     "Key":"{{returnSecondaryTagKey.secondaryPatchGroupKey}}",
                     "Values":[
                        "{{returnSecondaryTagValue.secondaryPatchGroupValue}}"
                     ]
                  }
               ],
               "MaxConcurrency":"10%",
               "MaxErrors":"10%"
            },
            "nextStep":"returnSecondaryToOriginalState"
         },
         {
            "name":"returnSecondaryToOriginalState",
            "action":"aws:executeScript",
            "timeoutSeconds":600,
            "onFailure":"Abort",
            "inputs":{
               "Runtime":"python3.11",
               "Handler":"returnToOriginalState",
               "InputPayload":{
                  "targetInstances":"{{getSecondaryInstanceState.originalInstanceStates}}"
               },
               "Script":"..."
            }
         }
      ]
   }
   ```

------

1. Emily는 완성된 스크립팅된 실행서 콘텐츠를 검토하고 대상 인스턴스와 동일한 AWS 계정 및 AWS 리전에 실행서를 생성합니다. 이제 프로덕션 환경에 구현하기 전 실행서를 테스트하여 자동화가 원하는 대로 작동하는지 확인할 준비가 되었습니다. 다음은 완성된 스크립팅된 실행서 콘텐츠입니다.

------
#### [ YAML ]

   ```
   description: An example of an Automation runbook that patches groups of Amazon EC2 instances in stages.
   schemaVersion: '0.3'
   assumeRole: '{{AutomationAssumeRole}}'
   parameters:
     AutomationAssumeRole:
       type: String
       description: '(Required) The Amazon Resource Name (ARN) of the IAM role that allows Automation to perform the actions on your behalf. If no role is specified, Systems Manager Automation uses your IAM permissions to operate this runbook.'
     PrimaryPatchGroupTag:
       type: StringMap
       description: '(Required) The tag for the primary group of instances you want to patch. Specify a key-value pair. Example: {"key" : "value"}'
     SecondaryPatchGroupTag:
       type: StringMap
       description: '(Required) The tag for the secondary group of instances you want to patch. Specify a key-value pair. Example: {"key" : "value"}'
     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: getPrimaryInstanceState
       action: 'aws:executeScript'
       timeoutSeconds: 120
       onFailure: Abort
       inputs:
         Runtime: python3.11
         Handler: getInstanceStates
         InputPayload:
           primaryTag: '{{PrimaryPatchGroupTag}}'
         Script: |-
           def getInstanceStates(events,context):
             import boto3
   
             #Initialize client
             ec2 = boto3.client('ec2')
             tag = events['primaryTag']
             tagKey, tagValue = list(tag.items())[0]
             instanceQuery = ec2.describe_instances(
             Filters=[
                 {
                     "Name": "tag:" + tagKey,
                     "Values": [tagValue]
                 }]
             )
             if not instanceQuery['Reservations']:
                 noInstancesForTagString = "No instances found for specified tag."
                 return({ 'noInstancesFound' : noInstancesForTagString })
             else:
                 queryResponse = instanceQuery['Reservations']
                 originalInstanceStates = {}
                 for results in queryResponse:
                     instanceSet = results['Instances']
                     for instance in instanceSet:
                         instanceId = instance['InstanceId']
                         originalInstanceStates[instanceId] = instance['State']['Name']
                 return originalInstanceStates
       outputs:
         - Name: originalInstanceStates
           Selector: $.Payload
           Type: StringMap
       nextStep: verifyPrimaryInstancesRunning
     - name: verifyPrimaryInstancesRunning
       action: 'aws:executeScript'
       timeoutSeconds: 600
       onFailure: Abort
       inputs:
         Runtime: python3.11
         Handler: verifyInstancesRunning
         InputPayload:
           targetInstances: '{{getPrimaryInstanceState.originalInstanceStates}}'
         Script: |-
           def verifyInstancesRunning(events,context):
             import boto3
   
             #Initialize client
             ec2 = boto3.client('ec2')
             instanceDict = events['targetInstances']
             for instance in instanceDict:
               if instanceDict[instance] == 'stopped':
                   print("The target instance " + instance + " is stopped. The instance will now be started.")
                   ec2.start_instances(
                       InstanceIds=[instance]
                       )
               elif instanceDict[instance] == 'stopping':
                   print("The target instance " + instance + " is stopping. Polling for instance to reach stopped state.")
                   while instanceDict[instance] != 'stopped':
                       poll = ec2.get_waiter('instance_stopped')
                       poll.wait(
                           InstanceIds=[instance]
                       )
                   ec2.start_instances(
                       InstanceIds=[instance]
                   )
               else:
                 pass
       nextStep: waitForPrimaryRunningInstances
     - name: waitForPrimaryRunningInstances
       action: 'aws:executeScript'
       timeoutSeconds: 300
       onFailure: Abort
       inputs:
         Runtime: python3.11
         Handler: waitForRunningInstances
         InputPayload:
           targetInstances: '{{getPrimaryInstanceState.originalInstanceStates}}'
         Script: |-
           def waitForRunningInstances(events,context):
             import boto3
   
             #Initialize client
             ec2 = boto3.client('ec2')
             instanceDict = events['targetInstances']
             for instance in instanceDict:
                 poll = ec2.get_waiter('instance_running')
                 poll.wait(
                     InstanceIds=[instance]
                 )
       nextStep: returnPrimaryTagKey
     - name: returnPrimaryTagKey
       action: 'aws:executeScript'
       timeoutSeconds: 120
       onFailure: Abort
       inputs:
         Runtime: python3.11
         Handler: returnTagValues
         InputPayload:
           primaryTag: '{{PrimaryPatchGroupTag}}'
         Script: |-
           def returnTagValues(events,context):
             tag = events['primaryTag']
             tagKey = list(tag)[0]
             stringKey = "tag:" + tagKey
             return {'tagKey' : stringKey}
       outputs:
         - Name: Payload
           Selector: $.Payload
           Type: StringMap
         - Name: primaryPatchGroupKey
           Selector: $.Payload.tagKey
           Type: String
       nextStep: returnPrimaryTagValue
     - name: returnPrimaryTagValue
       action: 'aws:executeScript'
       timeoutSeconds: 120
       onFailure: Abort
       inputs:
         Runtime: python3.11
         Handler: returnTagValues
         InputPayload:
           primaryTag: '{{PrimaryPatchGroupTag}}'
         Script: |-
           def returnTagValues(events,context):
             tag = events['primaryTag']
             tagKey = list(tag)[0]
             tagValue = tag[tagKey]
             return {'tagValue' : tagValue}
       outputs:
         - Name: Payload
           Selector: $.Payload
           Type: StringMap
         - Name: primaryPatchGroupValue
           Selector: $.Payload.tagValue
           Type: String
       nextStep: patchPrimaryInstances
     - name: patchPrimaryInstances
       action: 'aws:runCommand'
       onFailure: Abort
       timeoutSeconds: 7200
       inputs:
         DocumentName: AWS-RunPatchBaseline
         Parameters:
           SnapshotId: '{{SnapshotId}}'
           RebootOption: '{{RebootOption}}'
           Operation: '{{Operation}}'
         Targets:
           - Key: '{{returnPrimaryTagKey.primaryPatchGroupKey}}'
             Values:
               - '{{returnPrimaryTagValue.primaryPatchGroupValue}}'
         MaxConcurrency: 10%
         MaxErrors: 10%
       nextStep: returnPrimaryToOriginalState
     - name: returnPrimaryToOriginalState
       action: 'aws:executeScript'
       timeoutSeconds: 600
       onFailure: Abort
       inputs:
         Runtime: python3.11
         Handler: returnToOriginalState
         InputPayload:
           targetInstances: '{{getPrimaryInstanceState.originalInstanceStates}}'
         Script: |-
           def returnToOriginalState(events,context):
             import boto3
   
             #Initialize client
             ec2 = boto3.client('ec2')
             instanceDict = events['targetInstances']
             for instance in instanceDict:
               if instanceDict[instance] == 'stopped' or instanceDict[instance] == 'stopping':
                   ec2.stop_instances(
                       InstanceIds=[instance]
                       )
               else:
                 pass
       nextStep: getSecondaryInstanceState
     - name: getSecondaryInstanceState
       action: 'aws:executeScript'
       timeoutSeconds: 120
       onFailure: Abort
       inputs:
         Runtime: python3.11
         Handler: getInstanceStates
         InputPayload:
           secondaryTag: '{{SecondaryPatchGroupTag}}'
         Script: |-
           def getInstanceStates(events,context):
             import boto3
   
             #Initialize client
             ec2 = boto3.client('ec2')
             tag = events['secondaryTag']
             tagKey, tagValue = list(tag.items())[0]
             instanceQuery = ec2.describe_instances(
             Filters=[
                 {
                     "Name": "tag:" + tagKey,
                     "Values": [tagValue]
                 }]
             )
             if not instanceQuery['Reservations']:
                 noInstancesForTagString = "No instances found for specified tag."
                 return({ 'noInstancesFound' : noInstancesForTagString })
             else:
                 queryResponse = instanceQuery['Reservations']
                 originalInstanceStates = {}
                 for results in queryResponse:
                     instanceSet = results['Instances']
                     for instance in instanceSet:
                         instanceId = instance['InstanceId']
                         originalInstanceStates[instanceId] = instance['State']['Name']
                 return originalInstanceStates
       outputs:
         - Name: originalInstanceStates
           Selector: $.Payload
           Type: StringMap
       nextStep: verifySecondaryInstancesRunning
     - name: verifySecondaryInstancesRunning
       action: 'aws:executeScript'
       timeoutSeconds: 600
       onFailure: Abort
       inputs:
         Runtime: python3.11
         Handler: verifyInstancesRunning
         InputPayload:
           targetInstances: '{{getSecondaryInstanceState.originalInstanceStates}}'
         Script: |-
           def verifyInstancesRunning(events,context):
             import boto3
   
             #Initialize client
             ec2 = boto3.client('ec2')
             instanceDict = events['targetInstances']
             for instance in instanceDict:
               if instanceDict[instance] == 'stopped':
                   print("The target instance " + instance + " is stopped. The instance will now be started.")
                   ec2.start_instances(
                       InstanceIds=[instance]
                       )
               elif instanceDict[instance] == 'stopping':
                   print("The target instance " + instance + " is stopping. Polling for instance to reach stopped state.")
                   while instanceDict[instance] != 'stopped':
                       poll = ec2.get_waiter('instance_stopped')
                       poll.wait(
                           InstanceIds=[instance]
                       )
                   ec2.start_instances(
                       InstanceIds=[instance]
                   )
               else:
                 pass
       nextStep: waitForSecondaryRunningInstances
     - name: waitForSecondaryRunningInstances
       action: 'aws:executeScript'
       timeoutSeconds: 300
       onFailure: Abort
       inputs:
         Runtime: python3.11
         Handler: waitForRunningInstances
         InputPayload:
           targetInstances: '{{getSecondaryInstanceState.originalInstanceStates}}'
         Script: |-
           def waitForRunningInstances(events,context):
             import boto3
   
             #Initialize client
             ec2 = boto3.client('ec2')
             instanceDict = events['targetInstances']
             for instance in instanceDict:
                 poll = ec2.get_waiter('instance_running')
                 poll.wait(
                     InstanceIds=[instance]
                 )
       nextStep: returnSecondaryTagKey
     - name: returnSecondaryTagKey
       action: 'aws:executeScript'
       timeoutSeconds: 120
       onFailure: Abort
       inputs:
         Runtime: python3.11
         Handler: returnTagValues
         InputPayload:
           secondaryTag: '{{SecondaryPatchGroupTag}}'
         Script: |-
           def returnTagValues(events,context):
             tag = events['secondaryTag']
             tagKey = list(tag)[0]
             stringKey = "tag:" + tagKey
             return {'tagKey' : stringKey}
       outputs:
         - Name: Payload
           Selector: $.Payload
           Type: StringMap
         - Name: secondaryPatchGroupKey
           Selector: $.Payload.tagKey
           Type: String
       nextStep: returnSecondaryTagValue
     - name: returnSecondaryTagValue
       action: 'aws:executeScript'
       timeoutSeconds: 120
       onFailure: Abort
       inputs:
         Runtime: python3.11
         Handler: returnTagValues
         InputPayload:
           secondaryTag: '{{SecondaryPatchGroupTag}}'
         Script: |-
           def returnTagValues(events,context):
             tag = events['secondaryTag']
             tagKey = list(tag)[0]
             tagValue = tag[tagKey]
             return {'tagValue' : tagValue}
       outputs:
         - Name: Payload
           Selector: $.Payload
           Type: StringMap
         - Name: secondaryPatchGroupValue
           Selector: $.Payload.tagValue
           Type: String
       nextStep: patchSecondaryInstances
     - name: patchSecondaryInstances
       action: 'aws:runCommand'
       onFailure: Abort
       timeoutSeconds: 7200
       inputs:
         DocumentName: AWS-RunPatchBaseline
         Parameters:
           SnapshotId: '{{SnapshotId}}'
           RebootOption: '{{RebootOption}}'
           Operation: '{{Operation}}'
         Targets:
           - Key: '{{returnSecondaryTagKey.secondaryPatchGroupKey}}'
             Values:
             - '{{returnSecondaryTagValue.secondaryPatchGroupValue}}'
         MaxConcurrency: 10%
         MaxErrors: 10%
       nextStep: returnSecondaryToOriginalState
     - name: returnSecondaryToOriginalState
       action: 'aws:executeScript'
       timeoutSeconds: 600
       onFailure: Abort
       inputs:
         Runtime: python3.11
         Handler: returnToOriginalState
         InputPayload:
           targetInstances: '{{getSecondaryInstanceState.originalInstanceStates}}'
         Script: |-
           def returnToOriginalState(events,context):
             import boto3
   
             #Initialize client
             ec2 = boto3.client('ec2')
             instanceDict = events['targetInstances']
             for instance in instanceDict:
               if instanceDict[instance] == 'stopped' or instanceDict[instance] == 'stopping':
                   ec2.stop_instances(
                       InstanceIds=[instance]
                       )
               else:
                 pass
   ```

------
#### [ JSON ]

   ```
   {
      "description":"An example of an Automation runbook that patches groups of Amazon EC2 instances in stages.",
      "schemaVersion":"0.3",
      "assumeRole":"{{AutomationAssumeRole}}",
      "parameters":{
         "AutomationAssumeRole":{
            "type":"String",
            "description":"(Required) The Amazon Resource Name (ARN) of the IAM role that allows Automation to perform the actions on your behalf. If no role is specified, Systems Manager Automation uses your IAM permissions to operate this runbook."
         },
         "PrimaryPatchGroupTag":{
            "type":"StringMap",
            "description":"(Required) The tag for the primary group of instances you want to patch. Specify a key-value pair. Example: {\"key\" : \"value\"}"
         },
         "SecondaryPatchGroupTag":{
            "type":"StringMap",
            "description":"(Required) The tag for the secondary group of instances you want to patch. Specify a key-value pair. Example: {\"key\" : \"value\"}"
         },
         "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":"getPrimaryInstanceState",
            "action":"aws:executeScript",
            "timeoutSeconds":120,
            "onFailure":"Abort",
            "inputs":{
               "Runtime":"python3.11",
               "Handler":"getInstanceStates",
               "InputPayload":{
                  "primaryTag":"{{PrimaryPatchGroupTag}}"
               },
               "Script":"..."
            },
            "outputs":[
               {
                  "Name":"originalInstanceStates",
                  "Selector":"$.Payload",
                  "Type":"StringMap"
               }
            ],
            "nextStep":"verifyPrimaryInstancesRunning"
         },
         {
            "name":"verifyPrimaryInstancesRunning",
            "action":"aws:executeScript",
            "timeoutSeconds":600,
            "onFailure":"Abort",
            "inputs":{
               "Runtime":"python3.11",
               "Handler":"verifyInstancesRunning",
               "InputPayload":{
                  "targetInstances":"{{getPrimaryInstanceState.originalInstanceStates}}"
               },
               "Script":"..."
            },
            "nextStep":"waitForPrimaryRunningInstances"
         },
         {
            "name":"waitForPrimaryRunningInstances",
            "action":"aws:executeScript",
            "timeoutSeconds":300,
            "onFailure":"Abort",
            "inputs":{
               "Runtime":"python3.11",
               "Handler":"waitForRunningInstances",
               "InputPayload":{
                  "targetInstances":"{{getPrimaryInstanceState.originalInstanceStates}}"
               },
               "Script":"..."
            },
            "nextStep":"returnPrimaryTagKey"
         },
         {
            "name":"returnPrimaryTagKey",
            "action":"aws:executeScript",
            "timeoutSeconds":120,
            "onFailure":"Abort",
            "inputs":{
               "Runtime":"python3.11",
               "Handler":"returnTagValues",
               "InputPayload":{
                  "primaryTag":"{{PrimaryPatchGroupTag}}"
               },
               "Script":"..."
            },
            "outputs":[
               {
                  "Name":"Payload",
                  "Selector":"$.Payload",
                  "Type":"StringMap"
               },
               {
                  "Name":"primaryPatchGroupKey",
                  "Selector":"$.Payload.tagKey",
                  "Type":"String"
               }
            ],
            "nextStep":"returnPrimaryTagValue"
         },
         {
            "name":"returnPrimaryTagValue",
            "action":"aws:executeScript",
            "timeoutSeconds":120,
            "onFailure":"Abort",
            "inputs":{
               "Runtime":"python3.11",
               "Handler":"returnTagValues",
               "InputPayload":{
                  "primaryTag":"{{PrimaryPatchGroupTag}}"
               },
               "Script":"..."
            },
            "outputs":[
               {
                  "Name":"Payload",
                  "Selector":"$.Payload",
                  "Type":"StringMap"
               },
               {
                  "Name":"primaryPatchGroupValue",
                  "Selector":"$.Payload.tagValue",
                  "Type":"String"
               }
            ],
            "nextStep":"patchPrimaryInstances"
         },
         {
            "name":"patchPrimaryInstances",
            "action":"aws:runCommand",
            "onFailure":"Abort",
            "timeoutSeconds":7200,
            "inputs":{
               "DocumentName":"AWS-RunPatchBaseline",
               "Parameters":{
                  "SnapshotId":"{{SnapshotId}}",
                  "RebootOption":"{{RebootOption}}",
                  "Operation":"{{Operation}}"
               },
               "Targets":[
                  {
                     "Key":"{{returnPrimaryTagKey.primaryPatchGroupKey}}",
                     "Values":[
                        "{{returnPrimaryTagValue.primaryPatchGroupValue}}"
                     ]
                  }
               ],
               "MaxConcurrency":"10%",
               "MaxErrors":"10%"
            },
            "nextStep":"returnPrimaryToOriginalState"
         },
         {
            "name":"returnPrimaryToOriginalState",
            "action":"aws:executeScript",
            "timeoutSeconds":600,
            "onFailure":"Abort",
            "inputs":{
               "Runtime":"python3.11",
               "Handler":"returnToOriginalState",
               "InputPayload":{
                  "targetInstances":"{{getPrimaryInstanceState.originalInstanceStates}}"
               },
               "Script":"..."
            },
            "nextStep":"getSecondaryInstanceState"
         },
         {
            "name":"getSecondaryInstanceState",
            "action":"aws:executeScript",
            "timeoutSeconds":120,
            "onFailure":"Abort",
            "inputs":{
               "Runtime":"python3.11",
               "Handler":"getInstanceStates",
               "InputPayload":{
                  "secondaryTag":"{{SecondaryPatchGroupTag}}"
               },
               "Script":"..."
            },
            "outputs":[
               {
                  "Name":"originalInstanceStates",
                  "Selector":"$.Payload",
                  "Type":"StringMap"
               }
            ],
            "nextStep":"verifySecondaryInstancesRunning"
         },
         {
            "name":"verifySecondaryInstancesRunning",
            "action":"aws:executeScript",
            "timeoutSeconds":600,
            "onFailure":"Abort",
            "inputs":{
               "Runtime":"python3.11",
               "Handler":"verifyInstancesRunning",
               "InputPayload":{
                  "targetInstances":"{{getSecondaryInstanceState.originalInstanceStates}}"
               },
               "Script":"..."
            },
            "nextStep":"waitForSecondaryRunningInstances"
         },
         {
            "name":"waitForSecondaryRunningInstances",
            "action":"aws:executeScript",
            "timeoutSeconds":300,
            "onFailure":"Abort",
            "inputs":{
               "Runtime":"python3.11",
               "Handler":"waitForRunningInstances",
               "InputPayload":{
                  "targetInstances":"{{getSecondaryInstanceState.originalInstanceStates}}"
               },
               "Script":"..."
            },
            "nextStep":"returnSecondaryTagKey"
         },
         {
            "name":"returnSecondaryTagKey",
            "action":"aws:executeScript",
            "timeoutSeconds":120,
            "onFailure":"Abort",
            "inputs":{
               "Runtime":"python3.11",
               "Handler":"returnTagValues",
               "InputPayload":{
                  "secondaryTag":"{{SecondaryPatchGroupTag}}"
               },
               "Script":"..."
            },
            "outputs":[
               {
                  "Name":"Payload",
                  "Selector":"$.Payload",
                  "Type":"StringMap"
               },
               {
                  "Name":"secondaryPatchGroupKey",
                  "Selector":"$.Payload.tagKey",
                  "Type":"String"
               }
            ],
            "nextStep":"returnSecondaryTagValue"
         },
         {
            "name":"returnSecondaryTagValue",
            "action":"aws:executeScript",
            "timeoutSeconds":120,
            "onFailure":"Abort",
            "inputs":{
               "Runtime":"python3.11",
               "Handler":"returnTagValues",
               "InputPayload":{
                  "secondaryTag":"{{SecondaryPatchGroupTag}}"
               },
               "Script":"..."
            },
            "outputs":[
               {
                  "Name":"Payload",
                  "Selector":"$.Payload",
                  "Type":"StringMap"
               },
               {
                  "Name":"secondaryPatchGroupValue",
                  "Selector":"$.Payload.tagValue",
                  "Type":"String"
               }
            ],
            "nextStep":"patchSecondaryInstances"
         },
         {
            "name":"patchSecondaryInstances",
            "action":"aws:runCommand",
            "onFailure":"Abort",
            "timeoutSeconds":7200,
            "inputs":{
               "DocumentName":"AWS-RunPatchBaseline",
               "Parameters":{
                  "SnapshotId":"{{SnapshotId}}",
                  "RebootOption":"{{RebootOption}}",
                  "Operation":"{{Operation}}"
               },
               "Targets":[
                  {
                     "Key":"{{returnSecondaryTagKey.secondaryPatchGroupKey}}",
                     "Values":[
                        "{{returnSecondaryTagValue.secondaryPatchGroupValue}}"
                     ]
                  }
               ],
               "MaxConcurrency":"10%",
               "MaxErrors":"10%"
            },
            "nextStep":"returnSecondaryToOriginalState"
         },
         {
            "name":"returnSecondaryToOriginalState",
            "action":"aws:executeScript",
            "timeoutSeconds":600,
            "onFailure":"Abort",
            "inputs":{
               "Runtime":"python3.11",
               "Handler":"returnToOriginalState",
               "InputPayload":{
                  "targetInstances":"{{getSecondaryInstanceState.originalInstanceStates}}"
               },
               "Script":"..."
            }
         }
      ]
   }
   ```

------

이 예에 사용되는 자동화 작업에 대한 자세한 내용은 [Systems Manager Automation 작업 참조](automation-actions.md) 섹션을 참조하세요.

# 추가 런북 예제
<a name="automation-document-examples"></a>

다음 예제 런북에서는 AWS Systems Manager Automation 작업을 사용하여 일반적인 배포, 문제 해결 및 유지 관리 태스크를 자동화하는 방법을 보여줍니다.

**참고**  
이 섹션의 예제 런북은 특정 운영 요구를 지원하기 위해 사용자 지정 런북을 생성하는 방법을 보여주기 위한 것입니다. 이러한 실행서는 프로덕션 환경에서 현재 그대로 사용할 수 없습니다. 하지만 자체적인 용도로 사용자 정의할 수 있습니다.

**Topics**
+ [

# VPC 아키텍처 및 Microsoft Active Directory 도메인 컨트롤러 배포
](automation-document-architecture-deployment-example.md)
+ [

# 최신 스냅샷에서 루트 볼륨 복원
](automation-document-instance-recovery-example.md)
+ [

# AMI 및 크로스 리전 복사본 생성
](automation-document-backup-maintenance-example.md)

# VPC 아키텍처 및 Microsoft Active Directory 도메인 컨트롤러 배포
<a name="automation-document-architecture-deployment-example"></a>

효율성을 높이고 일반적인 작업을 표준화하기 위해 배포를 자동화하도록 선택할 수 있습니다. 이 기능은 여러 계정 및 AWS 리전에 동일한 아키텍처를 정기적으로 배포하는 경우에 유용합니다. 또한 아키텍처 배포를 자동화하면 수동으로 아키텍처를 배포할 때 발생할 수 있는 인적 오류의 가능성을 줄일 수 있습니다. AWS Systems Manager 이러한 경우 Automation 작업이 도움이 될 수 있습니다. Automation은 AWS Systems Manager의 도구입니다.

다음 예제 AWS Systems Manager 런북은 다음과 같은 작업을 수행합니다.
+ 도메인 컨트롤러로 구성할 EC2 인스턴스를 시작할 때 사용할 Systems Manager Parameter Store를 통해 최신 Windows Server 2016 Amazon Machine Image(AMI)를 검색합니다. Parameter Store는 AWS Systems Manager의 도구입니다.
+ `aws:executeAwsApi` Automation 작업으로 여러 AWS API 작업을 호출하여 VPC 아키텍처를 생성합니다. 도메인 컨트롤러 인스턴스는 프라이빗 서브넷에서 시작되고 NAT 게이트웨이를 사용하여 인터넷에 연결됩니다. 이렇게 하면 인스턴스의 SSM Agent가 필수 Systems Manager 엔드포인트에 액세스할 수 있습니다.
+ `aws:waitForAwsResourceProperty` 자동화 작업을 사용하여 이전 작업으로 시작된 인스턴스가 AWS Systems Manager에 대해 `Online`인지 확인합니다.
+ `aws:runCommand` 자동화 작업을 사용하여 Microsoft Active Directory 도메인 컨트롤러로 시작된 인스턴스를 구성합니다.

------
#### [ YAML ]

```
    ---
    description: Custom Automation Deployment Example
    schemaVersion: '0.3'
    parameters:
      AutomationAssumeRole:
        type: String
        default: ''
        description: >-
          (Optional) 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 run this runbook.
    mainSteps:
      - name: getLatestWindowsAmi
        action: aws:executeAwsApi
        onFailure: Abort
        inputs:
          Service: ssm
          Api: GetParameter
          Name: >-
            /aws/service/ami-windows-latest/Windows_Server-2016-English-Full-Base
        outputs:
          - Name: amiId
            Selector: $.Parameter.Value
            Type: String
        nextStep: createSSMInstanceRole
      - name: createSSMInstanceRole
        action: aws:executeAwsApi
        onFailure: Abort
        inputs:
          Service: iam
          Api: CreateRole
          AssumeRolePolicyDocument: >-
            {"Version": "2012-10-17",		 	 	 "Statement":[{"Effect":"Allow","Principal":{"Service":["ec2.amazonaws.com"]},"Action":["sts:AssumeRole"]}]}
          RoleName: sampleSSMInstanceRole
        nextStep: attachManagedSSMPolicy
      - name: attachManagedSSMPolicy
        action: aws:executeAwsApi
        onFailure: Abort
        inputs:
          Service: iam
          Api: AttachRolePolicy
          PolicyArn: 'arn:aws:iam::aws:policy/service-role/AmazonSSMManagedInstanceCore'
          RoleName: sampleSSMInstanceRole
        nextStep: createSSMInstanceProfile
      - name: createSSMInstanceProfile
        action: aws:executeAwsApi
        onFailure: Abort
        inputs:
          Service: iam
          Api: CreateInstanceProfile
          InstanceProfileName: sampleSSMInstanceRole
        outputs:
          - Name: instanceProfileArn
            Selector: $.InstanceProfile.Arn
            Type: String
        nextStep: addSSMInstanceRoleToProfile
      - name: addSSMInstanceRoleToProfile
        action: aws:executeAwsApi
        onFailure: Abort
        inputs:
          Service: iam
          Api: AddRoleToInstanceProfile
          InstanceProfileName: sampleSSMInstanceRole
          RoleName: sampleSSMInstanceRole
        nextStep: createVpc
      - name: createVpc
        action: aws:executeAwsApi
        onFailure: Abort
        inputs:
          Service: ec2
          Api: CreateVpc
          CidrBlock: 10.0.100.0/22
        outputs:
          - Name: vpcId
            Selector: $.Vpc.VpcId
            Type: String
        nextStep: getMainRtb
      - name: getMainRtb
        action: aws:executeAwsApi
        onFailure: Abort
        inputs:
          Service: ec2
          Api: DescribeRouteTables
          Filters:
            - Name: vpc-id
              Values:
                - '{{ createVpc.vpcId }}'
        outputs:
          - Name: mainRtbId
            Selector: '$.RouteTables[0].RouteTableId'
            Type: String
        nextStep: verifyMainRtb
      - name: verifyMainRtb
        action: aws:assertAwsResourceProperty
        onFailure: Abort
        inputs:
          Service: ec2
          Api: DescribeRouteTables
          RouteTableIds:
            - '{{ getMainRtb.mainRtbId }}'
          PropertySelector: '$.RouteTables[0].Associations[0].Main'
          DesiredValues:
            - 'True'
        nextStep: createPubSubnet
      - name: createPubSubnet
        action: aws:executeAwsApi
        onFailure: Abort
        inputs:
          Service: ec2
          Api: CreateSubnet
          CidrBlock: 10.0.103.0/24
          AvailabilityZone: us-west-2c
          VpcId: '{{ createVpc.vpcId }}'
        outputs:
          - Name: pubSubnetId
            Selector: $.Subnet.SubnetId
            Type: String
        nextStep: createPubRtb
      - name: createPubRtb
        action: aws:executeAwsApi
        onFailure: Abort
        inputs:
          Service: ec2
          Api: CreateRouteTable
          VpcId: '{{ createVpc.vpcId }}'
        outputs:
          - Name: pubRtbId
            Selector: $.RouteTable.RouteTableId
            Type: String
        nextStep: createIgw
      - name: createIgw
        action: aws:executeAwsApi
        onFailure: Abort
        inputs:
          Service: ec2
          Api: CreateInternetGateway
        outputs:
          - Name: igwId
            Selector: $.InternetGateway.InternetGatewayId
            Type: String
        nextStep: attachIgw
      - name: attachIgw
        action: aws:executeAwsApi
        onFailure: Abort
        inputs:
          Service: ec2
          Api: AttachInternetGateway
          InternetGatewayId: '{{ createIgw.igwId }}'
          VpcId: '{{ createVpc.vpcId }}'
        nextStep: allocateEip
      - name: allocateEip
        action: aws:executeAwsApi
        onFailure: Abort
        inputs:
          Service: ec2
          Api: AllocateAddress
          Domain: vpc
        outputs:
          - Name: eipAllocationId
            Selector: $.AllocationId
            Type: String
        nextStep: createNatGw
      - name: createNatGw
        action: aws:executeAwsApi
        onFailure: Abort
        inputs:
          Service: ec2
          Api: CreateNatGateway
          AllocationId: '{{ allocateEip.eipAllocationId }}'
          SubnetId: '{{ createPubSubnet.pubSubnetId }}'
        outputs:
          - Name: natGwId
            Selector: $.NatGateway.NatGatewayId
            Type: String
        nextStep: verifyNatGwAvailable
      - name: verifyNatGwAvailable
        action: aws:waitForAwsResourceProperty
        timeoutSeconds: 150
        inputs:
          Service: ec2
          Api: DescribeNatGateways
          NatGatewayIds:
            - '{{ createNatGw.natGwId }}'
          PropertySelector: '$.NatGateways[0].State'
          DesiredValues:
            - available
        nextStep: createNatRoute
      - name: createNatRoute
        action: aws:executeAwsApi
        onFailure: Abort
        inputs:
          Service: ec2
          Api: CreateRoute
          DestinationCidrBlock: 0.0.0.0/0
          NatGatewayId: '{{ createNatGw.natGwId }}'
          RouteTableId: '{{ getMainRtb.mainRtbId }}'
        nextStep: createPubRoute
      - name: createPubRoute
        action: aws:executeAwsApi
        onFailure: Abort
        inputs:
          Service: ec2
          Api: CreateRoute
          DestinationCidrBlock: 0.0.0.0/0
          GatewayId: '{{ createIgw.igwId }}'
          RouteTableId: '{{ createPubRtb.pubRtbId }}'
        nextStep: setPubSubAssoc
      - name: setPubSubAssoc
        action: aws:executeAwsApi
        onFailure: Abort
        inputs:
          Service: ec2
          Api: AssociateRouteTable
          RouteTableId: '{{ createPubRtb.pubRtbId }}'
          SubnetId: '{{ createPubSubnet.pubSubnetId }}'
      - name: createDhcpOptions
        action: aws:executeAwsApi
        onFailure: Abort
        inputs:
          Service: ec2
          Api: CreateDhcpOptions
          DhcpConfigurations:
            - Key: domain-name-servers
              Values:
                - '10.0.100.50,10.0.101.50'
            - Key: domain-name
              Values:
                - sample.com
        outputs:
          - Name: dhcpOptionsId
            Selector: $.DhcpOptions.DhcpOptionsId
            Type: String
        nextStep: createDCSubnet1
      - name: createDCSubnet1
        action: aws:executeAwsApi
        onFailure: Abort
        inputs:
          Service: ec2
          Api: CreateSubnet
          CidrBlock: 10.0.100.0/24
          AvailabilityZone: us-west-2a
          VpcId: '{{ createVpc.vpcId }}'
        outputs:
          - Name: firstSubnetId
            Selector: $.Subnet.SubnetId
            Type: String
        nextStep: createDCSubnet2
      - name: createDCSubnet2
        action: aws:executeAwsApi
        onFailure: Abort
        inputs:
          Service: ec2
          Api: CreateSubnet
          CidrBlock: 10.0.101.0/24
          AvailabilityZone: us-west-2b
          VpcId: '{{ createVpc.vpcId }}'
        outputs:
          - Name: secondSubnetId
            Selector: $.Subnet.SubnetId
            Type: String
        nextStep: createDCSecGroup
      - name: createDCSecGroup
        action: aws:executeAwsApi
        onFailure: Abort
        inputs:
          Service: ec2
          Api: CreateSecurityGroup
          GroupName: SampleDCSecGroup
          Description: Security Group for Sample Domain Controllers
          VpcId: '{{ createVpc.vpcId }}'
        outputs:
          - Name: dcSecGroupId
            Selector: $.GroupId
            Type: String
        nextStep: authIngressDCTraffic
      - name: authIngressDCTraffic
        action: aws:executeAwsApi
        onFailure: Abort
        inputs:
          Service: ec2
          Api: AuthorizeSecurityGroupIngress
          GroupId: '{{ createDCSecGroup.dcSecGroupId }}'
          IpPermissions:
            - FromPort: -1
              IpProtocol: '-1'
              IpRanges:
                - CidrIp: 0.0.0.0/0
                  Description: Allow all traffic between Domain Controllers
        nextStep: verifyInstanceProfile
      - name: verifyInstanceProfile
        action: aws:waitForAwsResourceProperty
        maxAttempts: 5
        onFailure: Abort
        inputs:
          Service: iam
          Api: ListInstanceProfilesForRole
          RoleName: sampleSSMInstanceRole
          PropertySelector: '$.InstanceProfiles[0].Arn'
          DesiredValues:
            - '{{ createSSMInstanceProfile.instanceProfileArn }}'
        nextStep: iamEventualConsistency
      - name: iamEventualConsistency
        action: aws:sleep
        inputs:
          Duration: PT2M
        nextStep: launchDC1
      - name: launchDC1
        action: aws:executeAwsApi
        onFailure: Abort
        inputs:
          Service: ec2
          Api: RunInstances
          BlockDeviceMappings:
            - DeviceName: /dev/sda1
              Ebs:
                DeleteOnTermination: true
                VolumeSize: 50
                VolumeType: gp2
            - DeviceName: xvdf
              Ebs:
                DeleteOnTermination: true
                VolumeSize: 100
                VolumeType: gp2
          IamInstanceProfile:
            Arn: '{{ createSSMInstanceProfile.instanceProfileArn }}'
          ImageId: '{{ getLatestWindowsAmi.amiId }}'
          InstanceType: t2.micro
          MaxCount: 1
          MinCount: 1
          PrivateIpAddress: 10.0.100.50
          SecurityGroupIds:
            - '{{ createDCSecGroup.dcSecGroupId }}'
          SubnetId: '{{ createDCSubnet1.firstSubnetId }}'
          TagSpecifications:
            - ResourceType: instance
              Tags:
                - Key: Name
                  Value: SampleDC1
        outputs:
          - Name: pdcInstanceId
            Selector: '$.Instances[0].InstanceId'
            Type: String
        nextStep: launchDC2
      - name: launchDC2
        action: aws:executeAwsApi
        onFailure: Abort
        inputs:
          Service: ec2
          Api: RunInstances
          BlockDeviceMappings:
            - DeviceName: /dev/sda1
              Ebs:
                DeleteOnTermination: true
                VolumeSize: 50
                VolumeType: gp2
            - DeviceName: xvdf
              Ebs:
                DeleteOnTermination: true
                VolumeSize: 100
                VolumeType: gp2
          IamInstanceProfile:
            Arn: '{{ createSSMInstanceProfile.instanceProfileArn }}'
          ImageId: '{{ getLatestWindowsAmi.amiId }}'
          InstanceType: t2.micro
          MaxCount: 1
          MinCount: 1
          PrivateIpAddress: 10.0.101.50
          SecurityGroupIds:
            - '{{ createDCSecGroup.dcSecGroupId }}'
          SubnetId: '{{ createDCSubnet2.secondSubnetId }}'
          TagSpecifications:
            - ResourceType: instance
              Tags:
                - Key: Name
                  Value: SampleDC2
        outputs:
          - Name: adcInstanceId
            Selector: '$.Instances[0].InstanceId'
            Type: String
        nextStep: verifyDCInstanceState
      - name: verifyDCInstanceState
        action: aws:waitForAwsResourceProperty
        inputs:
          Service: ec2
          Api: DescribeInstanceStatus
          IncludeAllInstances: true
          InstanceIds:
            - '{{ launchDC1.pdcInstanceId }}'
            - '{{ launchDC2.adcInstanceId }}'
          PropertySelector: '$.InstanceStatuses..InstanceState.Name'
          DesiredValues:
            - running
        nextStep: verifyInstancesOnlineSSM
      - name: verifyInstancesOnlineSSM
        action: aws:waitForAwsResourceProperty
        timeoutSeconds: 600
        inputs:
          Service: ssm
          Api: DescribeInstanceInformation
          InstanceInformationFilterList:
            - key: InstanceIds
              valueSet:
                - '{{ launchDC1.pdcInstanceId }}'
                - '{{ launchDC2.adcInstanceId }}'
          PropertySelector: '$.InstanceInformationList..PingStatus'
          DesiredValues:
            - Online
        nextStep: installADRoles
      - name: installADRoles
        action: aws:runCommand
        inputs:
          DocumentName: AWS-RunPowerShellScript
          InstanceIds:
            - '{{ launchDC1.pdcInstanceId }}'
            - '{{ launchDC2.adcInstanceId }}'
          Parameters:
            commands: |-
              try {
                  Install-WindowsFeature -Name AD-Domain-Services -IncludeManagementTools
              }
              catch {
                  Write-Error "Failed to install ADDS Role."
              }
        nextStep: setAdminPassword
      - name: setAdminPassword
        action: aws:runCommand
        inputs:
          DocumentName: AWS-RunPowerShellScript
          InstanceIds:
            - '{{ launchDC1.pdcInstanceId }}'
          Parameters:
            commands:
              - net user Administrator "sampleAdminPass123!"
        nextStep: createForest
      - name: createForest
        action: aws:runCommand
        inputs:
          DocumentName: AWS-RunPowerShellScript
          InstanceIds:
            - '{{ launchDC1.pdcInstanceId }}'
          Parameters:
            commands: |-
              $dsrmPass = 'sample123!' | ConvertTo-SecureString -asPlainText -Force
              try {
                  Install-ADDSForest -DomainName "sample.com" -DomainMode 6 -ForestMode 6 -InstallDNS -DatabasePath "D:\NTDS" -SysvolPath "D:\SYSVOL" -SafeModeAdministratorPassword $dsrmPass -Force
              }
              catch {
                  Write-Error $_
              }
              try {
                  Add-DnsServerForwarder -IPAddress "10.0.100.2"
              }
              catch {
                  Write-Error $_
              }
        nextStep: associateDhcpOptions
      - name: associateDhcpOptions
        action: aws:executeAwsApi
        onFailure: Abort
        inputs:
          Service: ec2
          Api: AssociateDhcpOptions
          DhcpOptionsId: '{{ createDhcpOptions.dhcpOptionsId }}'
          VpcId: '{{ createVpc.vpcId }}'
        nextStep: waitForADServices
      - name: waitForADServices
        action: aws:sleep
        inputs:
          Duration: PT1M
        nextStep: promoteADC
      - name: promoteADC
        action: aws:runCommand
        inputs:
          DocumentName: AWS-RunPowerShellScript
          InstanceIds:
            - '{{ launchDC2.adcInstanceId }}'
          Parameters:
            commands: |-
              ipconfig /renew
              $dsrmPass = 'sample123!' | ConvertTo-SecureString -asPlainText -Force
              $domAdminUser = "sample\Administrator"
              $domAdminPass = "sampleAdminPass123!" | ConvertTo-SecureString -asPlainText -Force
              $domAdminCred = New-Object System.Management.Automation.PSCredential($domAdminUser,$domAdminPass)
    
              try {
                  Install-ADDSDomainController -DomainName "sample.com" -InstallDNS -DatabasePath "D:\NTDS" -SysvolPath "D:\SYSVOL" -SafeModeAdministratorPassword $dsrmPass -Credential $domAdminCred -Force
              }
              catch {
                  Write-Error $_
              }
```

------
#### [ JSON ]

```
{
      "description": "Custom Automation Deployment Example",
      "schemaVersion": "0.3",
      "assumeRole": "{{ AutomationAssumeRole }}",
      "parameters": {
        "AutomationAssumeRole": {
          "type": "String",
          "description": "(Optional) 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 run this runbook.",
          "default": ""
        }
      },
      "mainSteps": [
        {
          "name": "getLatestWindowsAmi",
          "action": "aws:executeAwsApi",
          "onFailure": "Abort",
          "inputs": {
            "Service": "ssm",
            "Api": "GetParameter",
            "Name": "/aws/service/ami-windows-latest/Windows_Server-2016-English-Full-Base"
          },
          "outputs": [
            {
              "Name": "amiId",
              "Selector": "$.Parameter.Value",
              "Type": "String"
            }
          ],
          "nextStep": "createSSMInstanceRole"
        },
        {
          "name": "createSSMInstanceRole",
          "action": "aws:executeAwsApi",
          "onFailure": "Abort",
          "inputs": {
            "Service": "iam",
            "Api": "CreateRole",
            "AssumeRolePolicyDocument": "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\",\"Principal\":{\"Service\":[\"ec2.amazonaws.com\"]},\"Action\":[\"sts:AssumeRole\"]}]}",
            "RoleName": "sampleSSMInstanceRole"
          },
          "nextStep": "attachManagedSSMPolicy"
        },
        {
          "name": "attachManagedSSMPolicy",
          "action": "aws:executeAwsApi",
          "onFailure": "Abort",
          "inputs": {
            "Service": "iam",
            "Api": "AttachRolePolicy",
            "PolicyArn": "arn:aws:iam::aws:policy/service-role/AmazonSSMManagedInstanceCore",
            "RoleName": "sampleSSMInstanceRole"
          },
          "nextStep": "createSSMInstanceProfile"
        },
        {
          "name": "createSSMInstanceProfile",
          "action":"aws:executeAwsApi",
          "onFailure": "Abort",
          "inputs": {
            "Service": "iam",
            "Api": "CreateInstanceProfile",
            "InstanceProfileName": "sampleSSMInstanceRole"
          },
          "outputs": [
            {
              "Name": "instanceProfileArn",
              "Selector": "$.InstanceProfile.Arn",
              "Type": "String"
            }
          ],
          "nextStep": "addSSMInstanceRoleToProfile"
        },
        {
          "name": "addSSMInstanceRoleToProfile",
          "action": "aws:executeAwsApi",
          "onFailure": "Abort",
          "inputs": {
            "Service": "iam",
            "Api": "AddRoleToInstanceProfile",
            "InstanceProfileName": "sampleSSMInstanceRole",
            "RoleName": "sampleSSMInstanceRole"
          },
          "nextStep": "createVpc"
        },
        {
          "name": "createVpc",
          "action": "aws:executeAwsApi",
          "onFailure": "Abort",
          "inputs": {
            "Service": "ec2",
            "Api": "CreateVpc",
            "CidrBlock": "10.0.100.0/22"
          },
          "outputs": [
            {
              "Name": "vpcId",
              "Selector": "$.Vpc.VpcId",
              "Type": "String"
            }
          ],
          "nextStep": "getMainRtb"
        },
        {
          "name": "getMainRtb",
          "action": "aws:executeAwsApi",
          "onFailure": "Abort",
          "inputs": {
            "Service": "ec2",
            "Api": "DescribeRouteTables",
            "Filters": [
              {
                "Name": "vpc-id",
                "Values": ["{{ createVpc.vpcId }}"]
              }
            ]
          },
          "outputs": [
            {
              "Name": "mainRtbId",
              "Selector": "$.RouteTables[0].RouteTableId",
              "Type": "String"
            }
          ],
          "nextStep": "verifyMainRtb"
        },
        {
          "name": "verifyMainRtb",
          "action": "aws:assertAwsResourceProperty",
          "onFailure": "Abort",
          "inputs": {
            "Service": "ec2",
            "Api": "DescribeRouteTables",
            "RouteTableIds": ["{{ getMainRtb.mainRtbId }}"],
            "PropertySelector": "$.RouteTables[0].Associations[0].Main",
            "DesiredValues": ["True"]
          },
          "nextStep": "createPubSubnet"
        },
        {
          "name": "createPubSubnet",
          "action": "aws:executeAwsApi",
          "onFailure": "Abort",
          "inputs": {
            "Service": "ec2",
            "Api": "CreateSubnet",
            "CidrBlock": "10.0.103.0/24",
            "AvailabilityZone": "us-west-2c",
            "VpcId": "{{ createVpc.vpcId }}"
          },
          "outputs":[
            {
              "Name": "pubSubnetId",
              "Selector": "$.Subnet.SubnetId",
              "Type": "String"
            }
          ],
          "nextStep": "createPubRtb"
        },
        {
          "name": "createPubRtb",
          "action": "aws:executeAwsApi",
          "onFailure": "Abort",
          "inputs": {
            "Service": "ec2",
            "Api": "CreateRouteTable",
            "VpcId": "{{ createVpc.vpcId }}"
          },
          "outputs": [
            {
              "Name": "pubRtbId",
              "Selector": "$.RouteTable.RouteTableId",
              "Type": "String"
            }
          ],
          "nextStep": "createIgw"
        },
        {
          "name": "createIgw",
          "action": "aws:executeAwsApi",
          "onFailure": "Abort",
          "inputs": {
            "Service": "ec2",
            "Api": "CreateInternetGateway"
          },
          "outputs": [
            {
              "Name": "igwId",
              "Selector": "$.InternetGateway.InternetGatewayId",
              "Type": "String"
            }
          ],
          "nextStep": "attachIgw"
        },
        {
          "name": "attachIgw",
          "action": "aws:executeAwsApi",
          "onFailure": "Abort",
          "inputs": {
            "Service": "ec2",
            "Api": "AttachInternetGateway",
            "InternetGatewayId": "{{ createIgw.igwId }}",
            "VpcId": "{{ createVpc.vpcId }}"
          },
          "nextStep": "allocateEip"
        },
        {
          "name": "allocateEip",
          "action": "aws:executeAwsApi",
          "onFailure": "Abort",
          "inputs": {
            "Service": "ec2",
            "Api": "AllocateAddress",
            "Domain": "vpc"
          },
          "outputs": [
            {
              "Name": "eipAllocationId",
              "Selector": "$.AllocationId",
              "Type": "String"
            }
          ],
          "nextStep": "createNatGw"
        },
        {
          "name": "createNatGw",
          "action": "aws:executeAwsApi",
          "onFailure": "Abort",
          "inputs": {
            "Service": "ec2",
            "Api": "CreateNatGateway",
            "AllocationId": "{{ allocateEip.eipAllocationId }}",
            "SubnetId": "{{ createPubSubnet.pubSubnetId }}"
          },
          "outputs":[
            {
              "Name": "natGwId",
              "Selector": "$.NatGateway.NatGatewayId",
              "Type": "String"
            }
          ],
          "nextStep": "verifyNatGwAvailable"
        },
        {
          "name": "verifyNatGwAvailable",
          "action": "aws:waitForAwsResourceProperty",
          "timeoutSeconds": 150,
          "inputs": {
            "Service": "ec2",
            "Api": "DescribeNatGateways",
            "NatGatewayIds": [
              "{{ createNatGw.natGwId }}"
            ],
            "PropertySelector": "$.NatGateways[0].State",
            "DesiredValues": [
              "available"
            ]
          },
          "nextStep": "createNatRoute"
        },
        {
          "name": "createNatRoute",
          "action": "aws:executeAwsApi",
          "onFailure": "Abort",
          "inputs": {
            "Service": "ec2",
            "Api": "CreateRoute",
            "DestinationCidrBlock": "0.0.0.0/0",
            "NatGatewayId": "{{ createNatGw.natGwId }}",
            "RouteTableId": "{{ getMainRtb.mainRtbId }}"
          },
          "nextStep": "createPubRoute"
        },
        {
          "name": "createPubRoute",
          "action": "aws:executeAwsApi",
          "onFailure": "Abort",
          "inputs": {
            "Service": "ec2",
            "Api": "CreateRoute",
            "DestinationCidrBlock": "0.0.0.0/0",
            "GatewayId": "{{ createIgw.igwId }}",
            "RouteTableId": "{{ createPubRtb.pubRtbId }}"
          },
          "nextStep": "setPubSubAssoc"
        },
        {
          "name": "setPubSubAssoc",
          "action": "aws:executeAwsApi",
          "onFailure": "Abort",
          "inputs": {
            "Service": "ec2",
            "Api": "AssociateRouteTable",
            "RouteTableId": "{{ createPubRtb.pubRtbId }}",
            "SubnetId": "{{ createPubSubnet.pubSubnetId }}"
          }
        },
        {
          "name": "createDhcpOptions",
          "action": "aws:executeAwsApi",
          "onFailure": "Abort",
          "inputs": {
            "Service": "ec2",
            "Api": "CreateDhcpOptions",
            "DhcpConfigurations": [
              {
                "Key": "domain-name-servers",
                "Values": ["10.0.100.50,10.0.101.50"]
              },
              {
                "Key": "domain-name",
                "Values": ["sample.com"]
              }
            ]
          },
          "outputs": [
            {
              "Name": "dhcpOptionsId",
              "Selector": "$.DhcpOptions.DhcpOptionsId",
              "Type": "String"
            }
          ],
          "nextStep": "createDCSubnet1"
        },
        {
          "name": "createDCSubnet1",
          "action": "aws:executeAwsApi",
          "onFailure": "Abort",
          "inputs": {
            "Service": "ec2",
            "Api": "CreateSubnet",
            "CidrBlock": "10.0.100.0/24",
            "AvailabilityZone": "us-west-2a",
            "VpcId": "{{ createVpc.vpcId }}"
          },
          "outputs": [
            {
              "Name": "firstSubnetId",
              "Selector": "$.Subnet.SubnetId",
              "Type": "String"
            }
          ],
          "nextStep": "createDCSubnet2"
        },
        {
          "name": "createDCSubnet2",
          "action": "aws:executeAwsApi",
          "onFailure": "Abort",
          "inputs": {
            "Service": "ec2",
            "Api": "CreateSubnet",
            "CidrBlock": "10.0.101.0/24",
            "AvailabilityZone": "us-west-2b",
            "VpcId": "{{ createVpc.vpcId }}"
          },
          "outputs": [
            {
              "Name": "secondSubnetId",
              "Selector": "$.Subnet.SubnetId",
              "Type": "String"
            }
          ],
          "nextStep": "createDCSecGroup"
        },
        {
          "name": "createDCSecGroup",
          "action": "aws:executeAwsApi",
          "onFailure": "Abort",
          "inputs": {
            "Service": "ec2",
            "Api": "CreateSecurityGroup",
            "GroupName": "SampleDCSecGroup",
            "Description": "Security Group for Example Domain Controllers",
            "VpcId": "{{ createVpc.vpcId }}"
          },
          "outputs": [
            {
              "Name": "dcSecGroupId",
              "Selector": "$.GroupId",
              "Type": "String"
            }
          ],
          "nextStep": "authIngressDCTraffic"
        },
        {
          "name": "authIngressDCTraffic",
          "action": "aws:executeAwsApi",
          "onFailure": "Abort",
          "inputs": {
            "Service": "ec2",
            "Api": "AuthorizeSecurityGroupIngress",
            "GroupId": "{{ createDCSecGroup.dcSecGroupId }}",
            "IpPermissions": [
              {
                "FromPort": -1,
                "IpProtocol": "-1",
                "IpRanges": [
                  {
                    "CidrIp": "0.0.0.0/0",
                    "Description": "Allow all traffic between Domain Controllers"
                  }
                ]
              }
            ]
          },
          "nextStep": "verifyInstanceProfile"
        },
        {
          "name": "verifyInstanceProfile",
          "action": "aws:waitForAwsResourceProperty",
          "maxAttempts": 5,
          "onFailure": "Abort",
          "inputs": {
            "Service": "iam",
            "Api": "ListInstanceProfilesForRole",
            "RoleName": "sampleSSMInstanceRole",
            "PropertySelector": "$.InstanceProfiles[0].Arn",
            "DesiredValues": [
              "{{ createSSMInstanceProfile.instanceProfileArn }}"
            ]
          },
          "nextStep": "iamEventualConsistency"
        },
        {
          "name": "iamEventualConsistency",
          "action": "aws:sleep",
          "inputs": {
            "Duration": "PT2M"
          },
          "nextStep": "launchDC1"
        },
        {
          "name": "launchDC1",
          "action": "aws:executeAwsApi",
          "onFailure": "Abort",
          "inputs": {
            "Service": "ec2",
            "Api": "RunInstances",
            "BlockDeviceMappings": [
              {
                "DeviceName": "/dev/sda1",
                "Ebs": {
                  "DeleteOnTermination": true,
                  "VolumeSize": 50,
                  "VolumeType": "gp2"
                }
              },
              {
                "DeviceName": "xvdf",
                "Ebs": {
                  "DeleteOnTermination": true,
                  "VolumeSize": 100,
                  "VolumeType": "gp2"
                }
              }
            ],
            "IamInstanceProfile": {
              "Arn": "{{ createSSMInstanceProfile.instanceProfileArn }}"
            },
            "ImageId": "{{ getLatestWindowsAmi.amiId }}",
            "InstanceType": "t2.micro",
            "MaxCount": 1,
            "MinCount": 1,
            "PrivateIpAddress": "10.0.100.50",
            "SecurityGroupIds": [
              "{{ createDCSecGroup.dcSecGroupId }}"
            ],
            "SubnetId": "{{ createDCSubnet1.firstSubnetId }}",
            "TagSpecifications": [
              {
                "ResourceType": "instance",
                "Tags": [
                  {
                    "Key": "Name",
                    "Value": "SampleDC1"
                  }
                ]
              }
            ]
          },
          "outputs": [
            {
              "Name": "pdcInstanceId",
              "Selector": "$.Instances[0].InstanceId",
              "Type": "String"
            }
          ],
          "nextStep": "launchDC2"
        },
        {
          "name": "launchDC2",
          "action": "aws:executeAwsApi",
          "onFailure": "Abort",
          "inputs": {
            "Service": "ec2",
            "Api": "RunInstances",
            "BlockDeviceMappings": [
              {
                "DeviceName": "/dev/sda1",
                "Ebs": {
                  "DeleteOnTermination": true,
                  "VolumeSize": 50,
                  "VolumeType": "gp2"
                }
              },
              {
                "DeviceName": "xvdf",
                "Ebs": {
                  "DeleteOnTermination": true,
                  "VolumeSize": 100,
                  "VolumeType": "gp2"
                }
              }
            ],
            "IamInstanceProfile": {
              "Arn": "{{ createSSMInstanceProfile.instanceProfileArn }}"
            },
            "ImageId": "{{ getLatestWindowsAmi.amiId }}",
            "InstanceType": "t2.micro",
            "MaxCount": 1,
            "MinCount": 1,
            "PrivateIpAddress": "10.0.101.50",
            "SecurityGroupIds": [
              "{{ createDCSecGroup.dcSecGroupId }}"
            ],
            "SubnetId": "{{ createDCSubnet2.secondSubnetId }}",
            "TagSpecifications": [
              {
                "ResourceType": "instance",
                "Tags": [
                  {
                    "Key": "Name",
                    "Value": "SampleDC2"
                  }
                ]
              }
            ]
          },
          "outputs": [
            {
              "Name": "adcInstanceId",
              "Selector": "$.Instances[0].InstanceId",
              "Type": "String"
            }
          ],
          "nextStep": "verifyDCInstanceState"
        },
        {
          "name": "verifyDCInstanceState",
          "action": "aws:waitForAwsResourceProperty",
          "inputs": {
            "Service": "ec2",
            "Api": "DescribeInstanceStatus",
            "IncludeAllInstances": true,
            "InstanceIds": [
              "{{ launchDC1.pdcInstanceId }}",
              "{{ launchDC2.adcInstanceId }}"
            ],
            "PropertySelector": "$.InstanceStatuses[0].InstanceState.Name",
            "DesiredValues": [
              "running"
            ]
          },
          "nextStep": "verifyInstancesOnlineSSM"
        },
        {
          "name": "verifyInstancesOnlineSSM",
          "action": "aws:waitForAwsResourceProperty",
          "timeoutSeconds": 600,
          "inputs": {
            "Service": "ssm",
            "Api": "DescribeInstanceInformation",
            "InstanceInformationFilterList": [
              {
                "key": "InstanceIds",
                "valueSet": [
                  "{{ launchDC1.pdcInstanceId }}",
                  "{{ launchDC2.adcInstanceId }}"
                ]
              }
            ],
            "PropertySelector": "$.InstanceInformationList[0].PingStatus",
            "DesiredValues": [
              "Online"
            ]
          },
          "nextStep": "installADRoles"
        },
        {
          "name": "installADRoles",
          "action": "aws:runCommand",
          "inputs": {
            "DocumentName": "AWS-RunPowerShellScript",
            "InstanceIds": [
              "{{ launchDC1.pdcInstanceId }}",
              "{{ launchDC2.adcInstanceId }}"
            ],
            "Parameters": {
              "commands": [
                "try {",
                "  Install-WindowsFeature -Name AD-Domain-Services -IncludeManagementTools",
                "}",
                "catch {",
                "  Write-Error \"Failed to install ADDS Role.\"",
                "}"
              ]
            }
          },
          "nextStep": "setAdminPassword"
        },
        {
          "name": "setAdminPassword",
          "action": "aws:runCommand",
          "inputs": {
            "DocumentName": "AWS-RunPowerShellScript",
            "InstanceIds": [
              "{{ launchDC1.pdcInstanceId }}"
            ],
            "Parameters": {
              "commands": [
                "net user Administrator \"sampleAdminPass123!\""
              ]
            }
          },
          "nextStep": "createForest"
        },
        {
          "name": "createForest",
          "action": "aws:runCommand",
          "inputs": {
            "DocumentName": "AWS-RunPowerShellScript",
            "InstanceIds": [
              "{{ launchDC1.pdcInstanceId }}"
            ],
            "Parameters": {
              "commands": [
                "$dsrmPass = 'sample123!' | ConvertTo-SecureString -asPlainText -Force",
                "try {",
                "   Install-ADDSForest -DomainName \"sample.com\" -DomainMode 6 -ForestMode 6 -InstallDNS -DatabasePath \"D:\\NTDS\" -SysvolPath \"D:\\SYSVOL\" -SafeModeAdministratorPassword $dsrmPass -Force",
                "}",
                "catch {",
                "   Write-Error $_",
                "}",
                "try {",
                "   Add-DnsServerForwarder -IPAddress \"10.0.100.2\"",
                "}",
                "catch {",
                "   Write-Error $_",
                "}"
              ]
            }
          },
          "nextStep": "associateDhcpOptions"
        },
        {
          "name": "associateDhcpOptions",
          "action": "aws:executeAwsApi",
          "onFailure": "Abort",
          "inputs": {
            "Service": "ec2",
            "Api": "AssociateDhcpOptions",
            "DhcpOptionsId": "{{ createDhcpOptions.dhcpOptionsId }}",
            "VpcId": "{{ createVpc.vpcId }}"
          },
          "nextStep": "waitForADServices"
        },
        {
          "name": "waitForADServices",
          "action": "aws:sleep",
          "inputs": {
            "Duration": "PT1M"
          },
          "nextStep": "promoteADC"
        },
        {
          "name": "promoteADC",
          "action": "aws:runCommand",
          "inputs": {
            "DocumentName": "AWS-RunPowerShellScript",
            "InstanceIds": [
              "{{ launchDC2.adcInstanceId }}"
            ],
            "Parameters": {
              "commands": [
                "ipconfig /renew",
                "$dsrmPass = 'sample123!' | ConvertTo-SecureString -asPlainText -Force",
                "$domAdminUser = \"sample\\Administrator\"",
                "$domAdminPass = \"sampleAdminPass123!\" | ConvertTo-SecureString -asPlainText -Force",
                "$domAdminCred = New-Object System.Management.Automation.PSCredential($domAdminUser,$domAdminPass)",
                "try {",
                "   Install-ADDSDomainController -DomainName \"sample.com\" -InstallDNS -DatabasePath \"D:\\NTDS\" -SysvolPath \"D:\\SYSVOL\" -SafeModeAdministratorPassword $dsrmPass -Credential $domAdminCred -Force",
                "}",
                "catch {",
                "   Write-Error $_",
                "}"
              ]
            }
          }
        }
      ]
    }
```

------

# 최신 스냅샷에서 루트 볼륨 복원
<a name="automation-document-instance-recovery-example"></a>

루트 볼륨의 운영 체제는 여러 가지 이유로 손상될 수 있습니다. 예를 들어 패치 작업 후 손상된 커널 또는 레지스트리로 인해 인스턴스가 성공적으로 부팅되지 않을 수 있습니다. 패치 작업 전에 생성된 최신 스냅샷에서 루트 볼륨을 복원하는 것과 같은 일반적인 문제 해결 태스크를 자동화하면 가동 중지 시간을 줄이고 문제 해결 작업을 신속하게 수행할 수 있습니다. AWS Systems Manager 이러한 경우 Automation 작업이 도움이 될 수 있습니다. Automation은 AWS Systems Manager의 도구입니다.

다음 예제 AWS Systems Manager 런북은 다음과 같은 작업을 수행합니다.
+ `aws:executeAwsApi` 자동화 작업을 사용하여 인스턴스의 루트 볼륨에서 세부 정보를 검색합니다.
+ `aws:executeScript` 자동화 작업을 사용하여 루트 볼륨의 최신 스냅샷을 검색합니다.
+ 루트 볼륨에 대한 스냅샷이 발견되면 `aws:branch` 자동화 작업을 사용하여 자동화를 계속합니다.

------
#### [ YAML ]

```
    ---
    description: Custom Automation Troubleshooting Example
    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 use this runbook."
        default: ''
      InstanceId:
          type: String
          description: "(Required) The Instance Id whose root EBS volume you want to restore the latest Snapshot."
          default: ''
    mainSteps:
    - name: getInstanceDetails
      action: aws:executeAwsApi
      onFailure: Abort
      inputs:
        Service: ec2
        Api: DescribeInstances
        InstanceIds:
        - "{{ InstanceId }}"
      outputs:
        - Name: availabilityZone
          Selector: "$.Reservations[0].Instances[0].Placement.AvailabilityZone"
          Type: String
        - Name: rootDeviceName
          Selector: "$.Reservations[0].Instances[0].RootDeviceName"
          Type: String
      nextStep: getRootVolumeId
    - name: getRootVolumeId
      action: aws:executeAwsApi
      onFailure: Abort
      inputs:
        Service: ec2
        Api: DescribeVolumes
        Filters:
        -  Name: attachment.device
           Values: ["{{ getInstanceDetails.rootDeviceName }}"]
        -  Name: attachment.instance-id
           Values: ["{{ InstanceId }}"]
      outputs:
        - Name: rootVolumeId
          Selector: "$.Volumes[0].VolumeId"
          Type: String
      nextStep: getSnapshotsByStartTime
    - name: getSnapshotsByStartTime
      action: aws:executeScript
      timeoutSeconds: 45
      onFailure: Abort
      inputs:
        Runtime: python3.11
        Handler: getSnapshotsByStartTime
        InputPayload:
          rootVolumeId : "{{ getRootVolumeId.rootVolumeId }}"
        Script: |-
          def getSnapshotsByStartTime(events,context):
            import boto3
    
            #Initialize client
            ec2 = boto3.client('ec2')
            rootVolumeId = events['rootVolumeId']
            snapshotsQuery = ec2.describe_snapshots(
              Filters=[
                {
                  "Name": "volume-id",
                  "Values": [rootVolumeId]
                }
              ]
            )
            if not snapshotsQuery['Snapshots']:
              noSnapshotFoundString = "NoSnapshotFound"
              return { 'noSnapshotFound' : noSnapshotFoundString }
            else:
              jsonSnapshots = snapshotsQuery['Snapshots']
              sortedSnapshots = sorted(jsonSnapshots, key=lambda k: k['StartTime'], reverse=True)
              latestSortedSnapshotId = sortedSnapshots[0]['SnapshotId']
              return { 'latestSnapshotId' : latestSortedSnapshotId }
      outputs:
      - Name: Payload
        Selector: $.Payload
        Type: StringMap
      - Name: latestSnapshotId
        Selector: $.Payload.latestSnapshotId
        Type: String
      - Name: noSnapshotFound
        Selector: $.Payload.noSnapshotFound
        Type: String 
      nextStep: branchFromResults
    - name: branchFromResults
      action: aws:branch
      onFailure: Abort
      inputs:
        Choices:
        - NextStep: createNewRootVolumeFromSnapshot
          Not:
            Variable: "{{ getSnapshotsByStartTime.noSnapshotFound }}"
            StringEquals: "NoSnapshotFound"
      isEnd: true
    - name: createNewRootVolumeFromSnapshot
      action: aws:executeAwsApi
      onFailure: Abort
      inputs:
        Service: ec2
        Api: CreateVolume
        AvailabilityZone: "{{ getInstanceDetails.availabilityZone }}"
        SnapshotId: "{{ getSnapshotsByStartTime.latestSnapshotId }}"
      outputs:
        - Name: newRootVolumeId
          Selector: "$.VolumeId"
          Type: String
      nextStep: stopInstance
    - name: stopInstance
      action: aws:executeAwsApi
      onFailure: Abort
      inputs:
        Service: ec2
        Api: StopInstances
        InstanceIds:
        - "{{ InstanceId }}"
      nextStep: verifyVolumeAvailability
    - name: verifyVolumeAvailability
      action: aws:waitForAwsResourceProperty
      timeoutSeconds: 120
      inputs:
        Service: ec2
        Api: DescribeVolumes
        VolumeIds:
        - "{{ createNewRootVolumeFromSnapshot.newRootVolumeId }}"
        PropertySelector: "$.Volumes[0].State"
        DesiredValues:
        - "available"
      nextStep: verifyInstanceStopped
    - name: verifyInstanceStopped
      action: aws:waitForAwsResourceProperty
      timeoutSeconds: 120
      inputs:
        Service: ec2
        Api: DescribeInstances
        InstanceIds:
        - "{{ InstanceId }}"
        PropertySelector: "$.Reservations[0].Instances[0].State.Name"
        DesiredValues:
        - "stopped"
      nextStep: detachRootVolume
    - name: detachRootVolume
      action: aws:executeAwsApi
      onFailure: Abort
      inputs:
        Service: ec2
        Api: DetachVolume
        VolumeId: "{{ getRootVolumeId.rootVolumeId }}"
      nextStep: verifyRootVolumeDetached
    - name: verifyRootVolumeDetached
      action: aws:waitForAwsResourceProperty
      timeoutSeconds: 30
      inputs:
        Service: ec2
        Api: DescribeVolumes
        VolumeIds:
        - "{{ getRootVolumeId.rootVolumeId }}"
        PropertySelector: "$.Volumes[0].State"
        DesiredValues:
        - "available"
      nextStep: attachNewRootVolume
    - name: attachNewRootVolume
      action: aws:executeAwsApi
      onFailure: Abort
      inputs:
        Service: ec2
        Api: AttachVolume
        Device: "{{ getInstanceDetails.rootDeviceName }}"
        InstanceId: "{{ InstanceId }}"
        VolumeId: "{{ createNewRootVolumeFromSnapshot.newRootVolumeId }}"
      nextStep: verifyNewRootVolumeAttached
    - name: verifyNewRootVolumeAttached
      action: aws:waitForAwsResourceProperty
      timeoutSeconds: 30
      inputs:
        Service: ec2
        Api: DescribeVolumes
        VolumeIds:
        - "{{ createNewRootVolumeFromSnapshot.newRootVolumeId }}"
        PropertySelector: "$.Volumes[0].Attachments[0].State"
        DesiredValues:
        - "attached"
      nextStep: startInstance
    - name: startInstance
      action: aws:executeAwsApi
      onFailure: Abort
      inputs:
        Service: ec2
        Api: StartInstances
        InstanceIds:
        - "{{ InstanceId }}"
```

------
#### [ JSON ]

```
    {
       "description": "Custom Automation Troubleshooting Example",
       "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 run this runbook.",
             "default": ""
          },
          "InstanceId": {
             "type": "String",
             "description": "(Required) The Instance Id whose root EBS volume you want to restore the latest Snapshot.",
             "default": ""
          }
       },
       "mainSteps": [
          {
             "name": "getInstanceDetails",
             "action": "aws:executeAwsApi",
             "onFailure": "Abort",
             "inputs": {
                "Service": "ec2",
                "Api": "DescribeInstances",
                "InstanceIds": [
                   "{{ InstanceId }}"
                ]
             },
             "outputs": [
                {
                   "Name": "availabilityZone",
                   "Selector": "$.Reservations[0].Instances[0].Placement.AvailabilityZone",
                   "Type": "String"
                },
                {
                   "Name": "rootDeviceName",
                   "Selector": "$.Reservations[0].Instances[0].RootDeviceName",
                   "Type": "String"
                }
             ],
             "nextStep": "getRootVolumeId"
          },
          {
             "name": "getRootVolumeId",
             "action": "aws:executeAwsApi",
             "onFailure": "Abort",
             "inputs": {
                "Service": "ec2",
                "Api": "DescribeVolumes",
                "Filters": [
                   {
                      "Name": "attachment.device",
                      "Values": [
                         "{{ getInstanceDetails.rootDeviceName }}"
                      ]
                   },
                   {
                      "Name": "attachment.instance-id",
                      "Values": [
                         "{{ InstanceId }}"
                      ]
                   }
                ]
             },
             "outputs": [
                {
                   "Name": "rootVolumeId",
                   "Selector": "$.Volumes[0].VolumeId",
                   "Type": "String"
                }
             ],
             "nextStep": "getSnapshotsByStartTime"
          },
          {
             "name": "getSnapshotsByStartTime",
             "action": "aws:executeScript",
             "timeoutSeconds": 45,
             "onFailure": "Continue",
             "inputs": {
                "Runtime": "python3.11",
                "Handler": "getSnapshotsByStartTime",
                "InputPayload": {
                   "rootVolumeId": "{{ getRootVolumeId.rootVolumeId }}"
                },
                "Attachment": "getSnapshotsByStartTime.py"
             },
             "outputs": [
                {
                   "Name": "Payload",
                   "Selector": "$.Payload",
                   "Type": "StringMap"
                },
                {
                   "Name": "latestSnapshotId",
                   "Selector": "$.Payload.latestSnapshotId",
                   "Type": "String"
                },
                {
                   "Name": "noSnapshotFound",
                   "Selector": "$.Payload.noSnapshotFound",
                   "Type": "String"
                }
             ],
             "nextStep": "branchFromResults"
          },
          {
             "name": "branchFromResults",
             "action": "aws:branch",
             "onFailure": "Abort",
             "inputs": {
                "Choices": [
                   {
                      "NextStep": "createNewRootVolumeFromSnapshot",
                      "Not": {
                         "Variable": "{{ getSnapshotsByStartTime.noSnapshotFound }}",
                         "StringEquals": "NoSnapshotFound"
                      }
                   }
                ]
             },
             "isEnd": true
          },
          {
             "name": "createNewRootVolumeFromSnapshot",
             "action": "aws:executeAwsApi",
             "onFailure": "Abort",
             "inputs": {
                "Service": "ec2",
                "Api": "CreateVolume",
                "AvailabilityZone": "{{ getInstanceDetails.availabilityZone }}",
                "SnapshotId": "{{ getSnapshotsByStartTime.latestSnapshotId }}"
             },
             "outputs": [
                {
                   "Name": "newRootVolumeId",
                   "Selector": "$.VolumeId",
                   "Type": "String"
                }
             ],
             "nextStep": "stopInstance"
          },
          {
             "name": "stopInstance",
             "action": "aws:executeAwsApi",
             "onFailure": "Abort",
             "inputs": {
                "Service": "ec2",
                "Api": "StopInstances",
                "InstanceIds": [
                   "{{ InstanceId }}"
                ]
             },
             "nextStep": "verifyVolumeAvailability"
          },
          {
             "name": "verifyVolumeAvailability",
             "action": "aws:waitForAwsResourceProperty",
             "timeoutSeconds": 120,
             "inputs": {
                "Service": "ec2",
                "Api": "DescribeVolumes",
                "VolumeIds": [
                   "{{ createNewRootVolumeFromSnapshot.newRootVolumeId }}"
                ],
                "PropertySelector": "$.Volumes[0].State",
                "DesiredValues": [
                   "available"
                ]
             },
             "nextStep": "verifyInstanceStopped"
          },
          {
             "name": "verifyInstanceStopped",
             "action": "aws:waitForAwsResourceProperty",
             "timeoutSeconds": 120,
             "inputs": {
                "Service": "ec2",
                "Api": "DescribeInstances",
                "InstanceIds": [
                   "{{ InstanceId }}"
                ],
                "PropertySelector": "$.Reservations[0].Instances[0].State.Name",
                "DesiredValues": [
                   "stopped"
                ]
             },
             "nextStep": "detachRootVolume"
          },
          {
             "name": "detachRootVolume",
             "action": "aws:executeAwsApi",
             "onFailure": "Abort",
             "inputs": {
                "Service": "ec2",
                "Api": "DetachVolume",
                "VolumeId": "{{ getRootVolumeId.rootVolumeId }}"
             },
             "nextStep": "verifyRootVolumeDetached"
          },
          {
             "name": "verifyRootVolumeDetached",
             "action": "aws:waitForAwsResourceProperty",
             "timeoutSeconds": 30,
             "inputs": {
                "Service": "ec2",
                "Api": "DescribeVolumes",
                "VolumeIds": [
                   "{{ getRootVolumeId.rootVolumeId }}"
                ],
                "PropertySelector": "$.Volumes[0].State",
                "DesiredValues": [
                   "available"
                ]
             },
             "nextStep": "attachNewRootVolume"
          },
          {
             "name": "attachNewRootVolume",
             "action": "aws:executeAwsApi",
             "onFailure": "Abort",
             "inputs": {
                "Service": "ec2",
                "Api": "AttachVolume",
                "Device": "{{ getInstanceDetails.rootDeviceName }}",
                "InstanceId": "{{ InstanceId }}",
                "VolumeId": "{{ createNewRootVolumeFromSnapshot.newRootVolumeId }}"
             },
             "nextStep": "verifyNewRootVolumeAttached"
          },
          {
             "name": "verifyNewRootVolumeAttached",
             "action": "aws:waitForAwsResourceProperty",
             "timeoutSeconds": 30,
             "inputs": {
                "Service": "ec2",
                "Api": "DescribeVolumes",
                "VolumeIds": [
                   "{{ createNewRootVolumeFromSnapshot.newRootVolumeId }}"
                ],
                "PropertySelector": "$.Volumes[0].Attachments[0].State",
                "DesiredValues": [
                   "attached"
                ]
             },
             "nextStep": "startInstance"
          },
          {
             "name": "startInstance",
             "action": "aws:executeAwsApi",
             "onFailure": "Abort",
             "inputs": {
                "Service": "ec2",
                "Api": "StartInstances",
                "InstanceIds": [
                   "{{ InstanceId }}"
                ]
             }
          }
       ],
       "files": {
            "getSnapshotsByStartTime.py": {
                "checksums": {
                    "sha256": "sampleETagValue"
                }
            }
        }
    }
```

------

# AMI 및 크로스 리전 복사본 생성
<a name="automation-document-backup-maintenance-example"></a>

인스턴스의 Amazon Machine Image(AMI) 생성은 백업 및 복구에 사용되는 일반적인 프로세스입니다. 재해 복구 아키텍처의 일부로 AMI를 다른 AWS 리전에 복사하도록 선택할 수도 있습니다. 일반적인 유지 관리 태스크를 자동화하면 문제에 장애 조치가 필요한 경우 가동 중지 시간을 줄일 수 있습니다. AWS Systems Manager 이러한 경우 Automation 작업이 도움이 될 수 있습니다. Automation은 AWS Systems Manager의 도구입니다.

다음 예제 AWS Systems Manager 런북은 다음과 같은 작업을 수행합니다.
+ `aws:executeAwsApi` 자동화 작업을 사용하여 AMI를 생성합니다.
+ `aws:waitForAwsResourceProperty` 자동화 작업을 사용하여 AMI의 가용성을 확인합니다.
+ `aws:executeScript` 자동화 작업을 사용하여 AMI를 대상 리전으로 복사합니다.

------
#### [ YAML ]

```
    ---
    description: Custom Automation Backup and Recovery Example
    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 use this runbook."
        default: ''
      InstanceId:
        type: String
        description: "(Required) The ID of the EC2 instance."
        default: ''
    mainSteps:
    - name: createImage
      action: aws:executeAwsApi
      onFailure: Abort
      inputs:
        Service: ec2
        Api: CreateImage
        InstanceId: "{{ InstanceId }}"
        Name: "Automation Image for {{ InstanceId }}"
        NoReboot: false
      outputs:
        - Name: newImageId
          Selector: "$.ImageId"
          Type: String
      nextStep: verifyImageAvailability
    - name: verifyImageAvailability
      action: aws:waitForAwsResourceProperty
      timeoutSeconds: 600
      inputs:
        Service: ec2
        Api: DescribeImages
        ImageIds:
        - "{{ createImage.newImageId }}"
        PropertySelector: "$.Images[0].State"
        DesiredValues:
        - available
      nextStep: copyImage
    - name: copyImage
      action: aws:executeScript
      timeoutSeconds: 45
      onFailure: Abort
      inputs:
        Runtime: python3.11
        Handler: crossRegionImageCopy
        InputPayload:
          newImageId : "{{ createImage.newImageId }}"
        Script: |-
          def crossRegionImageCopy(events,context):
            import boto3
    
            #Initialize client
            ec2 = boto3.client('ec2', region_name='us-east-1')
            newImageId = events['newImageId']
    
            ec2.copy_image(
              Name='DR Copy for ' + newImageId,
              SourceImageId=newImageId,
              SourceRegion='us-west-2'
            )
```

------
#### [ JSON ]

```
    {
       "description": "Custom Automation Backup and Recovery Example",
       "schemaVersion": "0.3",
       "assumeRole": "{{ AutomationAssumeRole }}",
       "parameters": {
          "AutomationAssumeRole": {
             "type": "String",
             "description": "(Required) The ARN of the role that allows Automation to perform\nthe actions on your behalf. If no role is specified, Systems Manager Automation\nuses your IAM permissions to run this runbook.",
             "default": ""
          },
          "InstanceId": {
             "type": "String",
             "description": "(Required) The ID of the EC2 instance.",
             "default": ""
          }
       },
       "mainSteps": [
          {
             "name": "createImage",
             "action": "aws:executeAwsApi",
             "onFailure": "Abort",
             "inputs": {
                "Service": "ec2",
                "Api": "CreateImage",
                "InstanceId": "{{ InstanceId }}",
                "Name": "Automation Image for {{ InstanceId }}",
                "NoReboot": false
             },
             "outputs": [
                {
                   "Name": "newImageId",
                   "Selector": "$.ImageId",
                   "Type": "String"
                }
             ],
             "nextStep": "verifyImageAvailability"
          },
          {
             "name": "verifyImageAvailability",
             "action": "aws:waitForAwsResourceProperty",
             "timeoutSeconds": 600,
             "inputs": {
                "Service": "ec2",
                "Api": "DescribeImages",
                "ImageIds": [
                   "{{ createImage.newImageId }}"
                ],
                "PropertySelector": "$.Images[0].State",
                "DesiredValues": [
                   "available"
                ]
             },
             "nextStep": "copyImage"
          },
          {
             "name": "copyImage",
             "action": "aws:executeScript",
             "timeoutSeconds": 45,
             "onFailure": "Abort",
             "inputs": {
                "Runtime": "python3.11",
                "Handler": "crossRegionImageCopy",
                "InputPayload": {
                   "newImageId": "{{ createImage.newImageId }}"
                },
                "Attachment": "crossRegionImageCopy.py"
             }
          }
       ],
       "files": {
            "crossRegionImageCopy.py": {
                "checksums": {
                    "sha256": "sampleETagValue"
                }
            }
        }
    }
```

------

# AWS 리소스를 채우는 입력 파라미터 생성
<a name="populating-input-parameters"></a>

Systems Manager의 도구인 Automation은 입력 파라미터에 대해 정의한 리소스 타입과 일치하는 AWS Management Console의 AWS 리소스를 채웁니다. AWS 계정의 리소스 유형과 일치하는 리소스가 드롭다운 목록에 표시되어 선택할 수 있습니다. Amazon Elastic Compute Cloud(Amazon EC2) 인스턴스, Amazon Simple Storage Service(Amazon S3) 버킷, AWS Identity and Access Management(IAM) 역할에 대한 입력 파라미터 유형을 정의할 수 있습니다. 지원되는 형식 정의와 일치하는 리소스를 찾는 데 사용되는 정규 표현식은 다음과 같습니다.
+ `AWS::EC2::Instance::Id` - `^m?i-([a-z0-9]{8}|[a-z0-9]{17})$`
+ `List<AWS::EC2::Instance::Id>` - `^m?i-([a-z0-9]{8}|[a-z0-9]{17})$`
+ `AWS::S3::Bucket::Name` - `^[0-9a-z][a-z0-9\\-\\.]{3,63}$`
+ `List<AWS::S3::Bucket::Name>` - `^[0-9a-z][a-z0-9\\-\\.]{3,63}$`
+ `AWS::IAM::Role::Arn` - `^arn:(aws|aws-cn|aws-us-gov|aws-iso|aws-iso-b):iam::[0-9]{12}:role/.*$`
+ `List<AWS::IAM::Role::Arn>` - `^arn:(aws|aws-cn|aws-us-gov|aws-iso|aws-iso-b):iam::[0-9]{12}:role/.*$`

다음은 실행서 콘텐츠에 정의된 입력 파라미터 유형의 예제입니다.

------
#### [ YAML ]

```
description: Enables encryption on an Amazon S3 bucket
schemaVersion: '0.3'
assumeRole: '{{ AutomationAssumeRole }}'
parameters:
  BucketName:
    type: 'AWS::S3::Bucket::Name'
    description: (Required) The name of the Amazon S3 bucket you want to encrypt.
  SSEAlgorithm:
    type: String
    description: (Optional) The server-side encryption algorithm to use for the default encryption.
    default: AES256
  AutomationAssumeRole:
    type: 'AWS::IAM::Role::Arn'
    description: (Optional) The Amazon Resource Name (ARN) of the role that allows Automation to perform the actions on your behalf.
    default: ''
mainSteps:
  - name: enableBucketEncryption
    action: 'aws:executeAwsApi'
    inputs:
      Service: s3
      Api: PutBucketEncryption
      Bucket: '{{BucketName}}'
      ServerSideEncryptionConfiguration:
        Rules:
          - ApplyServerSideEncryptionByDefault:
              SSEAlgorithm: '{{SSEAlgorithm}}'
    isEnd: true
```

------
#### [ JSON ]

```
{
   "description": "Enables encryption on an Amazon S3 bucket",
   "schemaVersion": "0.3",
   "assumeRole": "{{ AutomationAssumeRole }}",
   "parameters": {
      "BucketName": {
         "type": "AWS::S3::Bucket::Name",
         "description": "(Required) The name of the Amazon S3 bucket you want to encrypt."
      },
      "SSEAlgorithm": {
         "type": "String",
         "description": "(Optional) The server-side encryption algorithm to use for the default encryption.",
         "default": "AES256"
      },
      "AutomationAssumeRole": {
         "type": "AWS::IAM::Role::Arn",
         "description": "(Optional) The Amazon Resource Name (ARN) of the role that allows Automation to perform the actions on your behalf.",
         "default": ""
      }
   },
   "mainSteps": [
      {
         "name": "enableBucketEncryption",
         "action": "aws:executeAwsApi",
         "inputs": {
            "Service": "s3",
            "Api": "PutBucketEncryption",
            "Bucket": "{{BucketName}}",
            "ServerSideEncryptionConfiguration": {
               "Rules": [
                  {
                     "ApplyServerSideEncryptionByDefault": {
                        "SSEAlgorithm": "{{SSEAlgorithm}}"
                     }
                  }
               ]
            }
         },
         "isEnd": true
      }
   ]
}
```

------

# 문서 빌더를 사용하여 런북 생성
<a name="automation-document-builder"></a>

AWS Systems Manager 퍼블릭 실행서가 AWS 리소스에서 수행하려는 모든 작업을 지원하지 않는 경우 자체 실행서를 생성할 수 있습니다. 사용자 정의 실행서를 생성하려면 적절한 자동화 작업을 사용하여 로컬 YAML 또는 JSON 형식 파일을 수동으로 생성할 수 있습니다. 또는 Systems Manager Automation 콘솔에서 문서 빌더를 사용하여 사용자 지정 런북을 빌드할 수도 있습니다.

문서 빌더를 사용하면 사용자 지정 런북에 자동화 작업을 추가하고 JSON 또는 YAML 구문을 사용하지 않고도 필요한 파라미터를 제공할 수 있습니다. 단계를 추가하고 실행서를 생성한 후에는 추가한 작업이 Systems Manager에서 자동화를 실행하는 데 사용할 수 있는 YAML 형식으로 변환됩니다.

실행서에서는 Markdown을 사용할 수 있습니다. 마크업 언어인 Markdown을 사용하면 실행서와 실행서 내의 개별 단계에 wiki 스타일의 설명을 추가할 수 있습니다. Markdown 사용에 대한 자세한 내용은 [AWS에서 Markdown 사용](https://docs.aws.amazon.com/general/latest/gr/aws-markdown.html)을 참조하세요.

## 문서 빌더를 사용하여 런북 생성
<a name="create-runbook"></a>

**시작하기 전 준비 사항**  
런북 내에서 사용할 수 있는 다양한 작업에 대해 읽어보는 것이 좋습니다. 자세한 내용은 [Systems Manager Automation 작업 참조](automation-actions.md) 섹션을 참조하세요.

**문서 빌더를 사용하여 실행서를 생성하려면**

1. AWS Systems Manager 콘솔([https://console.aws.amazon.com/systems-manager/](https://console.aws.amazon.com/systems-manager/))을 엽니다.

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

1. **Create automation(자동화 생성)**을 선택합니다.

1. [**이름(Name)**]에 실행서를 설명하는 이름을 입력합니다.

1. [**문서 설명(Document description)**]에 실행서에 대한 Markdown 스타일 설명을 입력합니다. 실행서 사용 지침, 번호가 매겨진 단계 또는 기타 유형의 정보를 사용하여 실행서를 설명할 수 있도록 지침을 제공할 수 있습니다. 내용 서식 지정에 대한 자세한 내용은 기본 텍스트를 참조하세요.
**작은 정보**  
**Hide preview(미리보기 숨기기)** 및 **Show preview(미리보기 표시)** 사이를 전환하여 작성 시 설명 내용이 어떤 형태인지 확인합니다.

1. (선택 사항) **Assume role(역할 수임)**에 사용자를 대신하여 작업을 수행할 서비스 역할의 이름 또는 ARN을 입력합니다. 역할을 지정하지 않으면 Automation은 자동화를 실행하는 사용자의 액세스 권한을 사용합니다.
**중요**  
`aws:executeScript` 작업을 사용하는 Amazon 소유가 아닌 실행서의 경우에는 역할을 지정해야 합니다. 자세한 내용은 [실행서 사용 권한](automation-document-script-considerations.md#script-permissions) 섹션을 참조하세요.

1. (옵션) [**출력(Outputs)**]에 다른 프로세스에서 사용할 수 있도록 이 실행서의 자동화를 위한 출력을 입력합니다.

   예를 들어 실행서에서 새 AMI를 생성하는 경우 ["CreateImage.ImageId"]를 지정한 다음 이 출력을 사용하여 후속 자동화에서 새 인스턴스를 생성할 수 있습니다.

1. (선택 사항) **Input parameter(입력 파라미터)** 섹션을 확장하고 다음을 수행합니다.

   1. [**파라미터 이름(Parameter name)**]에 생성 중인 실행서 파라미터에 대한 설명이 포함된 이름을 입력합니다.

   1. **유형**에서 파라미터 유형(예: `String` 또는 `MapList`)을 선택합니다.

   1. **필수**에서 다음 중 하나를 수행합니다.
      + 런타임 시 이 실행서 파라미터의 값을 제공해야 하는 경우 [**예(Yes)**]를 선택합니다.
      + 파라미터가 필수가 아닌 경우 [**아니요(No)**]를 선택하고 **기본값**에 기본 파라미터 값을 입력합니다(옵션).

   1. [**설명(Description)**]에 실행서 파라미터에 대한 설명을 입력합니다.
**참고**  
실행서 파라미터를 더 추가하려면 [**파라미터 추가(Add a parameter)**]를 선택합니다. 실행서 파라미터를 제거하려면 [**X**](제거) 버튼을 선택합니다.

1. (옵션) [**대상 유형(Target type)**] 섹션을 확장하고 대상 유형을 선택하여 자동화를 실행할 수 있는 리소스의 종류를 정의합니다. 예를 들어 EC2 인스턴스에서 실행서를 사용하려면 `/AWS::EC2::Instance`을 선택합니다.
**참고**  
'`/`' 값을 지정하면 모든 유형의 리소스에서 실행서를 실행할 수 있습니다. 유효한 리소스 유형 목록은 *AWS CloudFormation 사용 설명서*의 [AWS 리소스 유형 참조](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-template-resource-type-ref.html)를 참조하세요.

1. (옵션) [**문서 태그(Document tags)**] 섹션을 확장하고 실행서에 적용할 하나 이상의 태그 키-값 페어를 입력합니다. 태그를 사용하면 리소스를 쉽게 식별, 구성 및 검색할 수 있습니다.

1. **Step 1(1단계)** 섹션에서 다음 정보를 제공합니다.
   + [**단계 이름(Step name)**]에 자동화의 첫 번째 단계에 대해 설명하는 이름을 입력합니다.
   + **작업 유형**에서 이 단계에 사용할 작업 유형을 선택합니다.

     사용 가능한 작업 유형에 대한 목록과 자세한 내용은 [Systems Manager Automation 작업 참조](automation-actions.md) 섹션을 참조하세요.
   + **설명**에 자동화 단계에 대한 설명을 입력합니다. Markdown을 사용하여 텍스트 서식을 지정할 수 있습니다.
   + 선택한 **작업 유형**에 따라 **Step inputs(단계 입력)** 섹션에 작업 유형에 필요한 입력을 입력합니다. 예를 들어 작업 `aws:approve`을 선택한 경우 `Approvers` 속성에 대해 값을 지정해야 합니다.

     단계 입력 필드에 대한 자세한 내용은 선택한 작업 유형에 대한 [Systems Manager Automation 작업 참조](automation-actions.md)의 항목을 참조하세요. 예를 들면 [`aws:executeStateMachine` - AWS Step Functions 상태 시스템을 실행합니다.](automation-action-executeStateMachine.md)입니다.
   + (옵션) [**추가 입력(Additional inputs)**]에 실행서에 필요한 추가 입력 값을 입력합니다. 사용 가능한 입력 유형은 해당 단계에 대해 선택한 작업 유형에 따라 다릅니다 (일부 작업 유형에는 입력 값이 필요).
**참고**  
입력을 추가하려면 **Add optional input(선택적 입력 추가)**을 선택합니다. 입력을 제거하려면 **X**(제거) 버튼을 선택합니다.
   + (옵션) [**출력(Outputs)**]에 다른 프로세스에서 사용할 수 있도록 이 단계에 대한 출력을 입력합니다.
**참고**  
모든 작업 유형에서 **출력**을 사용할 수 없습니다.
   + (옵션) [**일반 속성(Common properties)**] 섹션을 확장하고 모든 자동화 작업에 공통적인 작업의 속성을 지정합니다. 예를 들어 [**시간 제한 초(Timeout seconds)**]에 단계가 중지되기 전까지 실행될 수 있는 기간을 지정할 수 있도록 초 단위의 값을 입력합니다.

     자세한 내용은 [모든 작업에서 공유하는 속성](automation-actions.md#automation-common) 섹션을 참조하세요.
**참고**  
단계를 더 추가하려면 [**단계 추가(Add step)**]를 선택하고 단계 생성 절차를 반복합니다. 단계를 제거하려면 [**단계 제거(Remove step)**]를 선택합니다.

1. **Create automation(자동화 생성)**을 선택하여 런북을 저장합니다.

## 스크립트를 실행하는 런북 생성
<a name="create-runbook-scripts"></a>

다음 절차에서는 AWS Systems Manager Automation 콘솔에서 문서 빌더를 사용하여, 스크립트를 실행하는 사용자 지정 런북을 생성하는 방법을 보여줍니다.

생성하는 실행서의 첫 번째 단계에서는 스크립트를 실행하여 Amazon Elastic Compute Cloud(Amazon EC2) 인스턴스를 시작합니다. 두 번째 단계는 다른 스크립트를 실행하여 `ok`로 변경할 인스턴스 상태 확인을 모니터링합니다. 그러면 자동화에 대한 전체 상태가 `Success`로 보고됩니다.

**시작하기 전 준비 사항**  
다음 단계를 완료했는지 확인합니다.
+ 관리자 권한이 있는지, 아니면 AWS Identity and Access Management(IAM)에서 Systems Manager에 액세스할 수 있는 적절한 권한을 부여 받았는지 확인합니다.

  자세한 내용은 [실행서에 대한 사용자 액세스 확인](automation-setup.md#automation-setup-user-access) 섹션을 참조하세요.
+ AWS 계정에 Automation을 위한 IAM 서비스 역할(*수임 역할*이라고도 함)이 있는지 확인합니다. 이 시연에서는 `aws:executeScript` 작업을 사용하기 때문에 이 역할이 필요합니다.

  이 역할을 생성하는 방법에 대한 상세 정보는 [자동화에 대한 서비스 역할(수임 역할) 액세스 구성](automation-setup.md#automation-setup-configure-role) 섹션을 참조하세요.

  `aws:executeScript` 실행을 위한 IAM 서비스 역할 요구 사항에 대한 자세한 내용은 [실행서 사용 권한](automation-document-script-considerations.md#script-permissions) 섹션을 참조하세요.
+ EC2 인스턴스를 시작할 권한이 있는지 확인합니다.

  자세한 내용은 *Amazon EC2 사용 설명서*의 [IAM 및 Amazon EC2](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/UsingIAM.html#intro-to-iam)를 참조하세요.

**문서 빌더를 사용하여, 스크립트를 실행하는 사용자 지정 런북을 생성하려면**

1. AWS Systems Manager 콘솔([https://console.aws.amazon.com/systems-manager/](https://console.aws.amazon.com/systems-manager/))을 엽니다.

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

1. **Create automation(자동화 생성)**을 선택합니다.

1. [**이름(Name)**]에 실행서에 대한 설명이 포함된 이름을 입력합니다(예: **LaunchInstanceAndCheckStatus**).

1. (옵션) [**문서 설명(Document description)**]에서 Markdown을 사용하여 기본 텍스트를 이 실행서에 대한 설명으로 바꿉니다. 다음은 예입니다.

   ```
   ##Title: LaunchInstanceAndCheckState
       -----
       **Purpose**: This runbook first launches an EC2 instance using the AMI ID provided in the parameter ```imageId```. The second step of this runbook continuously checks the instance status check value for the launched instance until the status ```ok``` is returned.
       
       ##Parameters:
       -----
       Name | Type | Description | Default Value
       ------------- | ------------- | ------------- | -------------
       assumeRole | String | (Optional) The ARN of the role that allows Automation to perform the actions on your behalf. | -
       imageId  | String | (Optional) The AMI ID to use for launching the instance. The default value uses the latest Amazon Linux 2023 AMI ID available. | {{ ssm:/aws/service/ami-amazon-linux-latest/al2023-ami-kernel-6.1-arm64 }}
   ```

1. [**수임 역할(Assume role)**]에 Automation용 IAM 서비스 역할(수임 역할)의 ARN을 **arn:aws:iam::111122223333:role/AutomationServiceRole** 형식으로 입력합니다. 111122223333을 사용자의 AWS 계정 ID로 대체합니다.

   사용자가 지정한 역할은 자동화를 시작하는 데 필요한 권한을 제공하는 데 사용됩니다.
**중요**  
`aws:executeScript` 작업을 사용하는 Amazon 소유가 아닌 실행서의 경우에는 역할을 지정해야 합니다. 자세한 내용은 [실행서 사용 권한](automation-document-script-considerations.md#script-permissions) 섹션을 참조하세요.

1. **입력 파라미터**를 확장하고 다음을 수행합니다.

   1. **파라미터 이름**에 **imageId**을 입력합니다.

   1. **Type(유형)**에서 **String**을 선택합니다.

   1. **필수**에서 `No`를 선택합니다.

   1. **기본값**에 다음을 입력합니다.

      ```
      {{ ssm:/aws/service/ami-amazon-linux-latest/al2023-ami-kernel-6.1-arm64 }}
      ```
**참고**  
이 값은 최신 Amazon Linux 2023 Amazon Machine Image(AMI) ID를 사용하여 Amazon EC2 인스턴스를 시작합니다. 다른 AMI를 사용하려면 값을 AMI ID로 바꿉니다.

   1. **설명**에 다음을 입력합니다.

      ```
      (Optional) The AMI ID to use for launching the instance. The default value uses the latest released Amazon Linux 2023 AMI ID.
      ```

1. **파라미터 추가**를 선택하여 두 번째 파라미터 **tagValue**를 생성하고 다음 정보를 입력합니다.

   1. **파라미터 이름**에 **tagValue**을 입력합니다.

   1. **Type(유형)**에서 **String**을 선택합니다.

   1. **필수**에서 `No`를 선택합니다.

   1. **기본값**에 **LaunchedBySsmAutomation**을 입력합니다. 그러면 인스턴스에 태그 키 페어 값 `Name:LaunchedBySsmAutomation`이 추가됩니다.

   1. **설명**에 다음을 입력합니다.

      ```
      (Optional) The tag value to add to the instance. The default value is LaunchedBySsmAutomation.
      ```

1. **파라미터 추가**를 선택하여 세 번째 파라미터 **instanceType**를 생성하고 다음 정보를 입력합니다.

   1. **파라미터 이름**에 **instanceType**을 입력합니다.

   1. **Type(유형)**에서 **String**을 선택합니다.

   1. **필수**에서 `No`를 선택합니다.

   1. **기본값**에 **t2.micro**를 입력합니다.

   1. **파라미터 설명**에 다음을 입력합니다.

      ```
      (Optional) The instance type to use for the instance. The default value is t2.micro.
      ```

1. **대상 유형**을 확장하고 **"/"**를 선택합니다.

1. (옵션) [**문서 태그(Document tags)**]를 확장하여 실행서에 리소스 태그를 적용합니다. **태그 키**에 **Purpose**을 입력하고 **태그 값**에 **LaunchInstanceAndCheckState**를 입력합니다.

1. **1단계(Step 1)** 섹션에서 다음 단계를 완료합니다.

   1. [**단계 이름(Step name)**]에 자동화의 첫 번째 단계에 대해 설명하는 단계 이름(**LaunchEc2Instance**)을 입력합니다.

   1. **작업 유형**에서 **Run a script(스크립트 실행)**(**aws:executeScript**)를 선택합니다.

   1. **설명**에 다음과 같은 자동화 단계에 대한 설명을 입력합니다.

      ```
      **About This Step**
          
          This step first launches an EC2 instance using the ```aws:executeScript``` action and the provided script.
      ```

   1. **입력**을 확장합니다.

   1. **런타임**에서는 제공된 스크립트를 실행하는 데 사용할 런타임 언어를 선택합니다.

   1. **핸들러**에 **launch\$1instance**를 입력합니다. 이는 다음 스크립트에서 선언된 함수 이름입니다.
**참고**  
PowerShell에는 필요하지 않습니다.

   1. **스크립트**에서 기본 내용을 다음과 같이 바꿉니다. 스크립트를 해당 런타임 값과 일치시켜야 합니다.

------
#### [ Python ]

      ```
      def launch_instance(events, context):
            import boto3
            ec2 = boto3.client('ec2')
          
            image_id = events['image_id']
            tag_value = events['tag_value']
            instance_type = events['instance_type']
          
            tag_config = {'ResourceType': 'instance', 'Tags': [{'Key':'Name', 'Value':tag_value}]}
          
            res = ec2.run_instances(ImageId=image_id, InstanceType=instance_type, MaxCount=1, MinCount=1, TagSpecifications=[tag_config])
          
            instance_id = res['Instances'][0]['InstanceId']
          
            print('[INFO] 1 EC2 instance is successfully launched', instance_id)
          
            return { 'InstanceId' : instance_id }
      ```

------
#### [ PowerShell ]

      ```
      Install-Module AWS.Tools.EC2 -Force
          Import-Module AWS.Tools.EC2
          
          $payload = $env:InputPayload | ConvertFrom-Json
          
          $imageid = $payload.image_id
          
          $tagvalue = $payload.tag_value
          
          $instanceType = $payload.instance_type
          
          $type = New-Object Amazon.EC2.InstanceType -ArgumentList $instanceType
          
          $resource = New-Object Amazon.EC2.ResourceType -ArgumentList 'instance'
          
          $tag = @{Key='Name';Value=$tagValue}
          
          $tagSpecs = New-Object Amazon.EC2.Model.TagSpecification
          
          $tagSpecs.ResourceType = $resource
          
          $tagSpecs.Tags.Add($tag)
          
          $res = New-EC2Instance -ImageId $imageId -MinCount 1 -MaxCount 1 -InstanceType $type -TagSpecification $tagSpecs
          
          return @{'InstanceId'=$res.Instances.InstanceId}
      ```

------

   1. **Additional inputs(추가 입력)**를 확장합니다.

   1. **Input name(입력 이름)**에서 **InputPayload**를 선택합니다. **Input value(입력 값)**에 다음 YAML 데이터를 입력합니다.

      ```
      image_id: "{{ imageId }}"
          tag_value: "{{ tagValue }}"
          instance_type: "{{ instanceType }}"
      ```

1. **출력**을 확장하고 다음을 수행합니다.
   + **이름**에 **payload**를 입력합니다.
   + **Selector(선택기)**에 **\$1.Payload**를 입력합니다.
   + **Type(유형)**에서 `StringMap`을 선택합니다.

1. [**단계 추가(Add step)**]를 선택하여 실행서에 두 번째 단계를 추가합니다. 두 번째 단계는 1단계에서 시작된 인스턴스의 상태를 쿼리하고 반환된 상태가 `ok`가 될 때까지 기다립니다.

1. **Step 2(2단계)** 섹션에서 다음을 수행합니다.

   1. [**단계 이름(Step name)**]에 자동화의 두 번째 단계에 대해 설명하는 이름(**WaitForInstanceStatusOk**)을 입력합니다.

   1. **작업 유형**에서 **Run a script(스크립트 실행)**(**aws:executeScript**)를 선택합니다.

   1. **설명**에 다음과 같은 자동화 단계에 대한 설명을 입력합니다.

      ```
      **About This Step**
          
          The script continuously polls the instance status check value for the instance launched in Step 1 until the ```ok``` status is returned.
      ```

   1. **런타임**에서는 제공된 스크립트를 실행하는 데 사용되는 런타임 언어를 선택합니다.

   1. **핸들러**에 **poll\$1instance**를 입력합니다. 이는 다음 스크립트에서 선언된 함수 이름입니다.
**참고**  
PowerShell에는 필요하지 않습니다.

   1. **스크립트**에서 기본 내용을 다음과 같이 바꿉니다. 스크립트를 해당 런타임 값과 일치시켜야 합니다.

------
#### [ Python ]

      ```
      def poll_instance(events, context):
            import boto3
            import time
          
            ec2 = boto3.client('ec2')
          
            instance_id = events['InstanceId']
          
            print('[INFO] Waiting for instance status check to report ok', instance_id)
          
            instance_status = "null"
          
            while True:
              res = ec2.describe_instance_status(InstanceIds=[instance_id])
          
              if len(res['InstanceStatuses']) == 0:
                print("Instance status information is not available yet")
                time.sleep(5)
                continue
          
              instance_status = res['InstanceStatuses'][0]['InstanceStatus']['Status']
          
              print('[INFO] Polling to get status of the instance', instance_status)
          
              if instance_status == 'ok':
                break
          
              time.sleep(10)
          
            return {'Status': instance_status, 'InstanceId': instance_id}
      ```

------
#### [ PowerShell ]

      ```
          Install-Module AWS.Tools.EC2 -Force
          
          $inputPayload = $env:InputPayload | ConvertFrom-Json
          
          $instanceId = $inputPayload.payload.InstanceId
          
          $status = Get-EC2InstanceStatus -InstanceId $instanceId
          
          while ($status.Status.Status -ne 'ok'){
             Write-Host 'Polling get status of the instance', $instanceId
          
             Start-Sleep -Seconds 5
          
             $status = Get-EC2InstanceStatus -InstanceId $instanceId
          }
          
          return @{Status = $status.Status.Status; InstanceId = $instanceId}
      ```

------

   1. **Additional inputs(추가 입력)**를 확장합니다.

   1. **Input name(입력 이름)**에서 **InputPayload**를 선택합니다. **Input value(입력 값)**에 다음을 입력합니다.

      ```
      {{ LaunchEc2Instance.payload }}
      ```

1. **Create automation(자동화 생성)**을 선택하여 런북을 저장합니다.

# 런북에서 스크립트 사용
<a name="automation-document-script-considerations"></a>

Automation 실행서는 자동화의 일부로 스크립트 실행을 지원합니다. Automation은 AWS Systems Manager의 도구입니다. 실행서를 사용하면 스크립트를 실행하기 위한 별도의 컴퓨팅 환경을 생성하지 않고도 AWS에서 직접 스크립트를 실행할 수 있습니다. 실행서는 승인과 같은 다른 자동화 단계 유형과 함께 스크립트 단계를 실행할 수 있기 때문에, 중요하거나 모호한 상황에 수동으로 개입할 수 있습니다. 실행서의 `aws:executeScript` 작업 출력을 Amazon CloudWatch Logs로 보낼 수 있습니다. 자세한 내용은 [CloudWatch Logs로 Automation 작업 출력 로깅](automation-action-logging.md) 섹션을 참조하세요.

## 실행서 사용 권한
<a name="script-permissions"></a>

실행서를 사용하려면 Systems Manager에서 AWS Identity and Access Management(IAM) 역할의 권한을 사용해야 합니다. 자동화에서 사용할 역할의 권한을 결정하는 데 사용하는 방법은 몇 가지 요소와 단계에서 `aws:executeScript` 작업을 사용하는지 여부에 따라 달라집니다.

`aws:executeScript`를 사용하지 않는 실행서의 경우 Automation은 두 가지 권한 소스 중 하나를 사용합니다.
+ 실행서에 지정되거나 파라미터로 전달되는 IAM 서비스 역할 또는 수임 역할의 권한입니다.
+ IAM 서비스 역할이 지정되지 않은 경우에는 자동화를 시작한 사용자의 권한입니다.

그러나 실행서의 단계에 `aws:executeScript` 작업이 포함되어 있는 경우 작업에 대해 지정된 Python 또는 PowerShell 스크립트가 AWS API 작업을 호출하는 경우 항상 IAM 서비스 역할(수임 역할)이 필요합니다. 자동화는 다음 순서로 이 역할을 확인합니다.
+ 실행서에 지정되거나 파라미터로 전달되는 IAM 서비스 역할 또는 수임 역할의 권한입니다.
+ 역할이 없는 경우 자동화는 권한 없이 `aws:executeScript`에 대해 지정된 Python 또는 PowerShell 스크립트의 실행을 시도합니다. 스크립트가 AWS API 작업(예: Amazon EC2 `CreateImage` 작업)을 호출하거나 AWS 리소스(예: EC2 인스턴스)에서 작업을 시도하는 경우 스크립트를 포함하는 단계가 실패하고 Systems Manager가 오류를 보고하는 오류 메시지를 반환합니다.

## 실행서에 스크립트 추가
<a name="adding-scripts"></a>

실행서의 단계의 일부로 스크립트를 인라인으로 포함시켜 실행서에 스크립트를 추가할 수 있습니다. 로컬 시스템에서 스크립트를 업로드하거나 스크립트가 위치하는 Amazon Simple Storage Service(Amazon S3) 버킷을 지정하여 실행서에 스크립트를 첨부할 수도 있습니다. 스크립트를 실행하는 단계가 완료되면 스크립트의 출력을 JSON 객체로 사용할 수 있습니다. 그런 다음 이를 실행서의 후속 단계에서 입력으로 사용할 수 있습니다. `aws:executeScript` 작업 및 스크립트에 첨부 파일을 사용하는 방법에 대한 자세한 내용은 [`aws:executeScript` - 스크립트 실행](automation-action-executeScript.md) 섹션을 참조하세요.

## 실행서에 대한 스크립트 제약 조건
<a name="script-constraints"></a>

실행서는 첨부 파일을 5개로 제한합니다. 스크립트는 Python 스크립트(.py) 또는 PowerShell Core 스크립트(.ps1)의 형태이거나 .zip 파일 내의 내용으로 첨부될 수 있습니다.

# 런북에서 조건문 사용
<a name="automation-branch-condition"></a>

기본적으로 실행서의 `mainSteps` 섹션에서 정의하는 단계는 순차적으로 실행됩니다. 한 작업이 완료된 후에는 `mainSteps` 섹션에 지정된 다음 작업이 시작됩니다. 또한 작업 실행에 실패할 경우 기본적으로 전체 자동화가 실패합니다. 이 섹션에 설명된 `aws:branch` 자동화 작업 및 실행서 옵션을 사용하여 *조건부 분기*를 수행하는 자동화를 생성할 수 있습니다. 다시 말해서 단계 완료 시 변경 내용에 동적으로 응답하거나 다양한 선택 항목을 평가한 후 다른 단계로 이동하는 자동화를 생성할 수 있습니다. 동적 자동화를 생성하는 데 사용할 수 있는 옵션 목록은 다음과 같습니다.
+ **`aws:branch`**: 이 자동화 작업을 통해 한 단계에서 여러 선택 항목을 평가한 다음 평가 결과에 따라 실행서의 다른 단계로 이동하는 동적 자동화를 생성할 수 있습니다.
+ **`nextStep`**: 이 옵션은 한 단계를 성공적으로 완료한 후 처리할 자동화의 단계를 지정합니다.
+ **`isEnd`**: 이 옵션은 특정 단계 종료 시 자동화를 중지합니다. 이 옵션의 기본값은 false입니다.
+ **`isCritical`**: 이 옵션은 자동화의 성공적 완료에 대해 단계를 심각으로 지정합니다. 이 지정이 있는 단계가 실패하면 Automation은 자동화의 최종 상태를 `Failed`로 보고합니다. 이 옵션의 기본값은 `true`입니다.
+ **`onFailure`**: 이 옵션은 실패 시 자동화가 중지되어야 하는지, 계속되어야 하는지 또는 다른 단계로 이동해야 하는지를 나타냅니다. 이 옵션의 기본값은 중단입니다.

다음 섹션에서는 `aws:branch` 자동화 작업을 설명합니다. `nextStep`, `isEnd`, `isCritical` 및 `onFailure` 옵션에 대한 자세한 내용은 [예제 `aws:branch` 실행서](#branch-runbook-examples) 섹션을 참조하세요.

## `aws:branch` 작업 수행
<a name="branch-action-explained"></a>

`aws:branch` 작업은 자동화에 대한 가장 동적인 조건부 분기 옵션을 제공합니다. 앞에서 언급한 바와 같이, 이 작업을 사용하면 자동화가 한 단계에서 여러 조건을 평가한 다음 해당 평가의 결과에 따라 새 단계로 이동할 수 있습니다. `aws:branch` 작업은 프로그래밍의 `IF-ELIF-ELSE` 문처럼 작동합니다.

다음은 `aws:branch` 단계의 YAML 예제입니다.

```
- name: ChooseOSforCommands
  action: aws:branch
  inputs:
    Choices:
    - NextStep: runPowerShellCommand
      Variable: "{{GetInstance.platform}}"
      StringEquals: Windows
    - NextStep: runShellCommand
      Variable: "{{GetInstance.platform}}"
      StringEquals: Linux
    Default:
      PostProcessing
```

단계에 대한 `aws:branch` 작업을 지정할 경우 해당 자동화에서 평가해야 하는 `Choices`를 지정할 수 있습니다. 이 자동화는 실행서의 `Parameters` 섹션에 지정된 파라미터의 값에 따라 `Choices`를 평가할 수 있습니다. 이 자동화는 이전 단계의 출력에 따라 `Choices`를 평가할 수도 있습니다.

이 자동화는 부울 식을 사용하여 각 선택을 평가합니다. 평가에서 첫 번째 선택 항목이 `true`인 것으로 확인되면 자동화는 해당 선택 항목에 지정된 단계로 이동합니다. 평가에서 첫 번째 선택 항목이 `false`인 것으로 확인되면 자동화는 다음 선택 항목을 평가합니다. 단계에 세 개 이상의 `Choices`가 포함된 경우 자동화는 `true`인 선택 항목을 평가할 때까지 순서대로 각 선택 항목을 평가합니다. 그런 다음 이 워크플로는 `true`인 선택 항목에 지정된 단계로 이동합니다.

`Choices` 중에 `true`인 항목이 없는 경우 자동화는 단계에 `Default` 값이 포함되었는지 확인합니다. `Default` 값은 선택 항목 중에 `true`인 항목이 없는 경우 자동화에서 이동해야 하는 단계를 정의합니다. 단계에 대한 `Default` 값이 지정되지 않은 경우 자동화는 실행서의 다음 단계를 처리합니다.

다음은 **chooseOSfromParameter**라는 YAML의 `aws:branch` 단계입니다. 이 단계에는 `NextStep: runWindowsCommand`와 `NextStep: runLinuxCommand`라는 두 `Choices`가 포함되어 있습니다. 이 자동화는 이러한 `Choices`를 평가하여 해당 운영 체제에 대해 실행할 명령을 결정합니다. 각 선택 항목에 대한 `Variable`은 `{{OSName}}`을 사용하며, 이것은 실행서 작성자가 실행서의 `Parameters` 섹션에 정의한 파라미터입니다.

```
mainSteps:
- name: chooseOSfromParameter
  action: aws:branch
  inputs:
    Choices:
    - NextStep: runWindowsCommand
      Variable: "{{OSName}}"
      StringEquals: Windows
    - NextStep: runLinuxCommand
      Variable: "{{OSName}}"
      StringEquals: Linux
```

다음은 **chooseOSfromOutput**이라는 YAML의 `aws:branch` 단계입니다. 이 단계에는 `NextStep: runPowerShellCommand`와 `NextStep: runShellCommand`라는 두 `Choices`가 포함되어 있습니다. 이 자동화는 이러한 `Choices`를 평가하여 해당 운영 체제에 대해 실행할 명령을 결정합니다. 각 선택 항목의 `Variable`은 `{{GetInstance.platform}}`을 사용하며, 이것은 실행서의 이전 단계에서 얻은 출력입니다. 이 예제에는 `Default`라는 옵션도 포함되어 있습니다. 자동화에서 두 `Choices`를 평가했지만 어느 것도 `true`가 아니면 이 자동화는 `PostProcessing`이라는 단계로 이동합니다.

```
mainSteps:
- name: chooseOSfromOutput
  action: aws:branch
  inputs:
    Choices:
    - NextStep: runPowerShellCommand
      Variable: "{{GetInstance.platform}}"
      StringEquals: Windows
    - NextStep: runShellCommand
      Variable: "{{GetInstance.platform}}"
      StringEquals: Linux
    Default:
      PostProcessing
```

### 실행서에서 `aws:branch` 단계 생성
<a name="create-branch-action"></a>

실행서에서 `aws:branch` 단계를 생성하는 경우 자동화에서 다음으로 이동해야 할 단계를 결정하기 위해 평가해야 하는 `Choices`를 정의합니다. 앞에서 언급한 바와 같이, `Choices`는 부울 식을 사용하여 평가됩니다. 각 선택 항목은 다음 옵션을 정의해야 합니다.
+ **NextStep**: 지정된 선택 항목이 `true`인 경우 처리할 실행서의 다음 단계입니다.
+ **Variable**: 런북의 `Parameters` 섹션에 정의된 파라미터(`Variables` 섹션에 정의된 변수)의 이름을 지정하거나 이전 단계에서 얻은 출력 객체를 지정합니다.

  다음 형식을 사용하여 변수 값을 지정합니다.

  `Variable: "{{variable name}}"`

  다음 형식을 사용하여 파라미터 값을 지정합니다.

  `Variable: "{{parameter name}}"`

  다음 형식을 사용하여 출력 객체 변수를 지정합니다.

  `Variable: "{{previousStepName.outputName}}"`
**참고**  
출력 변수 생성은 다음 섹션인 [출력 변수 생성 정보](#branch-action-output)에서 자세히 설명합니다.
+ **Operation**: 선택 항목을 평가하는 데 사용되는 기준으로, 예를 들면 `StringEquals: Linux`입니다. `aws:branch` 작업에서는 다음 연산을 지원합니다.

**문자열 연산**
  + StringEquals
  + EqualsIgnoreCase
  + StartsWith
  + EndsWith
  + 포함

**수치 연산**
  + NumericEquals
  + NumericGreater
  + NumericLesser
  + NumericGreaterOrEquals
  + NumericLesser
  + NumericLesserOrEquals

**부울 연산**
  + BooleanEquals
**중요**  
실행서를 생성하면 시스템에서 실행서의 각 작업을 검증합니다. 작업이 지원되지 않는 경우 실행서를 생성할 때 오류가 발생합니다.
+ **Default**: `Choices` 중 어떤 것도 `true`가 아니면 자동화에서 이동해야 할 폴백 단계를 지정합니다.
**참고**  
`Default` 값을 지정하지 않으려면 `isEnd` 옵션을 지정할 수 있습니다. `Choices` 중 어느 것도 `true`가 아니며 `Default` 값을 지정하지 않은 경우 자동화는 단계의 끝에서 중지됩니다.

다음 템플릿을 사용하여 실행서에서 `aws:branch` 단계를 생성합니다. 각 *example resource placeholder*를 사용자의 정보로 바꿉니다.

------
#### [ YAML ]

```
mainSteps:
- name: step name
  action: aws:branch
  inputs:
    Choices:
    - NextStep: step to jump to if evaluation for this choice is true
      Variable: "{{parameter name or output from previous step}}"
      Operation type: Operation value
    - NextStep: step to jump to if evaluation for this choice is true
      Variable: "{{parameter name or output from previous step}}"
      Operation type: Operation value
    Default:
      step to jump to if all choices are false
```

------
#### [ JSON ]

```
{
   "mainSteps":[
      {
         "name":"a name for the step",
         "action":"aws:branch",
         "inputs":{
            "Choices":[
               {
                  "NextStep":"step to jump to if evaluation for this choice is true",
                  "Variable":"{{parameter name or output from previous step}}",
                  "Operation type":"Operation value"
               },
               {
                  "NextStep":"step to jump to if evaluation for this choice is true",
                  "Variable":"{{parameter name or output from previous step}}",
                  "Operation type":"Operation value"
               }
            ],
            "Default":"step to jump to if all choices are false"
         }
      }
   ]
}
```

------

#### 출력 변수 생성 정보
<a name="branch-action-output"></a>

이전 단계의 출력을 참조하는 `aws:branch` 선택 항목을 생성하려면 이전 단계의 이름과 출력 필드의 이름을 식별해야 합니다. 그러고 나서 다음 형식을 사용하여 단계의 이름과 필드를 결합합니다.

`Variable: "{{previousStepName.outputName}}"`

예를 들어 다음 예에서 첫 번째 단계의 이름은 `GetInstance`입니다. 그 다음, `outputs` 아래에 `platform`이라는 필드가 있습니다. 두 번째 단계(`ChooseOSforCommands`)에서 작성자는 플랫폼 필드의 출력을 변수로 참조하려고 합니다. 변수를 생성하려면 단계 이름(GetInstance)과 출력 필드 이름(platform)을 결합하여 `Variable: "{{GetInstance.platform}}"`을 생성하면 됩니다.

```
mainSteps:
- Name: GetInstance
  action: aws:executeAwsApi
  inputs:
    Service: ssm
    Api: DescribeInstanceInformation
    Filters:
    - Key: InstanceIds
      Values: ["{{ InstanceId }}"]
  outputs:
  - Name: myInstance
    Selector: "$.InstanceInformationList[0].InstanceId"
    Type: String
  - Name: platform
    Selector: "$.InstanceInformationList[0].PlatformType"
    Type: String
- name: ChooseOSforCommands
  action: aws:branch
  inputs:
    Choices:
    - NextStep: runPowerShellCommand
      Variable: "{{GetInstance.platform}}"
      StringEquals: Windows
    - NextStep: runShellCommand
      Variable: "{{GetInstance.platform}}"
      StringEquals: Linux
    Default:
      Sleep
```

다음은 이전 단계 및 출력에서 *"Variable": "\$1\$1 describeInstance.Platform \$1\$1"*이 어떻게 생성되는지 보여주는 예시입니다.

```
- name: describeInstance
  action: aws:executeAwsApi
  onFailure: Abort
  inputs:
    Service: ec2
    Api: DescribeInstances
    InstanceIds:
    - "{{ InstanceId }}"
  outputs:
  - Name: Platform
    Selector: "$.Reservations[0].Instances[0].Platform"
    Type: String
  nextStep: branchOnInstancePlatform
- name: branchOnInstancePlatform
  action: aws:branch
  inputs:
    Choices:
    - NextStep: runEC2RescueForWindows
      Variable: "{{ describeInstance.Platform }}"
      StringEquals: windows
    Default: runEC2RescueForLinux
```

### 예제 `aws:branch` 실행서
<a name="branch-runbook-examples"></a>

다음은 `aws:branch`를 사용하는 몇 가지 예제 실행서입니다.

**예제 1: `aws:branch`를 출력 변수와 함께 사용하여 운영 체제 유형에 따라 명령 실행**

이 예의 첫 번째 단계(`GetInstance`)에서 실행서 작성자는 `aws:executeAwsApi` 작업을 사용하여 `ssm` `DescribeInstanceInformation` API 작업을 호출합니다. 작성자는 이 작업을 사용하여 인스턴스에서 사용 중인 운영 체제 유형을 확인합니다. `aws:executeAwsApi` 작업은 인스턴스 ID 및 플랫폼 유형을 출력합니다.

두 번째 단계(`ChooseOSforCommands`)에서 작성자는 `aws:branch` 작업과 두`Choices`인 `NextStep: runPowerShellCommand` 및 `NextStep: runShellCommand`를 함께 사용합니다. 이 자동화는 이전 단계(`Variable: "{{GetInstance.platform}}"`)의 출력을 사용하여 인스턴스의 운영 체제를 평가합니다. 이 자동화는 지정된 운영 체제에 대한 단계로 이동합니다.

```
---
schemaVersion: '0.3'
assumeRole: "{{AutomationAssumeRole}}"
parameters:
  AutomationAssumeRole:
    default: ""
    type: String
mainSteps:
- name: GetInstance
  action: aws:executeAwsApi
  inputs:
    Service: ssm
    Api: DescribeInstanceInformation
  outputs:
  - Name: myInstance
    Selector: "$.InstanceInformationList[0].InstanceId"
    Type: String
  - Name: platform
    Selector: "$.InstanceInformationList[0].PlatformType"
    Type: String
- name: ChooseOSforCommands
  action: aws:branch
  inputs:
    Choices:
    - NextStep: runPowerShellCommand
      Variable: "{{GetInstance.platform}}"
      StringEquals: Windows
    - NextStep: runShellCommand
      Variable: "{{GetInstance.platform}}"
      StringEquals: Linux
    Default:
      Sleep
- name: runShellCommand
  action: aws:runCommand
  inputs:
    DocumentName: AWS-RunShellScript
    InstanceIds:
    - "{{GetInstance.myInstance}}"
    Parameters:
      commands:
      - ls
  isEnd: true
- name: runPowerShellCommand
  action: aws:runCommand
  inputs:
    DocumentName: AWS-RunPowerShellScript
    InstanceIds:
    - "{{GetInstance.myInstance}}"
    Parameters:
      commands:
      - ls
  isEnd: true
- name: Sleep
  action: aws:sleep
  inputs:
    Duration: PT3S
```

**예 2: `aws:branch`를 파라미터 변수와 함께 사용하여 운영 체제 유형에 따라 명령 실행**

실행서 작성자는 실행서의 시작 부분에 나오는 `parameters` 섹션에서 여러 파라미터 옵션을 정의합니다. 파라미터 하나의 이름은 `OperatingSystemName`입니다. 첫 번째 단계(`ChooseOS`)에서 작성자는 `aws:branch` 작업과 두`Choices`인 `NextStep: runWindowsCommand` 및 `NextStep: runLinuxCommand`를 함께 사용합니다. 이러한 `Choices`의 변수는 파라미터 섹션에 지정된 파라미터 옵션(`Variable: "{{OperatingSystemName}}"`)을 참조합니다. 사용자는 이 실행서를 실행할 경우 런타임 시 `OperatingSystemName`에 대한 값을 지정합니다. 이 자동화는 `Choices` 평가 중에 런타임 파라미터를 사용합니다. 이 자동화는 `OperatingSystemName`에 지정된 런타임 파라미터에 따라 지정된 운영 체제에 해당하는 단계로 이동합니다.

```
---
schemaVersion: '0.3'
assumeRole: "{{AutomationAssumeRole}}"
parameters:
  AutomationAssumeRole:
    default: ""
    type: String
  OperatingSystemName:
    type: String
  LinuxInstanceId:
    type: String
  WindowsInstanceId:
    type: String
mainSteps:
- name: ChooseOS
  action: aws:branch
  inputs:
    Choices:
    - NextStep: runWindowsCommand
      Variable: "{{OperatingSystemName}}"
      StringEquals: windows
    - NextStep: runLinuxCommand
      Variable: "{{OperatingSystemName}}"
      StringEquals: linux
    Default:
      Sleep
- name: runLinuxCommand
  action: aws:runCommand
  inputs:
    DocumentName: "AWS-RunShellScript"
    InstanceIds:
    - "{{LinuxInstanceId}}"
    Parameters:
      commands:
      - ls
  isEnd: true
- name: runWindowsCommand
  action: aws:runCommand
  inputs:
    DocumentName: "AWS-RunPowerShellScript"
    InstanceIds:
    - "{{WindowsInstanceId}}"
    Parameters:
      commands:
      - date
  isEnd: true
- name: Sleep
  action: aws:sleep
  inputs:
    Duration: PT3S
```

### 연산자를 사용하여 복합 분기 자동화 생성
<a name="branch-operators"></a>

`aws:branch` 단계에서 `And`, `Or` 및 `Not` 연산자를 사용하여 복합 문기 자동화를 생성할 수 있습니다.

**'And' 연산자**  
선택 항목에 대해 여러 변수가 `true`가 되도록 하려는 경우 `And` 연산자를 사용합니다. 다음 예제에서는 첫 번째 선택 항목이 인스턴스가 `running`이고 `Windows` 운영 체제를 사용하는지 여부를 평가합니다. 이들 변수 *모두*를 평가한 결과가 true이면 이 자동화는 `runPowerShellCommand` 단계로 이동합니다. 변수 중 하나 이상이 `false`이면 이 자동화는 두 번째 선택 항목에 대한 변수를 평가합니다.

```
mainSteps:
- name: switch2
  action: aws:branch
  inputs:
    Choices:
    - And:
      - Variable: "{{GetInstance.pingStatus}}"
        StringEquals: running
      - Variable: "{{GetInstance.platform}}"
        StringEquals: Windows
      NextStep: runPowerShellCommand

    - And:
      - Variable: "{{GetInstance.pingStatus}}"
        StringEquals: running
      - Variable: "{{GetInstance.platform}}"
        StringEquals: Linux
      NextStep: runShellCommand
    Default:
      sleep3
```

**'Or' 연산자**  
선택 항목에 대해 여러 변수 중 *하나라도* true가 되도록 하려는 경우 `Or` 연산자를 사용합니다. 다음 예제에서 첫 번째 선택 항목은 파라미터 문자열이 `Windows`이고 AWS Lambda 단계의 출력이 true인지 여부를 평가합니다. 평가 결과 이들 변수 중 *하나*가 true인 것으로 확인되면 이 자동화는 `RunPowerShellCommand` 단계로 이동합니다. 두 변수가 모두 false이면 이 자동화는 두 번째 선택 항목에 대한 변수를 평가합니다.

```
- Or:
  - Variable: "{{parameter1}}"
    StringEquals: Windows
  - Variable: "{{BooleanParam1}}"
    BooleanEquals: true
  NextStep: RunPowershellCommand
- Or:
  - Variable: "{{parameter2}}"
    StringEquals: Linux
  - Variable: "{{BooleanParam2}}"
    BooleanEquals: true
  NextStep: RunShellScript
```

**'Not' 연산자**  
변수가 true가 *아닐* 때 정의된 단계로 이동하려면 `Not` 연산자를 사용합니다. 다음 예제에서 첫 번째 선택 항목은 파라미터 문자열이 `Not Linux`인지 여부를 평가합니다. 평가 결과 이 변수가 Linux가 아니면 이 자동화는 `sleep2` 단계로 이동합니다. 첫 번째 선택 항목의 평가에서 Linux*인* 것으로 확인되면 이 자동화는 다음 선택 항목을 평가합니다.

```
mainSteps:
- name: switch
  action: aws:branch
  inputs:
    Choices:
    - NextStep: sleep2
      Not:
        Variable: "{{testParam}}"
        StringEquals: Linux
    - NextStep: sleep1
      Variable: "{{testParam}}"
      StringEquals: Windows
    Default:
      sleep3
```

## 조건 옵션 사용 방법의 예
<a name="conditional-examples"></a>

이 섹션에는 실행서에서 동적 옵션 사용 방법의 다양한 예가 포함되어 있습니다. 이 섹션에 나오는 각 예는 다음 실행서를 확장합니다. 이 실행서에는 2개의 작업이 있습니다. 첫 번째 작업의 이름은 `InstallMsiPackage`입니다. `aws:runCommand` 작업을 사용하여 Windows Server 인스턴스에 애플리케이션을 설치합니다. 두 번째 작업의 이름은 `TestInstall`입니다. 이 작업은 `aws:invokeLambdaFunction` 작업을 사용하여 애플리케이션이 성공적으로 설치된 경우 설치된 애플리케이션의 테스트를 수행합니다. 1단계는 `onFailure: Abort`를 지정합니다. 따라서 애플리케이션이 성공적으로 설치되지 않은 경우 2단계 이전에 자동화가 중지됩니다.

**예 1: 2개의 선형 작업이 있는 실행서**

```
---
schemaVersion: '0.3'
description: Install MSI package and run validation.
assumeRole: "{{automationAssumeRole}}"
parameters:
  automationAssumeRole:
    type: String
    description: "(Required) Assume role."
  packageName:
    type: String
    description: "(Required) MSI package to be installed."
  instanceIds:
    type: String
    description: "(Required) Comma separated list of instances."
mainSteps:
- name: InstallMsiPackage
  action: aws:runCommand
  maxAttempts: 2
  onFailure: Abort
  inputs:
    InstanceIds:
    - "{{instanceIds}}"
    DocumentName: AWS-RunPowerShellScript
    Parameters:
      commands:
      - msiexec /i {{packageName}}
- name: TestInstall
  action: aws:invokeLambdaFunction
  maxAttempts: 1
  timeoutSeconds: 500
  inputs:
    FunctionName: TestLambdaFunction
...
```

**`onFailure` 옵션을 사용하여 다양한 단계로 이동하는 동적 자동화 생성**

다음 예에서는 `onFailure: step:step name`, `nextStep` 및 `isEnd` 옵션을 사용하여 동적 자동화를 생성합니다. 이 예제에서 `InstallMsiPackage` 작업이 실패하면 자동화가 *PostFailure*(`onFailure: step:PostFailure`)라는 작업으로 이동하여 설치가 실패할 경우 특정 작업을 수행하는 AWS Lambda 함수를 실행합니다. 설치에 성공하면 이 자동화는 TestInstall 작업(`nextStep: TestInstall`)으로 이동합니다. 두 단계 중 하나가 완료될 때 자동화가 끝나도록 두 `TestInstall` 및 `PostFailure` 단계에 모두 `isEnd` 옵션(`isEnd: true`)이 사용됩니다.

**참고**  
`mainSteps` 섹션의 마지막 단계에서 `isEnd` 옵션을 사용하는 것은 선택 사항입니다. 마지막 단계가 다른 단계로 건너뛰지 않으면 마지막 단계에서 작업을 실행한 후 자동화가 중지됩니다.

**예 2: 다양한 단계로 이동하는 동적 자동화**

```
mainSteps
- name: InstallMsiPackage
  action: aws:runCommand
  onFailure: step:PostFailure
  maxAttempts: 2
  inputs:
    InstanceIds:
    - "{{instanceIds}}"
    DocumentName: AWS-RunPowerShellScript
    Parameters:
      commands:
      - msiexec /i {{packageName}}
  nextStep: TestInstall
- name: TestInstall
  action: aws:invokeLambdaFunction
  maxAttempts: 1
  timeoutSeconds: 500
  inputs:
    FunctionName: TestLambdaFunction
  isEnd: true
- name: PostFailure
  action: aws:invokeLambdaFunction
  maxAttempts: 1
  timeoutSeconds: 500
  inputs:
    FunctionName: PostFailureRecoveryLambdaFunction
  isEnd: true
...
```

**참고**  
실행서를 처리하기 전에 시스템은 실행서가 무한 루프를 생성하지 않는지 확인합니다. 무한 루프가 감지되면 자동화는 오류와 순환 추적을 반환하여 루프를 생성하는 단계를 표시합니다.

**중요 단계를 정의하는 동적 자동화 생성**

단계가 자동화의 전체 성공에 중요한지를 지정할 수 있습니다. 중요 단계가 실패하면 하나 이상의 단계가 성공적으로 실행되더라도 Automation은 자동화 상태를 `Failed`로 보고합니다. 다음 예에서 사용자는 *InstallMsiPackage* 단계가 실패하는 경우(`onFailure: step:VerifyDependencies`) *VerifyDependencies* 단계를 식별합니다. 사용자는 `InstallMsiPackage` 단계가 중요하지 않다고 지정합니다(`isCritical: false`). 이 예에서는 애플리케이션 설치에 실패한 경우 자동화가 `VerifyDependencies` 단계를 처리하여 하나 이상의 종속성이 누락되어 결과적으로 애플리케이션 설치에 실패했는지 여부를 확인합니다.

**예제 3: 자동화의 중요 단계 정의**

```
---
name: InstallMsiPackage
action: aws:runCommand
onFailure: step:VerifyDependencies
isCritical: false
maxAttempts: 2
inputs:
  InstanceIds:
  - "{{instanceIds}}"
  DocumentName: AWS-RunPowerShellScript
  Parameters:
    commands:
    - msiexec /i {{packageName}}
nextStep: TestPackage
...
```

# 작업 출력을 입력으로 사용
<a name="automation-action-outputs-inputs"></a>

몇 가지 자동화 작업은 사전 정의된 출력을 반환합니다. `{{stepName.outputName}}` 형식을 사용하여 이러한 출력을 런북의 이후 단계에 입력으로 전달할 수 있습니다. 런북에서 다양한 자동화 작업의 출력을 정의할 수 있습니다. 이를 통해 스크립트를 실행하거나 다른 AWS 서비스를 위한 API 작업을 한 번 호출하여 이후 작업에서 해당 값을 입력으로 재사용할 수 있습니다. 런북의 파라미터 유형은 정적입니다. 즉, 파라미터 유형을 정의한 후에는 변경할 수 없습니다. 단계 출력을 정의하려면 다음 필드를 제공하십시오.
+ 이름: (필수) 이후 단계에서 출력 값을 참조하는 데 사용되는 출력 이름입니다.
+ 선택기: (필수) 출력 값을 결정하는 데 사용되는 JSONPath 표현식입니다.
+ 유형: (선택 사항) 선택기 필드에서 반환되는 값의 데이터 유형입니다. 유효한 유형 값은`String`, `Integer`, `Boolean`, `StringList`, `StringMap`, `MapList`입니다. 기본값은 `String`입니다.

출력 값이 지정한 데이터 유형과 일치하지 않는 경우 Automation은 데이터 유형을 변환하려고 시도합니다. 예를 들어, 반환된 값이 `Integer`이지만 지정된 `Type`은 `String`인 경우 최종 출력 값은 `String` 값입니다. 다음과 같은 유형의 반환이 지원됩니다.
+ `String` 값을 `StringList`, `Integer` 및 `Boolean`로 변환할 수 있습니다.
+ `Integer` 값을 `String`, `StringList`로 변환할 수 있습니다.
+ `Boolean` 값을 `String`, `StringList`로 변환할 수 있습니다.
+ 한 가지 요소가 포함된 `StringList`, `IntegerList` 또는 `BooleanList` 값은 `String`, `Integer` 또는 `Boolean`으로 변환할 수 없습니다.

자동화 작업에 파라미터 또는 출력을 사용하면 데이터 유형을 작업의 입력 내에서 동적으로 변경할 수 없습니다.

다음은 작업 출력을 정의하고 해당 값을 이후 작업의 입력으로 참조하는 방법을 보여주는 예제 런북입니다. 이 런북은 다음 작업을 수행합니다.
+ `aws:executeAwsApi` 작업을 사용하여 특정 Windows Server 2016 AMI의 이름을 가져오도록 Amazon EC2 DescribeImages API 작업을 호출합니다. 이미지 ID를 `ImageId`로 출력합니다.
+ `aws:executeAwsApi` 작업을 사용하여 이전 단계의 `ImageId`를 사용하는 인스턴스 하나를 시작하도록 Amazon EC2 RunInstances API 작업을 호출합니다. 인스턴스 ID를 `InstanceId`로 출력합니다.
+ ` aws:waitForAwsResourceProperty` 작업을 사용하여 인스턴스가 `running` 상태에 도달할 때까지 기다리도록 Amazon EC2 DescribeInstanceStatus API 작업을 폴링합니다. 작업 제한 시간은 60초입니다. 폴링 후 60초가 경과되었지만 인스턴스가 `running` 상태에 도달하지 못하면 단계가 시간 초과됩니다.
+ `aws:assertAwsResourceProperty` 작업으로 Amazon EC2 `DescribeInstanceStatus` API 작업을 호출하여 인스턴스가 `running` 상태에 있음을 어설션합니다. 인스턴스 상태가 `running`이 아니면 단계가 실패합니다.

```
---
description: Sample runbook using AWS API operations
schemaVersion: '0.3'
assumeRole: "{{ AutomationAssumeRole }}"
parameters:
  AutomationAssumeRole:
    type: String
    description: "(Optional) The ARN of the role that allows Automation to perform the actions on your behalf."
    default: ''
  ImageName:
    type: String
    description: "(Optional) Image Name to launch EC2 instance with."
    default: "Windows_Server-2022-English-Full-Base*"
mainSteps:
- name: getImageId
  action: aws:executeAwsApi
  inputs:
    Service: ec2
    Api: DescribeImages
    Filters:  
    - Name: "name"
      Values: 
      - "{{ ImageName }}"
  outputs:
  - Name: ImageId
    Selector: "$.Images[0].ImageId"
    Type: "String"
- name: launchOneInstance
  action: aws:executeAwsApi
  inputs:
    Service: ec2
    Api: RunInstances
    ImageId: "{{ getImageId.ImageId }}"
    MaxCount: 1
    MinCount: 1
  outputs:
  - Name: InstanceId
    Selector: "$.Instances[0].InstanceId"
    Type: "String"
- name: waitUntilInstanceStateRunning
  action: aws:waitForAwsResourceProperty
  timeoutSeconds: 60
  inputs:
    Service: ec2
    Api: DescribeInstanceStatus
    InstanceIds:
    - "{{ launchOneInstance.InstanceId }}"
    PropertySelector: "$.InstanceStatuses[0].InstanceState.Name"
    DesiredValues:
    - running
- name: assertInstanceStateRunning
  action: aws:assertAwsResourceProperty
  inputs:
    Service: ec2
    Api: DescribeInstanceStatus
    InstanceIds:
    - "{{ launchOneInstance.InstanceId }}"
    PropertySelector: "$.InstanceStatuses[0].InstanceState.Name"
    DesiredValues:
    - running
outputs:
- "launchOneInstance.InstanceId"
...
```

각각의 이전에 설명된 자동화 작업을 통해 서비스 네임스페이스, API 작업 이름, 입력 파라미터 및 출력 파라미터를 지정하여 특정 API 작업을 호출할 수 있습니다. 입력은 선택하는 API 작업에 의해 정의됩니다. 다음 [[서비스 참조(Services Reference)](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/index.html)] 페이지의 왼쪽 탐색 영역에서 서비스를 선택하여 API 작업(메서드라고도 함)을 볼 수 있습니다. 호출할 서비스에 대한 **클라이언트** 섹션에서 메서드를 선택합니다. 예를 들어 Amazon Relational Database Service(Amazon RDS)에 대한 모든 API 작업(메서드)이 [Amazon RDS 메서드](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/rds.html) 페이지에 나열됩니다.

다음 위치에서 각 자동화 작업에 대한 스키마를 볼 수 있습니다.
+ [`aws:assertAwsResourceProperty` - AWS 리소스 상태 또는 이벤트 상태 어설션](automation-action-assertAwsResourceProperty.md)
+ [`aws:executeAwsApi` - AWS API 작업 호출 및 실행](automation-action-executeAwsApi.md)
+ [`aws:waitForAwsResourceProperty` - AWS 리소스 속성 대기](automation-action-waitForAwsResourceProperty.md)

스키마에는 각 작업을 사용하기 위한 필수 필드에 대한 설명이 포함되어 있습니다.

**Selector/PropertySelector 필드 사용**  
각 Automation 작업에서는 출력 `Selector`(`aws:executeAwsApi`의 경우) 또는 `PropertySelector`(`aws:assertAwsResourceProperty` 및 `aws:waitForAwsResourceProperty`의 경우)를 지정해야 합니다. 이러한 필드는 AWS API 작업의 JSON 응답을 처리하는 데 사용됩니다. 이러한 필드는 JSONPath 구문에 사용됩니다.

다음은 `aws:executeAwsAPi` 작업과 관련하여 이 개념을 설명하는 데 도움이 되는 예제입니다.

```
---
mainSteps:
- name: getImageId
  action: aws:executeAwsApi
  inputs:
    Service: ec2
    Api: DescribeImages
    Filters:  
      - Name: "name"
        Values: 
          - "{{ ImageName }}"
  outputs:
    - Name: ImageId
      Selector: "$.Images[0].ImageId"
      Type: "String"
...
```

이 자동화는 `aws:executeAwsApi` 단계인 `getImageId`에서 `DescribeImages` API 작업을 호출하고 `ec2`의 응답을 수신합니다. 그런 다음 이 자동화는 `Selector - "$.Images[0].ImageId"`를 API 응답에 적용하고 선택한 값을 `ImageId` 변수에 할당합니다. 동일한 자동화의 다른 단계에서는 `"{{ getImageId.ImageId }}"`를 지정하여 `ImageId`의 값을 사용할 수 있습니다.

다음은 `aws:waitForAwsResourceProperty` 작업과 관련하여 이 개념을 설명하는 데 도움이 되는 예제입니다.

```
---
- name: waitUntilInstanceStateRunning
  action: aws:waitForAwsResourceProperty
  # timeout is strongly encouraged for action - aws:waitForAwsResourceProperty
  timeoutSeconds: 60
  inputs:
    Service: ec2
    Api: DescribeInstanceStatus
    InstanceIds:
    - "{{ launchOneInstance.InstanceId }}"
    PropertySelector: "$.InstanceStatuses[0].InstanceState.Name"
    DesiredValues:
    - running
...
```

이 자동화는 `aws:waitForAwsResourceProperty` 단계인 `waitUntilInstanceStateRunning`에서 `DescribeInstanceStatus` API 작업을 간접적으로 호출하고 `ec2`의 응답을 수신합니다. 그런 다음 이 자동화는 `PropertySelector - "$.InstanceStatuses[0].InstanceState.Name"`을 응답에 적용하여 지정된 반환 값이 `DesiredValues` 목록의 값(이 경우 `running`)과 일치하는지 확인합니다. 이 단계는 응답이 인스턴스 상태 `running`을 반환할 때까지 이 프로세스를 반복합니다.

## 런북에서 JSONPath 사용
<a name="automation-action-json-path"></a>

JSONPath 식은 “\$1.”로 시작하는 문자열로 JSON 요소 내에서 하나 이상의 구성 요소를 선택하는 데 사용됩니다. 다음 목록에는 Systems Manager Automation에서 지원되는 JSONPath 연산자에 대한 정보가 포함되어 있습니다.
+ **점으로 표기된 하위 객체(.)**: JSON 객체와 함께 사용합니다. 이 연산자는 특정 키의 값을 선택합니다.
+ **상세 검색(..)**: JSON 요소와 함께 사용합니다. 이 연산자는 수준별로 JSON 요소 수준을 검색하고 특정 키가 지정된 값의 목록을 선택합니다. 이 연산자의 반환 유형은 항상 JSON 배열입니다. 자동화 작업 출력 유형의 컨텍스트에서 이 연산자는 StringList 또는 MapList일 수 있습니다.
+ **배열-인덱스([ ])**: JSON 배열과 함께 사용합니다. 이 연산자는 특정 인덱스의 값을 가져옵니다.
+ **필터([?(*expression*)])**: JSON 배열과 함께 사용합니다. 이 연산자는 필터 표현식에 정의된 기준과 일치하는 JSON 배열 값을 필터링합니다. 필터 표현식에는 이 연산자(==, \$1=, >, <, >= 또는 <=)만 사용할 수 있습니다. 여러 필터 표현식을 AND(&&) 또는 OR(\$1\$1)과 결합하는 것은 지원되지 않습니다. 이 연산자의 반환 유형은 항상 JSON 배열입니다.

JSONPath 연산자를 더 명확히 이해하려면 ec2 `DescribeInstances` API 작업의 다음 JSON 응답을 검토합니다. 이 응답 아래에는 다양한 JSONPath 식을 `DescribeInstances` API 작업의 응답에 적용하여 다양한 결과를 표시하는 여러 예제가 나와 있습니다.

```
{
    "NextToken": "abcdefg",
    "Reservations": [
        {
            "OwnerId": "123456789012",
            "ReservationId": "r-abcd12345678910",
            "Instances": [
                {
                    "ImageId": "ami-12345678",
                    "BlockDeviceMappings": [
                        {
                            "Ebs": {
                                "DeleteOnTermination": true,
                                "Status": "attached",
                                "VolumeId": "vol-000000000000"
                            },
                            "DeviceName": "/dev/xvda"
                        }
                    ],
                    "State": {
                        "Code": 16,
                        "Name": "running"
                    }
                }
            ],
            "Groups": []
        },
        {
            "OwnerId": "123456789012",
            "ReservationId": "r-12345678910abcd",
            "Instances": [
                {
                    "ImageId": "ami-12345678",
                    "BlockDeviceMappings": [
                        {
                            "Ebs": {
                                "DeleteOnTermination": true,
                                "Status": "attached",
                                "VolumeId": "vol-111111111111"
                            },
                            "DeviceName": "/dev/xvda"
                        }
                    ],
                    "State": {
                        "Code": 80,
                        "Name": "stopped"
                    }
                }
            ],
            "Groups": []
        }
    ]
}
```

**JSONPath 예제 1: JSON 응답에서 특정 문자열 가져오기**

```
JSONPath: 
$.Reservations[0].Instances[0].ImageId 

Returns:
"ami-12345678"

Type: String
```

**JSONPath 예제 2: JSON 응답에서 특정 부울 가져오기**

```
JSONPath:
$.Reservations[0].Instances[0].BlockDeviceMappings[0].Ebs.DeleteOnTermination
        
Returns:
true

Type: Boolean
```

**JSONPath 예제 3: JSON 응답에서 특정 정수 가져오기**

```
JSONPath:
$.Reservations[0].Instances[0].State.Code
        
Returns:
16

Type: Integer
```

**JSONPath 예제 4: JSON 응답을 상세 검색한 다음, VolumeId에 대한 모든 값을 StringList로 가져오기** 

```
JSONPath:
$.Reservations..BlockDeviceMappings..VolumeId
        
Returns:
[
   "vol-000000000000",
   "vol-111111111111"
]

Type: StringList
```

**JSONPath 예제 5: 특정 BlockDeviceMappings 객체를 StringMap으로 가져오기**

```
JSONPath:
$.Reservations[0].Instances[0].BlockDeviceMappings[0]
        
Returns:
{
   "Ebs" : {
      "DeleteOnTermination" : true,
      "Status" : "attached",
      "VolumeId" : "vol-000000000000"
   },
   "DeviceName" : "/dev/xvda"
}

Type: StringMap
```

**JSONPath 예제 6: JSON 응답을 상세 검색한 후 모든 State 객체를 MapList로 가져오기**

```
JSONPath:
$.Reservations..Instances..State 
    
Returns:
[
   {
      "Code" : 16,
      "Name" : "running"
   },
   {
      "Code" : 80,
      "Name" : "stopped"
   }
]

Type: MapList
```

**JSONPath 예제 7: `running` 상태에 있는 인스턴스에 대한 필터링**

```
JSONPath:
$.Reservations..Instances[?(@.State.Name == 'running')]

Returns:
[
  {
    "ImageId": "ami-12345678",
    "BlockDeviceMappings": [
      {
        "Ebs": {
          "DeleteOnTermination": true,
          "Status": "attached",
          "VolumeId": "vol-000000000000"
        },
        "DeviceName": "/dev/xvda"
      }
    ],
    "State": {
      "Code": 16,
      "Name": "running"
    }
  }
]

Type: MapList
```

**JSONPath 예제 8: `running` 상태에 있지 않은 `ImageId` 인스턴스의 반환**

```
JSONPath:
$.Reservations..Instances[?(@.State.Name != 'running')].ImageId

Returns:
[
  "ami-12345678"
]

Type: StringList | String
```

# Automation을 위한 웹후크 통합 생성
<a name="creating-webhook-integrations"></a>

자동화 중 웹후크를 사용하여 메시지를 전송하려면 통합을 생성합니다. 실행서에서 `aws:invokeWebhook` 작업을 사용하여 자동화 중 통합을 호출할 수 있습니다. 웹후크를 아직 생성하지 않은 경우 [통합을 위한 웹후크 생성](#creating-webhooks) 섹션을 참조하세요. `aws:invokeWebhook` 작업에 대한 자세한 내용은 [`aws:invokeWebhook` - Automation 웹후크 통합 호출](invoke-webhook.md) 섹션을 참조하세요.

다음 절차에서 볼 수 있듯이 Systems Manager 자동화 콘솔이나 선호하는 명령줄 도구를 사용하여 통합을 생성할 수 있습니다.

## 통합 생성(콘솔)
<a name="creating-integrations-console"></a>

**Automation을 위한 통합 생성(콘솔)**

1. [https://console.aws.amazon.com/systems-manager/](https://console.aws.amazon.com/systems-manager/)에서 AWS Systems Manager 콘솔을 엽니다.

1. 왼쪽 탐색 창에서 **Automation**을 선택합니다.

1. **통합(Integrations)** 탭을 선택합니다.

1. **통합 추가(Add integration)**를 선택하고 **웹후크(Webhook)**를 선택합니다.

1. 통합에 포함할 필수 값과 선택적 값을 입력합니다.

1. **추가(Add)**를 선택하여 통합을 생성합니다.

## 통합 생성(명령줄)
<a name="creating-integrations-commandline"></a>

명령줄 도구를 사용하여 통합을 생성하려면 통합에 필요한 `SecureString` 파라미터를 생성해야 합니다. Automation은 Systems Manager의 도구인 Parameter Store에서 예약된 네임스페이스를 사용하여 통합에 대한 정보를 저장합니다. AWS Management Console을 사용하여 통합을 생성하는 경우 Automation이 이 프로세스를 자동으로 처리합니다. 네임스페이스 다음에 생성하려는 통합 유형을 지정하고 통합 이름을 지정해야 합니다. 현재 Automation은 `webhook` 유형 통합을 지원합니다.

`webhook` 유형 통합에 지원되는 필드는 다음과 같습니다.
+ 설명
+ 헤더
+ payload
+ URL

**시작하기 전 준비 사항**  
아직 하지 않은 경우 AWS Command Line Interface(AWS CLI) 또는 AWS Tools for PowerShell을 설치하고 구성합니다. 자세한 내용은 [최신 버전의 AWS CLI 설치 또는 업데이트](https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html) 및 [AWS Tools for PowerShell 설치](https://docs.aws.amazon.com/powershell/latest/userguide/pstools-getting-set-up.html)를 참조하세요.

**Automation을 위한 통합 생성(명령줄)**
+ 다음 명령을 실행하여 통합에 필요한 `SecureString` 파라미터를 생성합니다. 각 *example resource placeholder*를 사용자의 정보로 바꿉니다. `/d9d01087-4a3f-49e0-b0b4-d568d7826553/ssm/integrations/webhook/` 네임스페이스는 통합을 위해 Parameter Store에 예약되어 있습니다. 파라미터 이름은 이 네임스페이스 다음에 통합 이름을 사용해야 합니다. 예: `/d9d01087-4a3f-49e0-b0b4-d568d7826553/ssm/integrations/webhook/myWebhookIntegration`.

------
#### [ Linux & macOS ]

  ```
  aws ssm put-parameter \
      --name "/d9d01087-4a3f-49e0-b0b4-d568d7826553/ssm/integrations/webhook/myWebhookIntegration" \
      --type "SecureString" \
      --data-type "aws:ssm:integration" \
      --value '{"description": "My first webhook integration for Automation.", "url": "myWebHookURL"}'
  ```

------
#### [ Windows ]

  ```
  aws ssm put-parameter ^
      --name "/d9d01087-4a3f-49e0-b0b4-d568d7826553/ssm/integrations/webhook/myWebhookIntegration" ^
      --type "SecureString" ^
      --data-type "aws:ssm:integration" ^
      --value  "{\"description\":\"My first webhook integration for Automation.\",\"url\":\"myWebHookURL\"}"
  ```

------
#### [ PowerShell ]

  ```
  Write-SSMParameter `
      -Name "/d9d01087-4a3f-49e0-b0b4-d568d7826553/ssm/integrations/webhook/myWebhookIntegration" `
      -Type "SecureString"
      -DataType "aws:ssm:integration"
      -Value '{"description": "My first webhook integration for Automation.", "url": "myWebHookURL"}'
  ```

------

## 통합을 위한 웹후크 생성
<a name="creating-webhooks"></a>

공급자와 웹후크를 생성할 때는 다음 사항에 유의하세요.
+ 프로토콜은 HTTPS여야 합니다.
+ 사용자 정의 요청 헤더가 지원됩니다.
+ 기본 요청 본문을 지정할 수 있습니다.
+ `aws:invokeWebhook` 작업을 사용하여 통합을 호출할 때 기본 요청 본문을 재정의할 수 있습니다.

# 실행서에서 시간 제한 처리
<a name="automation-handling-timeouts"></a>

`timeoutSeconds` 속성은 모든 자동화 작업에서 공유됩니다. 이 속성을 사용하여 작업에 대한 실행 제한 시간 값을 지정할 수 있습니다. 또한 작업 시간 제한이 자동화 및 전체 실행 상태에 미치는 영향을 변경할 수 있습니다. 또한 작업에 `onFailure` 및 `isCritical` 공유 속성을 정의하여 수행할 수도 있습니다.

예를 들어 작업 시간이 초과된 경우 사용 사례에 따라 자동화가 다른 작업을 계속 진행하고 자동화의 전체 상태에 영향을 주지 않도록 해야 할 경우가 있습니다. 이 예에서는 `timeoutSeconds` 속성을 사용하여 작업 시간이 초과되기 전에 대기할 시간을 지정합니다. 그런 다음 시간 제한이 있는 경우 자동화가 이동해야 하는 작업 또는 단계를 지정합니다. 기본값 `Abort` 대신 `onFailure` 속성에 대한 `step:step name` 형식을 사용하여 값을 지정합니다. 기본적으로 작업 시간이 초과되면 자동화 실행 상태는 `Timed Out`이 됩니다. 시간 제한이 자동화 실행 상태에 영향을 미치지 않도록 하려면 `false` 속성에 `isCritical`을 지정합니다.

다음 예에서는 이 시나리오에서 설명하는 작업의 공유 속성을 정의하는 방법을 보여줍니다.

------
#### [ YAML ]

```
- name: verifyImageAvailability
  action: 'aws:waitForAwsResourceProperty'
  timeoutSeconds: 600
  isCritical: false
  onFailure: 'step:getCurrentImageState'
  inputs:
    Service: ec2
    Api: DescribeImages
    ImageIds:
      - '{{ createImage.newImageId }}'
    PropertySelector: '$.Images[0].State'
    DesiredValues:
      - available
  nextStep: copyImage
```

------
#### [ JSON ]

```
{
    "name": "verifyImageAvailability",
    "action": "aws:waitForAwsResourceProperty",
    "timeoutSeconds": 600,
    "isCritical": false,
    "onFailure": "step:getCurrentImageState",
    "inputs": {
        "Service": "ec2",
        "Api": "DescribeImages",
        "ImageIds": [
            "{{ createImage.newImageId }}"
        ],
        "PropertySelector": "$.Images[0].State",
        "DesiredValues": [
            "available"
        ]
    },
    "nextStep": "copyImage"
}
```

------

모든 자동화 작업에서 공유하는 속성에 대한 자세한 내용은 [모든 작업에서 공유하는 속성](automation-actions.md#automation-common) 섹션을 참조하세요.

# Systems Manager Automation 런북 참조
<a name="automation-documents-reference"></a>

AWS Systems Manager는 빠르게 시작할 수 있도록 미리 정의된 실행서를 제공합니다. 이러한 실행서는 Amazon Web Services, AWS Support 및 AWS Config에 의해 유지 관리됩니다. 런북 참조에서는 Systems Manager, 지원 및 AWS Config에서 제공하는 미리 정의된 런북을 각각 설명합니다. 자세한 내용은 [Systems Manager Automation 런북 참조](https://docs.aws.amazon.com/systems-manager-automation-runbooks/latest/userguide)를 참조하세요.

# 자습서
<a name="automation-tutorials"></a>

다음 자습서는 AWS Systems Manager Automation을 사용하여 일반적인 사용 사례를 해결하는 데 도움이 됩니다. 이 자습서에서는 자체 런북, Automation에서 제공하는 사전 정의된 런북 및 기타 Systems Manager 도구를 다른 AWS 서비스에 사용하는 방법을 보여줍니다.

**Contents**
+ [

# AMIs 업데이트
](automation-tutorial-update-ami.md)
  + [

# Linux AMI 업데이트
](automation-tutorial-update-patch-linux-ami.md)
  + [

## Linux AMI(AWS CLI) 업데이트
](automation-tutorial-update-ami.md#update-patch-linux-ami-cli)
  + [

# Windows Server AMI 업데이트
](automation-tutorial-update-patch-windows-ami.md)
  + [

# Automation, AWS Lambda 및 Parameter Store를 사용하여 골든 AMI 업데이트
](automation-tutorial-update-patch-golden-ami.md)
    + [

## 태스크 1: Systems Manager Parameter Store에서 파라미터 생성
](automation-tutorial-update-patch-golden-ami.md#create-parameter-ami)
    + [

## 태스크 2: AWS Lambda용 IAM 역할 생성
](automation-tutorial-update-patch-golden-ami.md#create-lambda-role)
    + [

## 작업 3: AWS Lambda 함수 생성
](automation-tutorial-update-patch-golden-ami.md#create-lambda-function)
    + [

## 태스크 4: 실행서 생성 및 AMI 패치
](automation-tutorial-update-patch-golden-ami.md#create-custom-ami-update-runbook)
  + [

# Automation 및 Jenkins를 사용하여 AMIs 업데이트
](automation-tutorial-update-patch-ami-jenkins-integration.md)
  + [

# 오토 스케일링을 위해 AMIs 업데이트
](automation-tutorial-update-patch-windows-ami-autoscaling.md)
    + [

## **PatchAMIAndUpdateASG** 런북 생성
](automation-tutorial-update-patch-windows-ami-autoscaling.md#create-autoscaling-update-runbook)
+ [

# AWS Support 셀프 서비스 런북 사용
](automation-tutorial-support-runbooks.md)
  + [

# 연결할 수 없는 인스턴스에서 EC2Rescue 도구 실행
](automation-ec2rescue.md)
    + [

## 작동 방식
](automation-ec2rescue.md#automation-ec2rescue-how)
    + [

## 시작하기 전 준비 사항
](automation-ec2rescue.md#automation-ec2rescue-begin)
      + [

### `AWSSupport-EC2Rescue`에 인스턴스에서 작업을 수행할 권한 부여
](automation-ec2rescue.md#automation-ec2rescue-access)
        + [

#### IAM 정책을 사용하여 권한 부여
](automation-ec2rescue.md#automation-ec2rescue-access-iam)
        + [

#### CloudFormation 템플릿을 사용하여 권한 부여
](automation-ec2rescue.md#automation-ec2rescue-access-cfn)
    + [

## 자동화 실행
](automation-ec2rescue.md#automation-ec2rescue-executing)
  + [

# EC2 인스턴스에서 암호 및 SSH 키 재설정
](automation-ec2reset.md)
    + [

## 작동 방식
](automation-ec2reset.md#automation-ec2reset-how)
    + [

## 시작하기 전 준비 사항
](automation-ec2reset.md#automation-ec2reset-begin)
      + [

### AWSSupport-EC2Rescue에 인스턴스에서 작업을 수행할 권한 부여
](automation-ec2reset.md#automation-ec2reset-access)
        + [

#### IAM 정책을 사용하여 권한 부여
](automation-ec2reset.md#automation-ec2reset-access-iam)
        + [

#### CloudFormation 템플릿을 사용하여 권한 부여
](automation-ec2reset.md#automation-ec2reset-access-cfn)
    + [

## 자동화 실행
](automation-ec2reset.md#automation-ec2reset-executing)
+ [

# 입력 변환기를 사용하여 Automation에 데이터 전달
](automation-tutorial-eventbridge-input-transformers.md)

# AMIs 업데이트
<a name="automation-tutorial-update-ami"></a>

다음 자습서에서는 최신 패치를 포함하도록 Amazon Machine Image(AMIs)를 업데이트하는 방법을 설명합니다.

**Topics**
+ [

# Linux AMI 업데이트
](automation-tutorial-update-patch-linux-ami.md)
+ [

## Linux AMI(AWS CLI) 업데이트
](#update-patch-linux-ami-cli)
+ [

# Windows Server AMI 업데이트
](automation-tutorial-update-patch-windows-ami.md)
+ [

# Automation, AWS Lambda 및 Parameter Store를 사용하여 골든 AMI 업데이트
](automation-tutorial-update-patch-golden-ami.md)
+ [

# Automation 및 Jenkins를 사용하여 AMIs 업데이트
](automation-tutorial-update-patch-ami-jenkins-integration.md)
+ [

# 오토 스케일링을 위해 AMIs 업데이트
](automation-tutorial-update-patch-windows-ami-autoscaling.md)

# Linux AMI 업데이트
<a name="automation-tutorial-update-patch-linux-ami"></a>

이 Systems Manager Automation 시연에서는 AWS CLI와 `AWS-UpdateLinuxAmi` 런북을 사용하여, 지정한 최신 패키지의 패치로 Linux AMI를 자동으로 업데이트하는 방법을 보여줍니다. Automation은 AWS Systems Manager의 도구입니다. `AWS-UpdateLinuxAmi` 런북은 사이트에 특정한 추가 패키지와 구성의 설치도 자동화합니다. 이 시연을 통해 Ubuntu Server, Red Hat Enterprise Linux(RHEL) 또는 Amazon Linux AMIs를 포함하여 다양한 Linux 배포를 업데이트할 수 있습니다. 지원되는 Linux 버전의 전체 목록은 [Patch Manager 필수 조건](patch-manager-prerequisites.md) 섹션을 참조하세요.

`AWS-UpdateLinuxAmi` 런북을 사용하면 JSON 또는 YAML로 런북을 만들지 않고도 이미지 유지 관리 태스크를 자동화할 수 있습니다. 다음과 같은 유형의 태스크를 수행하는 데 `AWS-UpdateLinuxAmi` 런북을 사용할 수 있습니다.
+ Amazon Linux, Red Hat Enterprise Linux 또는 Ubuntu Server Amazon Machine Image(AMI)에서 모든 배포 패키지와 Amazon 소프트웨어를 업그레이드합니다. 이는 기본 런북 동작입니다.
+ 기존 이미지에 AWS Systems Manager SSM Agent를 설치하여 Systems Manager 도구를 사용합니다. 예를 들어 AWS Systems Manager Run Command를 사용하여 원격 명령을 실행하거나 Inventory를 사용하여 소프트웨어 인벤토리를 수집할 수 있습니다.
+ 추가 소프트웨어 패키지를 설치합니다.

**시작하기 전 준비 사항**  
실행서로 작업을 시작하기 전에 역할을 구성하고, 선택적으로 Automation을 위한 EventBridge를 구성합니다. 자세한 내용은 [Automation 설정](automation-setup.md) 섹션을 참조하세요. 또한 이 시연에서는 AWS Identity and Access Management(IAM) 인스턴스 프로파일의 이름을 지정해야 합니다. IAM 인스턴스 프로파일 생성에 대한 자세한 내용은 [Systems Manager에 필요한 인스턴스 권한 구성](setup-instance-permissions.md)을 참조하세요.

`AWS-UpdateLinuxAmi` 런북은 다음 입력 파라미터를 수락합니다.


****  

| 파라미터 | 유형 | 설명 | 
| --- | --- | --- | 
|  SourceAmiId  |  문자열  |  (필수) 소스 AMI ID입니다.  | 
|  IamInstanceProfileName  |  문자열  |  (필수) [Systems Manager에 필요한 인스턴스 권한 구성](setup-instance-permissions.md)에서 생성한 IAM 인스턴스 프로파일 역할의 이름입니다. 인스턴스 프로파일 역할은 인스턴스에 대해 명령 실행 또는 서비스 시작 및 중지와 같은 작업을 수행할 권한을 자동화 서비스에 부여합니다. 실행서에서는 이 인스턴스 프로파일 역할의 이름만 사용합니다. Amazon 리소스 이름(ARN)을 지정하면 자동화가 실패합니다.  | 
|  AutomationAssumeRole  |  문자열  |  (필수) [Automation 설정](automation-setup.md)에서 생성한 IAM 서비스 역할의 이름입니다. 서비스 역할(수임 역할)은 IAM 역할을 수임하고 사용자를 대신하여 작업을 수행할 수 있는 Automation 권한을 부여합니다. 예를 들어 서비스 역할은 실행서에서 `aws:createImage` 작업을 실행할 때 Automation이 새로운 AMI를 생성할 수 있도록 합니다. 이 파라미터의 경우, 전체 ARN을 지정해야 합니다.  | 
|  TargetAmiName  |  문자열  |  (옵션) 새로 생성된 AMI의 이름입니다. 기본 이름은 원본 AMI ID, 생성 시간 및 날짜가 포함된 시스템 생성 문자열입니다.  | 
|  InstanceType  |  문자열  |  (선택 사항) 작업 영역의 호스트로 시작할 인스턴스의 유형입니다. 인스턴스 유형은 리전마다 다릅니다. 기본 형식은 t2.micro입니다.  | 
|  PreUpdateScript  |  문자열  |  (선택 사항) 업데이트가 적용되기 전에 실행할 스크립트의 URL. 기본값(\$1"none\$1")은 스크립트를 실행하지 않는 것입니다.  | 
|  PostUpdateScript  |  문자열  |  (선택 사항) 패키지 업데이트가 적용된 후에 실행할 스크립트의 URL. 기본값(\$1"none\$1")은 스크립트를 실행하지 않는 것입니다.  | 
|  IncludePackages  |  문자열  |  (선택 사항) 이름 지정된 패키지만 업데이트합니다. 기본적으로(\$1"all\$1"), 사용 가능한 업데이트는 모두 적용합니다.  | 
|  ExcludePackages  |  문자열  |  (선택 사항) 어떤 조건에서나 업데이트를 보류할 패키지의 이름입니다. 기본적으로(\$1"none\$1"), 어떤 패키지도 제외되지 않습니다.  | 

**자동화 단계**  
`AWS-UpdateLinuxAmi` 실행서에는 기본적으로 다음과 같은 자동화 작업이 포함됩니다.

**1단계: launchInstance(`aws:runInstances` 작업) **  
이 단계에서는 Amazon Elastic Compute Cloud(Amazon EC2) 사용자 데이터와 IAM 인스턴스 프로파일 역할을 사용하여 인스턴스를 시작합니다. 이때 사용자 데이터는 운영 체제에 따라 적절한 SSM Agent를 설치합니다. SSM Agent를 설치하면 Run Command, State Manager 및 Inventory와 같은 Systems Manager 도구를 사용할 수 있습니다.

**2단계: updateOSSoftware(`aws:runCommand` 작업) **  
이 단계에서는 시작된 인스턴스에서 다음 명령을 실행합니다.  
+ Amazon S3에서 업데이트 스크립트를 다운로드합니다.
+ 선택 사항인 업데이트 전 스크립트를 실행합니다.
+ 배포 패키지와 Amazon 소프트웨어를 업데이트합니다.
+ 선택 사항인 업데이트 후 스크립트를 실행합니다.
사용자가 나중에 볼 수 있도록 /tmp 폴더에 실행 로그가 저장됩니다.  
특정한 패키지 세트를 업그레이드하려면 `IncludePackages` 파라미터를 사용하여 목록을 입력하면 됩니다. 목록이 입력되면 시스템에서 해당하는 패키지와 그 종속 항목만 업데이트하려고 시도합니다. 다른 업데이트는 수행하지 않습니다. 기본적으로, *포함* 패키지를 지정하지 않으면 이 프로그램은 사용 가능한 패키지를 모두 업데이트합니다.  
특정한 패키지 세트를 업그레이드에서 제외하려면 `ExcludePackages` 파라미터에 목록을 입력하면 됩니다. 목록이 입력되면 다른 어떤 옵션을 지정했든 간에 이러한 패키지는 현재 버전으로 유지됩니다. 기본적으로, *제외* 패키지를 지정하지 않으면 어떤 패키지도 제외되지 않습니다.

**3단계: stopInstance(`aws:changeInstanceState` 작업)**  
이 단계에서는 업데이트된 인스턴스를 중지합니다.

**4단계: createImage(`aws:createImage` 작업) **  
이 단계에서는 원본 ID 및 생성 시간과 링크할 수 있는 설명 이름으로 새 AMI를 생성합니다. 예를 들어 "EC2 Automation이 \$1\$1global:DATE\$1TIME\$1\$1에 \$1\$1SourceAmiId\$1\$1에서 생성한 AMI"와 같습니다. 여기서 DATE\$1TIME 및 SourceID는 Automation의 변수를 나타냅니다.

**5단계: terminateInstance(`aws:changeInstanceState` 작업) **  
이 단계에서는 실행 인스턴스를 종료하여 자동화를 정리합니다.

**출력**  
자동화는 새로운 AMI ID를 출력으로 반환합니다.

**참고**  
기본적으로 Automation에서 `AWS-UpdateLinuxAmi` 실행서를 실행하면 시스템이 기본 VPC에 임시 인스턴스를 생성합니다(172.30.0.0/16). 기본 VPC를 삭제했다면 다음 오류 메시지를 받게 됩니다.  
`VPC not defined 400`  
이 문제를 해결하려면 `AWS-UpdateLinuxAmi` 실행서의 사본을 만들고 서브넷 ID를 지정해야 합니다. 자세한 내용은 [VPC not defined 400](automation-troubleshooting.md#automation-trbl-common-vpc) 섹션을 참조하세요.

**Automation을 이용해 패치된 AMI를 생성하려면(AWS Systems Manager)**

1. [https://console.aws.amazon.com/systems-manager/](https://console.aws.amazon.com/systems-manager/)에서 AWS Systems Manager 콘솔을 엽니다.

1. 왼쪽 탐색 창에서 **Automation**을 선택합니다.

1. **자동화 실행(Execute automation)**을 선택합니다.

1. [**Automation 문서(Automation document)**] 목록에서 [`AWS-UpdateLinuxAmi`]를 선택합니다.

1. **문서 세부 정보** 섹션에서 **문서 버전**이 **런타임 시 기본 버전**으로 설정되어 있는지 확인합니다.

1. **다음**을 선택합니다.

1. **Execution mode(실행 모드)** 섹션에서 **Simple Execution(단순 실행)**을 선택합니다.

1. **시작하기 전에** 섹션에서 수집한 정보를 [**입력 파라미터(Input parameters)**] 섹션에 입력합니다.

1. **실행**을 선택합니다. 콘솔에 자동화 실행의 상태가 표시됩니다.

워크플로가 종료된 후 업데이트된 AMI에서 테스트 인스턴스를 시작하여 변경을 확인합니다.

**참고**  
자동화 중 실패한 단계가 있으면 [**Automation 실행(Automation Executions)**] 페이지에 실패에 대한 정보가 나열됩니다. 자동화는 모든 태스크를 성공적으로 완료한 후 임시 인스턴스를 종료하도록 디자인되었습니다. 단계가 실패하면 시스템이 인스턴스를 종료하지 않을 수 있습니다. 따라서 단계가 실패하면 임시 인스턴스를 수동으로 종료합니다.

## Linux AMI(AWS CLI) 업데이트
<a name="update-patch-linux-ami-cli"></a>

이 AWS Systems Manager Automation 시연은 AWS Command Line Interface(AWS CLI)와 Systems Manager `AWS-UpdateLinuxAmi` 실행서를 사용하여 지정한 최신 패키지 버전으로 Linux Amazon Machine Image(AMI)를 자동으로 패치하는 방법을 보여줍니다. Automation은 AWS Systems Manager의 도구입니다. `AWS-UpdateLinuxAmi` 런북은 사이트에 특정한 추가 패키지와 구성의 설치도 자동화합니다. 이 시연을 통해 Ubuntu Server, Red Hat Enterprise Linux(RHEL) 또는 Amazon Linux AMIs를 포함하여 다양한 Linux 배포를 업데이트할 수 있습니다. 지원되는 Linux 버전의 전체 목록은 [Patch Manager 필수 조건](patch-manager-prerequisites.md) 섹션을 참조하세요.

`AWS-UpdateLinuxAmi` 실행서를 사용하면 JSON 또는 YAML로 실행서를 만들지 않고도 이미지 유지 관리 태스크를 자동화할 수 있습니다. 다음과 같은 유형의 태스크를 수행하는 데 `AWS-UpdateLinuxAmi` 런북을 사용할 수 있습니다.
+ Amazon Linux, RHEL 또는 Ubuntu Server Amazon Machine Image(AMI)에서 모든 배포 패키지와 Amazon 소프트웨어를 업그레이드합니다. 이는 기본 런북 동작입니다.
+ 기존 이미지에 AWS Systems Manager SSM Agent를 설치하여 Systems Manager 기능을 사용합니다. 예를 들면 AWS Systems Manager Run Command를 사용하여 원격 명령을 실행하거나 Inventory를 사용하여 소프트웨어 인벤토리를 수집할 수 있습니다.
+ 추가 소프트웨어 패키지를 설치합니다.

**시작하기 전 준비 사항**  
실행서로 작업을 시작하기 전에 역할을 구성하고, 선택적으로 Automation을 위한 EventBridge를 구성합니다. 자세한 정보는 [Automation 설정](automation-setup.md) 섹션을 참조하세요. 또한 이 시연에서는 AWS Identity and Access Management(IAM) 인스턴스 프로파일의 이름을 지정해야 합니다. IAM 인스턴스 프로파일 생성에 대한 자세한 내용은 [Systems Manager에 필요한 인스턴스 권한 구성](setup-instance-permissions.md)을 참조하세요.

`AWS-UpdateLinuxAmi` 런북은 다음 입력 파라미터를 수락합니다.


****  

| 파라미터 | 유형 | 설명 | 
| --- | --- | --- | 
|  SourceAmiId  |  String  |  (필수) 소스 AMI ID입니다. AWS Systems Manager Parameter Store *public* 파라미터를 사용하여 Linux용 Amazon EC2 AMI의 최신 ID를 자동으로 참조할 수 있습니다. 자세한 내용은 [Query for the latest Amazon Linux AMI IDs using AWS Systems Manager Parameter Store](https://aws.amazon.com/blogs/compute/query-for-the-latest-amazon-linux-ami-ids-using-aws-systems-manager-parameter-store/)를 참조하세요.  | 
|  IamInstanceProfileName  |  String  |  (필수) [Systems Manager에 필요한 인스턴스 권한 구성](setup-instance-permissions.md)에서 생성한 IAM 인스턴스 프로파일 역할의 이름입니다. 인스턴스 프로파일 역할은 인스턴스에 대해 명령 실행 또는 서비스 시작 및 중지와 같은 작업을 수행할 권한을 자동화 서비스에 부여합니다. 실행서에서는 이 인스턴스 프로파일 역할의 이름만 사용합니다.  | 
|  AutomationAssumeRole  |  String  |  (필수) [Automation 설정](automation-setup.md)에서 생성한 IAM 서비스 역할의 이름입니다. 서비스 역할(수임 역할)은 IAM 역할을 수임하고 사용자를 대신하여 작업을 수행할 수 있는 Automation 권한을 부여합니다. 예를 들어 서비스 역할은 실행서에서 `aws:createImage` 작업을 실행할 때 Automation이 새로운 AMI를 생성할 수 있도록 합니다. 이 파라미터의 경우, 전체 ARN을 지정해야 합니다.  | 
|  TargetAmiName  |  String  |  (옵션) 새로 생성된 AMI의 이름입니다. 기본 이름은 원본 AMI ID, 생성 시간 및 날짜가 포함된 시스템 생성 문자열입니다.  | 
|  InstanceType  |  String  |  (선택 사항) 작업 영역의 호스트로 시작할 인스턴스의 유형입니다. 인스턴스 유형은 리전마다 다릅니다. 기본 형식은 t2.micro입니다.  | 
|  PreUpdateScript  |  String  |  (선택 사항) 업데이트가 적용되기 전에 실행할 스크립트의 URL. 기본값(\$1"none\$1")은 스크립트를 실행하지 않는 것입니다.  | 
|  PostUpdateScript  |  String  |  (선택 사항) 패키지 업데이트가 적용된 후에 실행할 스크립트의 URL. 기본값(\$1"none\$1")은 스크립트를 실행하지 않는 것입니다.  | 
|  IncludePackages  |  String  |  (선택 사항) 이름 지정된 패키지만 업데이트합니다. 기본적으로(\$1"all\$1"), 사용 가능한 업데이트는 모두 적용합니다.  | 
|  ExcludePackages  |  String  |  (선택 사항) 어떤 조건에서나 업데이트를 보류할 패키지의 이름입니다. 기본적으로(\$1"none\$1"), 어떤 패키지도 제외되지 않습니다.  | 

**자동화 단계**  
`AWS-UpdateLinuxAmi` 실행서에는 기본적으로 다음과 같은 단계가 포함됩니다.

**1단계: launchInstance(`aws:runInstances` 작업) **  
이 단계에서는 Amazon Elastic Compute Cloud(Amazon EC2) 사용자 데이터와 IAM 인스턴스 프로파일 역할을 사용하여 인스턴스를 시작합니다. 이때 사용자 데이터는 운영 체제에 따라 적절한 SSM Agent를 설치합니다. SSM Agent를 설치하면 Run Command, State Manager 및 Inventory와 같은 Systems Manager 도구를 사용할 수 있습니다.

**2단계: updateOSSoftware(`aws:runCommand` 작업) **  
이 단계에서는 시작된 인스턴스에서 다음 명령을 실행합니다.  
+ Amazon Simple Storage Service(Amazon S3)에서 업데이트 스크립트를 다운로드합니다.
+ 선택 사항인 업데이트 전 스크립트를 실행합니다.
+ 배포 패키지와 Amazon 소프트웨어를 업데이트합니다.
+ 선택 사항인 업데이트 후 스크립트를 실행합니다.
사용자가 나중에 볼 수 있도록 /tmp 폴더에 실행 로그가 저장됩니다.  
특정한 패키지 세트를 업그레이드하려면 `IncludePackages` 파라미터를 사용하여 목록을 입력하면 됩니다. 목록이 입력되면 시스템에서 해당하는 패키지와 그 종속 항목만 업데이트하려고 시도합니다. 다른 업데이트는 수행하지 않습니다. 기본적으로, *포함* 패키지를 지정하지 않으면 이 프로그램은 사용 가능한 패키지를 모두 업데이트합니다.  
특정한 패키지 세트를 업그레이드에서 제외하려면 `ExcludePackages` 파라미터에 목록을 입력하면 됩니다. 목록이 입력되면 다른 어떤 옵션을 지정했든 간에 이러한 패키지는 현재 버전으로 유지됩니다. 기본적으로, *제외* 패키지를 지정하지 않으면 어떤 패키지도 제외되지 않습니다.

**3단계: stopInstance(`aws:changeInstanceState` 작업)**  
이 단계에서는 업데이트된 인스턴스를 중지합니다.

**4단계: createImage(`aws:createImage` 작업) **  
이 단계에서는 원본 ID 및 생성 시간과 링크할 수 있는 설명 이름으로 새 AMI를 생성합니다. 예를 들면 "EC2 자동화가 \$1\$1global:DATE\$1TIME\$1\$1에 \$1\$1SourceAmiId\$1\$1에서 생성한 AMI"와 같습니다. 여기서 DATE\$1TIME 및 SourceID는 자동화의 변수를 나타냅니다.

**5단계: terminateInstance(`aws:changeInstanceState` 작업) **  
이 단계에서는 실행 인스턴스를 종료하여 자동화를 정리합니다.

**출력**  
자동화는 새로운 AMI ID를 출력으로 반환합니다.

**참고**  
기본적으로 Automation에서 `AWS-UpdateLinuxAmi` 실행서를 실행하면 시스템이 기본 VPC에 임시 인스턴스를 생성합니다(172.30.0.0/16). 기본 VPC를 삭제했다면 다음 오류 메시지를 받게 됩니다.  
`VPC not defined 400`  
이 문제를 해결하려면 `AWS-UpdateLinuxAmi` 실행서의 사본을 만들고 서브넷 ID를 지정해야 합니다. 자세한 정보는 [VPC not defined 400](automation-troubleshooting.md#automation-trbl-common-vpc) 섹션을 참조하세요.

**Automation을 이용해 패치된 AMI를 생성하려면**

1. 아직 하지 않은 경우 AWS Command Line Interface(AWS CLI)을 설치하고 구성합니다.

   자세한 내용은 [최신 버전의 AWS CLI 설치 또는 업데이트](https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html)를 참조하세요.

1. 다음 명령을 실행하여 `AWS-UpdateLinuxAmi` 실행서를 실행합니다. 각 *example resource placeholder*를 사용자의 정보로 바꿉니다.

   ```
   aws ssm start-automation-execution \
       --document-name "AWS-UpdateLinuxAmi" \
       --parameters \
       SourceAmiId=AMI ID, \
       IamInstanceProfileName=IAM instance profile, \
       AutomationAssumeRole='arn:aws:iam::{{global:ACCOUNT_ID}}:role/AutomationServiceRole'
   ```

   이 명령으로 실행 ID가 반환됩니다. 클립보드에 이 ID를 복사합니다. 이 ID를 사용하여 자동화 상태를 확인합니다.

   ```
   {
       "AutomationExecutionId": "automation execution ID"
   }
   ```

1. AWS CLI를 사용하여 자동화를 보려면 다음 명령을 실행합니다.

   ```
   aws ssm describe-automation-executions
   ```

1. 자동화 진행 상황에 대한 세부 정보를 보려면 다음 명령을 실행합니다. *자동화 실행 ID*를 자신의 정보를 바꿉니다.

   ```
   aws ssm get-automation-execution --automation-execution-id automation execution ID
   ```

   업데이트 프로세스가 완료될 때까지 30분 이상 걸릴 수 있습니다.
**참고**  
콘솔에서 자동화 상태를 모니터링할 수도 있습니다. 목록에서 방금 실행한 자동화를 선택한 후 [**단계(Steps)**] 탭을 선택합니다. 이 탭은 자동화 작업의 상태를 보여줍니다.

워크플로가 종료된 후 업데이트된 AMI에서 테스트 인스턴스를 시작하여 변경을 확인합니다.

**참고**  
자동화 중 실패한 단계가 있으면 [**Automation 실행(Automation Executions)**] 페이지에 실패에 대한 정보가 나열됩니다. 자동화는 모든 태스크를 성공적으로 완료한 후 임시 인스턴스를 종료하도록 디자인되었습니다. 단계가 실패하면 시스템이 인스턴스를 종료하지 않을 수 있습니다. 따라서 단계가 실패하면 임시 인스턴스를 수동으로 종료합니다.

# Windows Server AMI 업데이트
<a name="automation-tutorial-update-patch-windows-ami"></a>

`AWS-UpdateWindowsAmi` 실행서를 사용하면 JSON 또는 YAML로 실행서를 만들지 않고도 Amazon Windows Amazon Machine Image(AMI)를 기반으로 이미지 유지 관리 태스크를 자동화할 수 있습니다. 이 실행서는 Windows Server 2008 R2 이상에 지원됩니다. 다음과 같은 유형의 태스크를 수행하는 데 `AWS-UpdateWindowsAmi` 실행서를 사용할 수 있습니다.
+ 모든 Windows 업데이트를 설치하고 Amazon 소프트웨어를 업그레이드합니다(기본 동작).
+ 특정 Windows 업데이트를 설치하고 Amazon 소프트웨어를 업그레이드합니다.
+ 스크립트를 이용해 AMI를 사용자 지정합니다.

**시작하기 전 준비 사항**  
실행서 작업을 시작하기 전에 액세스 권한을 부여하려는 인스턴스 프로파일의 ARN을 참조하는 `iam:PassRole` 정책을 추가하도록 [Automation에 대한 역할을 구성](automation-setup-iam.md)합니다. 필요에 따라 AWS Systems Manager의 도구인 Automation에 대해 Amazon EventBridge를 구성합니다. 자세한 내용은 [Automation 설정](automation-setup.md) 섹션을 참조하세요. 또한 이 시연에서는 AWS Identity and Access Management(IAM) 인스턴스 프로파일의 이름을 지정해야 합니다. IAM 인스턴스 프로파일 생성에 대한 자세한 내용은 [Systems Manager에 필요한 인스턴스 권한 구성](setup-instance-permissions.md)을 참조하세요.

**참고**  
AWS Systems Manager SSM Agent 업데이트는 일반적으로 서로 다른 시점에 여러 리전에 배포됩니다. AMI를 사용자 지정하거나 업데이트하려면 작업 중인 리전에 게시된 소스 AMI만 사용합니다. 그러면 해당 리전에 릴리스된 최신 SSM Agent로 작업하고 호환성 문제를 피할 수 있습니다.

`AWS-UpdateWindowsAmi` 실행서는 다음 입력 파라미터를 수락합니다.


****  

| 파라미터 | 유형 | 설명 | 
| --- | --- | --- | 
|  SourceAmiId  |  문자열  |  (필수) 소스 AMI ID입니다. Systems Manager Parameter Store *public* 파라미터를 사용하여 자동으로 최신 Windows Server AMI ID를 참조할 수 있습니다. 자세한 내용은 [AWS Systems ManagerParameter Store를 사용하여 최신 Windows AMI ID 쿼리](https://aws.amazon.com/blogs/mt/query-for-the-latest-windows-ami-using-systems-manager-parameter-store/)를 참조하세요.  | 
|  SubnetId  |  문자열  |  (선택 사항) 임시 인스턴스를 시작할 서브넷입니다. 기본 VPC를 삭제한 경우 이 파라미터의 값을 지정해야 합니다.  | 
|  IamInstanceProfileName  |  문자열  |  (필수) [Systems Manager에 필요한 인스턴스 권한 구성](setup-instance-permissions.md)에서 생성한 IAM 인스턴스 프로파일 역할의 이름입니다. 인스턴스 프로파일 역할은 인스턴스에 대해 명령 실행 또는 서비스 시작 및 중지와 같은 작업을 수행할 권한을 자동화 서비스에 부여합니다. 실행서에서는 이 인스턴스 프로파일 역할의 이름만 사용합니다.  | 
|  AutomationAssumeRole  |  문자열  |  (필수) [Automation 설정](automation-setup.md)에서 생성한 IAM 서비스 역할의 이름입니다. 서비스 역할(수임 역할)은 IAM 역할을 수임하고 사용자를 대신하여 작업을 수행할 수 있는 Automation 권한을 부여합니다. 예를 들어 서비스 역할은 실행서에서 `aws:createImage` 작업을 실행할 때 Automation이 새로운 AMI를 생성할 수 있도록 합니다. 이 파라미터의 경우, 전체 ARN을 지정해야 합니다.  | 
|  TargetAmiName  |  문자열  |  (옵션) 새로 생성된 AMI의 이름입니다. 기본 이름은 원본 AMI ID, 생성 시간 및 날짜가 포함된 시스템 생성 문자열입니다.  | 
|  InstanceType  |  문자열  |  (선택 사항) 작업 영역의 호스트로 시작할 인스턴스의 유형입니다. 인스턴스 유형은 리전마다 다릅니다. 기본 형식은 t2.medium입니다.  | 
|  PreUpdateScript  |  문자열  |  (옵션) AMI를 업데이트하기 전에 실행할 스크립트. 실행서 또는 런타임에 파라미터로 스크립트를 입력합니다.  | 
|  PostUpdateScript  |  문자열  |  (옵션) AMI를 업데이트한 후에 실행할 스크립트. 실행서 또는 런타임에 파라미터로 스크립트를 입력합니다.  | 
|  IncludeKbs  |  문자열  |  (선택 사항) 포함시킬 하나 이상의 Microsoft Knowledge Base(KB) 문서 ID를 지정합니다. 쉼표로 분리된 값을 사용하여 여러 ID를 설치할 수 있습니다. 유효한 형식: KB9876543 또는 9876543.  | 
|  ExcludeKbs  |  문자열  |  (선택 사항) 제외할 하나 이상의 Microsoft Knowledge Base(KB) 문서 ID를 지정합니다. 쉼표로 분리된 값을 사용하여 여러 ID를 제외할 수 있습니다. 유효한 형식: KB9876543 또는 9876543.  | 
|  Categories  |  문자열  |  (선택 사항)하나 이상의 업데이트 범주를 지정합니다. 쉼표로 분리된 값을 사용하여 범주를 필터링할 수 있습니다. 옵션: 중요 업데이트, 보안 업데이트, 정의 업데이트, 업데이트 롤업, 서비스 팩, 도구, 업데이트 또는 드라이버. 유효한 형식에는 중요 업데이트 등 단일 입력이 포함됩니다. 또는 중요 업데이트,보안 업데이트,정의 업데이트처럼 쉼표로 구분된 목록을 지정할 수 있습니다.  | 
|  SeverityLevels  |  문자열  |  (선택 사항) 업데이트와 연결되는 하나 이상의 MSRC 심각도를 지정합니다. 쉼표로 분리된 값을 사용하여 심각도를 필터링할 수 있습니다. 옵션: 심각, 중요, 낮음, 보통 또는 비지정. 유효한 형식에는 심각 등 단일 입력이 포함됩니다. 또는 심각,중요,낮음처럼 쉼표로 구분된 목록을 지정할 수 있습니다.  | 

**자동화 단계**  
`AWS-UpdateWindowsAmi` 실행서에는 기본적으로 다음과 같은 단계가 포함됩니다.

**1단계: launchInstance(`aws:runInstances` 작업)**  
이 단계는 지정된 `SourceAmiID`의 IAM 인스턴스 프로파일 역할을 사용하여 인스턴스를 시작합니다.

**2단계: runPreUpdateScript(`aws:runCommand` 작업)**  
이 단계에서는 업데이트가 설치되기 전에 실행되는 문자열로 스크립트를 지정할 수 있습니다.

**3단계: updateEC2Config(`aws:runCommand` 작업)**  
이 단계는 `AWS-InstallPowerShellModule` 실행서를 사용하여 AWS 퍼블릭 PowerShell 모듈을 다운로드합니다. Systems Manager는 SHA-256 해시를 사용하여 모듈의 무결성을 확인합니다. 그런 다음 Systems Manager는 운영 체제를 확인하여 EC2Config 또는 EC2Launch를 업데이트할지 결정합니다. EC2Config는 Windows Server 2008 R2에서 Windows Server 2012 R2까지 실행됩니다. EC2Launch는 Windows Server 2016에서 실행됩니다.

**4단계: updateSSMAgent(`aws:runCommand` 작업)**  
이 단계는 `AWS-UpdateSSMAgent` 실행서를 사용하여 SSM Agent를 업데이트합니다.

**5단계: updateAWSPVDriver(`aws:runCommand` 작업)**  
이 단계는 `AWS-ConfigureAWSPackage` 실행서를 사용하여 AWS PV 드라이버를 업데이트합니다.

**6단계: updateAwsEnaNetworkDriver `aws:runCommand` 작업)**  
이 단계는 `AWS-ConfigureAWSPackage` 실행서를 사용하여 AWS ENA 네트워크 드라이버를 업데이트합니다.

**7단계: installWindowsUpdates(`aws:runCommand` 작업) **  
이 단계는 `AWS-InstallWindowsUpdates` 실행서를 사용하여 Windows 업데이트를 설치합니다. 기본적으로 Systems Manager는 누락된 모든 업데이트를 검색하고 설치합니다. 파라미터 `IncludeKbs`, `ExcludeKbs`, `Categories` 또는 `SeverityLevels` 중 하나를 지정하여 기본 동작을 변경할 수 있습니다.

**8단계: runPostUpdateScript(`aws:runCommand` 작업)**  
이 단계에서는 업데이트가 설치된 후에 실행되는 문자열로 스크립트를 지정할 수 있습니다.

**9단계: runSysprepGeneralize(`aws:runCommand` 작업) **  
이 단계는 `AWS-InstallPowerShellModule` 실행서를 사용하여 AWS 퍼블릭 PowerShell 모듈을 다운로드합니다. Systems Manager는 SHA-256 해시를 사용하여 모듈의 무결성을 확인합니다. 그런 다음 Systems Manager는 EC2Launch(Windows Server 2016) 또는 EC2Config(Windows Server 2008 R2\$12012 R2)에 대해 AWS 지원 방법을 사용하여 sysprep을 실행합니다.

**10단계: stopInstance(`aws:changeInstanceState` 작업) **  
이 단계에서는 업데이트된 인스턴스를 중지합니다.

**11단계: createImage(`aws:createImage` 작업) **  
이 단계에서는 원본 ID 및 생성 시간과 링크할 수 있는 설명 이름으로 새 AMI를 생성합니다. 예를 들면 "EC2 자동화가 \$1\$1global:DATE\$1TIME\$1\$1에 \$1\$1SourceAmiId\$1\$1에서 생성한 AMI"와 같습니다. 여기서 DATE\$1TIME 및 SourceID는 자동화의 변수를 나타냅니다.

**12단계: TerminateInstance(`aws:changeInstanceState` 작업) **  
이 단계에서는 실행 인스턴스를 종료하여 자동화를 정리합니다.

**출력**  
이 섹션에서는 다양한 단계의 출력 또는 원하는 파라미터의 값을 자동화 출력으로 지정할 수 있습니다. 기본적으로 출력은 실행에 의해 생성되어 업데이트된 Windows AMI의 ID입니다.

**참고**  
기본적으로 Automation이 `AWS-UpdateWindowsAmi` 실행서를 실행하고 임시 인스턴스를 생성하면 시스템이 기본 VPC를 사용합니다(172.30.0.0/16). 기본 VPC를 삭제했다면 다음 오류 메시지를 받게 됩니다.  
VPC not defined 400  
이 문제를 해결하려면 `AWS-UpdateWindowsAmi` 실행서의 사본을 만들고 서브넷 ID를 지정해야 합니다. 자세한 내용은 [VPC not defined 400](automation-troubleshooting.md#automation-trbl-common-vpc) 섹션을 참조하세요.

**Automation을 이용해 패치된 Windows AMI를 생성하려면**

1. 아직 하지 않은 경우 AWS Command Line Interface(AWS CLI)을 설치하고 구성합니다.

   자세한 내용은 [최신 버전의 AWS CLI 설치 또는 업데이트](https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html)를 참조하세요.

1. 다음 명령을 실행하여 `AWS-UpdateWindowsAmi` 실행서를 실행합니다. 각 *example resource placeholder*를 사용자의 정보로 바꿉니다. 아래 예제 명령은 최신 Amazon EC2 AMI를 사용하여 적용해야 하는 패치의 개수를 최소화합니다. 이 명령을 두 번 이상 실행하면 `targetAMIname`에 고유한 값을 지정해야 합니다. AMI 이름은 고유해야 합니다.

   ```
   aws ssm start-automation-execution \
       --document-name="AWS-UpdateWindowsAmi" \
       --parameters SourceAmiId='AMI ID',IamInstanceProfileName='IAM instance profile',AutomationAssumeRole='arn:aws:iam::{{global:ACCOUNT_ID}}:role/AutomationServiceRole'
   ```

   이 명령으로 실행 ID가 반환됩니다. 클립보드에 이 ID를 복사합니다. 이 ID를 사용하여 자동화 상태를 확인합니다.

   ```
   {
       "AutomationExecutionId": "automation execution ID"
   }
   ```

1. AWS CLI를 사용하여 자동화를 보려면 다음 명령을 실행합니다.

   ```
   aws ssm describe-automation-executions
   ```

1. 자동화 진행 상황에 대한 세부 정보를 보려면 다음 명령을 실행합니다.

   ```
   aws ssm get-automation-execution 
       --automation-execution-id automation execution ID
   ```

**참고**  
적용된 패치 수에 따라 이 샘플 자동화에서 실행된 Windows 패치 프로세스가 완료되는 데 30분 이상의 시간이 소요될 수 있습니다.

# Automation, AWS Lambda 및 Parameter Store를 사용하여 골든 AMI 업데이트
<a name="automation-tutorial-update-patch-golden-ami"></a>

다음 예시에는 조직이 Amazon Elastic Compute Cloud(Amazon EC2) AMIs에서 구축하는 것이 아니라 자체적인 고유의 AMIs를 유지 관리하고 정기적으로 패치하는 모델을 사용합니다.

다음 절차에서는 이미 *최신* AMI로 간주되는 AMI에 운영 체제(OS) 패치를 자동으로 적용하는 방법을 보여줍니다. 이 예제에서 `SourceAmiId` 파라미터의 기본값은 `latestAmi`라는 AWS Systems Manager Parameter Store 파라미터로 정의됩니다. `latestAmi` 값은 자동화가 끝날 때 호출되는 AWS Lambda 함수를 통해 업데이트됩니다. 이 Automation 프로세스의 결과로 최신 AMI에 패치가 항상 적용되기 때문에 AMIs를 패치하는 데 소비되는 시간과 노력이 최소화됩니다. Parameter Store와 Automation은 AWS Systems Manager의 도구입니다.

**시작하기 전 준비 사항**  
Automation 역할 및 Automation을 위한 Amazon EventBridge(옵션)를 구성합니다. 자세한 내용은 [Automation 설정](automation-setup.md) 섹션을 참조하세요.

**Topics**
+ [

## 태스크 1: Systems Manager Parameter Store에서 파라미터 생성
](#create-parameter-ami)
+ [

## 태스크 2: AWS Lambda용 IAM 역할 생성
](#create-lambda-role)
+ [

## 작업 3: AWS Lambda 함수 생성
](#create-lambda-function)
+ [

## 태스크 4: 실행서 생성 및 AMI 패치
](#create-custom-ami-update-runbook)

## 태스크 1: Systems Manager Parameter Store에서 파라미터 생성
<a name="create-parameter-ami"></a>

다음 정보를 사용하는 문자열 파라미터를 Parameter Store에 생성
+ **이름**: `latestAmi`.
+ **값**: AMI ID입니다. 예: ` ami-188d6e0e`

Parameter Store 문자열 파라미터를 생성하는 방법에 대한 자세한 내용은 [Systems Manager에서 Parameter Store 파라미터 생성](sysman-paramstore-su-create.md) 섹션을 참조하세요.

## 태스크 2: AWS Lambda용 IAM 역할 생성
<a name="create-lambda-role"></a>

다음 절차를 사용하여 AWS Lambda용 IAM 서비스 역할을 생성합니다. 이 정책은 Lambda 함수와 Systems Manager를 사용하여 `latestAmi` 파라미터의 값을 업데이트할 Lambda 권한을 부여합니다.

**Lambda용 IAM 서비스 역할을 생성하려면**

1. AWS Management Console에 로그인하여 [https://console.aws.amazon.com/iam/](https://console.aws.amazon.com/iam/)에서 IAM 콘솔을 엽니다.

1. 탐색 창에서 **정책**을 선택한 후 **정책 생성**을 선택합니다.

1. **JSON** 탭을 선택합니다.

1. 기본 콘텐츠를 다음과 같은 정책으로 바꿉니다. 각 *리소스 자리 표시자 예*를 자신의 정보로 바꿉니다.

------
#### [ JSON ]

****  

   ```
   {
       "Version":"2012-10-17",		 	 	 
       "Statement": [
           {
               "Effect": "Allow",
               "Action": "logs:CreateLogGroup",
               "Resource": "arn:aws:logs:us-east-1:111122223333:*"
           },
           {
               "Effect": "Allow",
               "Action": [
                   "logs:CreateLogStream",
                   "logs:PutLogEvents"
               ],
               "Resource": [
                   "arn:aws:logs:us-east-1:111122223333:log-group:/aws/lambda/function name:*"
               ]
           }
       ]
   }
   ```

------

1. **다음: 태그**를 선택합니다.

1. (선택 사항) 이 정책에 대한 액세스를 구성, 추적 또는 제어할 태그-키 값 페어를 하나 이상 추가합니다.

1. **다음: 검토**를 선택합니다.

1. **Review policy(정책 검토)** 페이지에서 **Name(이름)**에 인라인 정책 이름을 입력합니다(예: **amiLambda**)

1. **정책 생성**을 선택합니다.

1. 2단계와 3단계를 반복합니다.

1. 다음 정책을 붙여넣습니다. 각 *example resource placeholder*를 사용자의 정보로 바꿉니다.

------
#### [ JSON ]

****  

   ```
   {
       "Version":"2012-10-17",		 	 	 
       "Statement": [
           {
               "Effect": "Allow",
               "Action": "ssm:PutParameter",
               "Resource": "arn:aws:ssm:us-east-1:111122223333:parameter/latestAmi"
           },
           {
               "Effect": "Allow",
               "Action": "ssm:DescribeParameters",
               "Resource": "*"
           }
       ]
   }
   ```

------

1. **다음: 태그**를 선택합니다.

1. (선택 사항) 이 정책에 대한 액세스를 구성, 추적 또는 제어할 태그-키 값 페어를 하나 이상 추가합니다.

1. **다음: 검토**를 선택합니다.

1. **Review policy(정책 검토)** 페이지에서 **Name(이름)**에 인라인 정책 이름을 입력합니다(예: **amiParameter**)

1. **정책 생성**을 선택합니다.

1. 탐색 창에서 **역할**을 선택한 후 **역할 생성**을 선택합니다.

1. **사용 사례**에서 **Lambda**를 선택한 후 **다음**을 선택합니다.

1. **권한 추가** 페이지의 **검색** 필드를 사용하여 앞서 생성한 두 정책을 찾습니다.

1. 정책 옆 확인란을 선택하고 **다음**을 선택합니다.

1. **역할 이름**에 새 역할의 이름(예: **lambda-ssm-role** 또는 자신이 선호하는 다른 이름)을 입력합니다.
**참고**  
다양한 주체가 역할을 참조할 수 있기 때문에 역할이 생성된 후에는 역할 이름을 변경할 수 없습니다.

1. (선택 사항) 이 역할에 대한 액세스를 구성, 추적 또는 제어할 태그 키-값 페어를 하나 이상 추가한 후 **역할 생성**을 선택합니다.

## 작업 3: AWS Lambda 함수 생성
<a name="create-lambda-function"></a>

다음 절차를 사용하여 `latestAmi` 파라미터의 값을 자동으로 업데이트하는 Lambda 함수를 생성합니다.

**Lambda 함수 생성하려면**

1. AWS Management Console에 로그인하고 [https://console.aws.amazon.com/lambda/](https://console.aws.amazon.com/lambda/)에서 AWS Lambda 콘솔을 엽니다.

1. **함수 생성**을 선택합니다.

1. **함수 생성** 페이지에서 **처음부터 새로 작성**을 선택합니다.

1. [**함수 이름**]에 **Automation-UpdateSsmParam**을 입력합니다.

1. **런타임**에서 **Python 3.11**를 선택합니다.

1. **아키텍처**에서 함수를 실행하는 데 사용할 Lambda용 컴퓨터 프로세서 유형(**x86\$164** 또는 **arm64**)을 선택합니다.

1. **권한** 섹션에서 **기본 실행 역할 변경**을 확장합니다.

1. [**기존 역할 사용(Use an existing role)**]을 선택하고 태스크 2에서 생성한 Lambda에 대한 서비스 역할을 선택합니다.

1. **함수 생성**을 선택합니다.

1. **코드 소스** 영역의 **lambda\$1function** 탭에서 필드에 미리 채워진 코드를 삭제하고 다음 코드 샘플을 붙여 넣습니다.

   ```
   from __future__ import print_function
   
   import json
   import boto3
   
   print('Loading function')
   
   
   #Updates an SSM parameter
   #Expects parameterName, parameterValue
   def lambda_handler(event, context):
       print("Received event: " + json.dumps(event, indent=2))
   
       # get SSM client
       client = boto3.client('ssm')
   
       #confirm  parameter exists before updating it
       response = client.describe_parameters(
          Filters=[
             {
              'Key': 'Name',
              'Values': [ event['parameterName'] ]
             },
           ]
       )
   
       if not response['Parameters']:
           print('No such parameter')
           return 'SSM parameter not found.'
   
       #if parameter has a Description field, update it PLUS the Value
       if 'Description' in response['Parameters'][0]:
           description = response['Parameters'][0]['Description']
           
           response = client.put_parameter(
             Name=event['parameterName'],
             Value=event['parameterValue'],
             Description=description,
             Type='String',
             Overwrite=True
           )
       
       #otherwise just update Value
       else:
           response = client.put_parameter(
             Name=event['parameterName'],
             Value=event['parameterValue'],
             Type='String',
             Overwrite=True
           )
           
       responseString = 'Updated parameter %s with value %s.' % (event['parameterName'], event['parameterValue'])
           
       return responseString
   ```

1. **파일, 저장**을 선택합니다.

1. Lambda 함수를 테스트하려면 **테스트** 메뉴에서 **테스트 이벤트 구성**을 선택합니다.

1. **이벤트 이름**에 테스트 이벤트의 이름을 입력합니다(예: **MyTestEvent**).

1. 기존 텍스트를 다음 JSON으로 바꿉니다. *AMI ID*를 자신의 정보로 바꾸어 `latestAmi` 파라미터 값을 설정합니다.

   ```
   {
      "parameterName":"latestAmi",
      "parameterValue":"AMI ID"
   }
   ```

1. **저장**을 선택합니다.

1. 함수를 테스트하려면 **테스트**를 선택합니다. **실행 결과** 탭에서 업데이트에 대한 다른 세부 정보와 함께 상태가 **성공**으로 보고되어야 합니다.

## 태스크 4: 실행서 생성 및 AMI 패치
<a name="create-custom-ami-update-runbook"></a>

다음 절차를 사용하여 **latestAmi** 파라미터에 지정한 AMI를 패치하는 실행서를 생성하고 실행합니다. 자동화가 완료되면 **latestAmi** 값이 새로 패치된 AMI의 ID로 업데이트됩니다. 이후 자동화는 이전 실행에서 생성된 AMI를 사용합니다.

**실행서를 생성하고 실행하려면**

1. AWS Systems Manager 콘솔([https://console.aws.amazon.com/systems-manager/](https://console.aws.amazon.com/systems-manager/))을 엽니다.

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

1. **문서 생성**에서 **Automation**을 선택합니다.

1. **이름**에 **UpdateMyLatestWindowsAmi**를 입력합니다.

1. **편집기** 탭을 선택하고 **편집**을 선택합니다.

1. 메시지가 나타나면 **확인**을 선택합니다.

1. **문서 편집기** 필드에서 기본 콘텐츠를 다음 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: The ID of the AMI you want to patch.
       default: '{{ ssm:latestAmi }}'
     SubnetId:
       type: String
       description: The ID of the subnet where the instance from the SourceAMI parameter is launched.
     SecurityGroupIds:
       type: StringList
       description: The IDs of the security groups to associate with the instance that's launched from the SourceAMI parameter.
     NewAMI:
       type: String
       description: The name of of newly patched AMI.
       default: 'patchedAMI-{{global:DATE_TIME}}'
     InstanceProfile:
       type: String
       description: 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: updateSsmParam
       action: aws:invokeLambdaFunction
       timeoutSeconds: 1200
       maxAttempts: 1
       onFailure: Abort
       inputs:
           FunctionName: Automation-UpdateSsmParam
           Payload: '{"parameterName":"latestAmi", "parameterValue":"{{createImage.ImageId}}"}'
   outputs:
   - createImage.ImageId
   ```

1. **Create automation(자동화 생성)**을 선택합니다.

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

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

1. **UpdateMyLatestWindowsAmi** 런북을 검색하고 **UpdateMyLatestWindowsAmi** 카드에서 버튼을 선택합니다.

1. **다음**을 선택합니다.

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

1. 입력 파라미터에 대한 값을 지정합니다.

1. **실행**을 선택합니다.

1. 자동화가 완료된 후 탐색 창에서 **Parameter Store**를 선택하고 `latestAmi`의 새 값이 자동화에서 반환된 값과 일치하는지 확인합니다. 새 AMI ID가 Amazon EC2 콘솔의 [**AMI(AMIs)**] 섹션에 있는 Automation 출력과 일치하는지도 확인할 수 있습니다.

# Automation 및 Jenkins를 사용하여 AMIs 업데이트
<a name="automation-tutorial-update-patch-ami-jenkins-integration"></a>

조직에서 CI/CD 파이프라인에 Jenkins 소프트웨어를 사용하는 경우 Automation을 사후 빌드 단계로 추가하여 Amazon Machine Images(AMIs)에 애플리케이션 릴리스를 미리 설치할 수 있습니다. Automation은 AWS Systems Manager의 도구입니다. 또한 Jenkins 예약 기능을 사용하여 Automation을 호출하고 고유의 OS(운영 체제) 패치 케이던스를 만들 수 있습니다.

아래 예제에서는 온프레미스 또는 Amazon Elastic Compute Cloud(Amazon EC2)에서 실행 중인 Jenkins 서버에서 Automation을 호출하는 방법을 보여줍니다. 인증을 위해 Jenkins 서버는 예제에서 생성하고 인스턴스 프로파일에 연결하는 IAM 정책을 기반으로 한 AWS 자격 증명을 사용합니다.

**참고**  
인스턴스를 구성할 때는 반드시 Jenkins 보안 모범 사례를 따르세요.

**시작하기 전 준비 사항**  
Jenkins를 사용하여 Automation을 구성하기 전에 다음 작업을 완료합니다.
+ [Automation, AWS Lambda 및 Parameter Store를 사용하여 골든 AMI 업데이트](automation-tutorial-update-patch-golden-ami.md) 예제를 완료합니다. 다음 예제에서는 해당 예제에서 만든 **UpdateMyLatestWindowsAmi** 실행서를 사용합니다.
+ Automation을 위한 IAM 역할을 구성합니다. 자동화 처리를 위해 Systems Manager에 인스턴스 프로파일 역할과 서비스 역할 ARN이 필요합니다. 자세한 내용은 [Automation 설정](automation-setup.md) 섹션을 참조하세요.

**Jenkins 서버의 IAM 정책 생성**

1. AWS Management Console에 로그인하여 [https://console.aws.amazon.com/iam/](https://console.aws.amazon.com/iam/)에서 IAM 콘솔을 엽니다.

1. 탐색 창에서 **정책**을 선택한 후 **정책 생성**을 선택합니다.

1. **JSON** 탭을 선택합니다.

1. 각 *example resource placeholder*를 사용자의 정보로 바꿉니다.

------
#### [ JSON ]

****  

   ```
   {
       "Version":"2012-10-17",		 	 	 
       "Statement": [
           {
               "Effect": "Allow",
               "Action": "ssm:StartAutomationExecution",
               "Resource": [
                   "arn:aws:ssm:us-east-1:111122223333:document/UpdateMyLatestWindowsAmi",
                   "arn:aws:ssm:us-east-1:111122223333:automation-execution/*"
               ]
           }
       ]
   }
   ```

------

1. **Review policy**(정책 검토)를 선택합니다.

1. **Review policy(정책 검토)** 페이지에서 **Name(이름)**에 인라인 정책 이름을 입력합니다(예: **JenkinsPolicy**)

1. **정책 생성**을 선택합니다.

1. 탐색 창에서 **역할**을 선택합니다.

1. Jenkins 서버에 연결된 인스턴스 프로파일을 선택합니다.

1. **권한** 탭에서 **권한 추가**, **정책 연결**을 선택합니다.

1. **기타 권한 정책** 섹션에서 이전 단계에서 생성한 정책의 이름을 입력합니다. **JenkinsPolicy**를 예로 들 수 있습니다.

1. 정책 옆의 확인란을 선택한 다음 **정책 연결**을 선택합니다.

다음 절차를 사용하여 AWS CLI 서버에서 Jenkins를 구성합니다.

**자동화를 위해 Jenkins 서버를 구성하려면**

1. 기본 브라우저를 사용하여 포트 8080에서 Jenkins 서버에 연결하고 관리 인터페이스에 액세스합니다.

1. `/var/lib/jenkins/secrets/initialAdminPassword`에서 찾은 암호를 입력합니다. 암호를 표시하려면 다음 명령을 실행합니다.

   ```
   sudo cat /var/lib/jenkins/secrets/initialAdminPassword
   ```

1. Jenkins 설치 스크립트가 **Jenkins 사용자 지정** 페이지로 안내합니다. [**제안된 플러그인 설치(Install suggested plugins)**]를 선택합니다.

1. 설치가 완료되면 **관리자 자격 증명**, **자격 증명 저장**, **Jenkins를 사용하여 시작**을 차례로 선택합니다.

1. 왼쪽 탐색 창에서 **Jenkins 관리**를 선택한 후 **플러그인 관리**를 선택합니다.

1. [**사용 가능(Available)**] 탭을 선택하고 **Amazon EC2 plugin**을 입력합니다.

1. **Amazon EC2 plugin** 확인란을 선택하고 [**다시 시작하지 않고 설치(Install without restart)**]를 선택합니다.

1. 설치가 완료되면 [**맨 위 페이지로 돌아가기(Go back to the top page)**]를 선택합니다.

1. **Jenkins 관리**를 선택한 다음 **노드 및 클라우드 관리**를 선택합니다.

1. **클라우드 구성** 섹션에서 **새 클라우드 추가**를 선택한 다음 **Amazon EC2**를 선택합니다.

1. 나머지 필드에 정보를 입력합니다. **EC2 인스턴스 프로파일을 사용하여 자격 증명 가져오기** 옵션을 선택해야 합니다.

다음 절차를 사용하여 Automation을 호출하도록 Jenkins 프로젝트를 구성합니다.

**Automation을 호출하도록 Jenkins 서버를 구성하려면**

1. 웹 브라우저를 사용하여 Jenkins 콘솔을 엽니다.

1. 자동화로 구성할 프로젝트를 선택한 후 **구성**을 선택합니다.

1. **빌드** 탭에서 **빌드 단계 추가**를 선택합니다.

1. **Execute shell(셸 실행)** 또는 **Execute Windows batch command(Windows 배치 명령 실행)**를 선택합니다(운영 체제에 따라 선택).

1. **명령(Command)** 필드에서 다음과 같이 AWS CLI 명령을 실행합니다. 각 *example resource placeholder*를 사용자의 정보로 바꿉니다.

   ```
   aws ssm start-automation-execution \
           --document-name runbook name \
           --region AWS 리전 of your source AMI \
           --parameters runbook parameters
   ```

   다음 예제 명령에서는 **UpdateMyLatestWindowsAmi** 실행서와 [Automation, AWS Lambda 및 Parameter Store를 사용하여 골든 AMI 업데이트](automation-tutorial-update-patch-golden-ami.md)에서 생성한 Systems Manager 파라미터 `latestAmi`를 사용합니다.

   ```
   aws ssm start-automation-execution \
           --document-name UpdateMyLatestWindowsAmi \
           --parameters \
               "sourceAMIid='{{ssm:latestAmi}}'"
           --region region
   ```

   Jenkins에서 이 명령은 다음 스크린샷의 예제와 같이 표시됩니다.  
![\[Jenkins 소프트웨어의 샘플 명령.\]](http://docs.aws.amazon.com/ko_kr/systems-manager/latest/userguide/images/sysman-ami-jenkins2.png)

1. Jenkins 프로젝트에서 **지금 빌드**를 선택합니다. Jenkins는 다음 예제와 비슷한 출력 결과를 반환합니다.  
![\[Jenkins 소프트웨어의 샘플 명령 출력.\]](http://docs.aws.amazon.com/ko_kr/systems-manager/latest/userguide/images/sysman-ami-jenkins.png)

# 오토 스케일링을 위해 AMIs 업데이트
<a name="automation-tutorial-update-patch-windows-ami-autoscaling"></a>

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

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

**시작하기 전 준비 사항**  
이 예제를 시작하기 전에 다음 작업을 완료합니다.
+ AWS Systems Manager의 도구인 Automation을 위한 IAM 역할을 구성합니다. 자동화 처리를 위해 Systems Manager에 인스턴스 프로파일 역할과 서비스 역할 ARN이 필요합니다. 자세한 내용은 [Automation 설정](automation-setup.md) 섹션을 참조하세요.

## **PatchAMIAndUpdateASG** 런북 생성
<a name="create-autoscaling-update-runbook"></a>

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

**실행서를 생성하고 실행하려면**

1. AWS Systems Manager 콘솔([https://console.aws.amazon.com/systems-manager/](https://console.aws.amazon.com/systems-manager/))을 엽니다.

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

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. 탐색 창에서 **Automation**(자동화)을 선택한 후 **Execute automation**(자동화 실행)을 선택합니다.

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 Groups)**]을 선택합니다. Auto Scaling 그룹에서 새로운 시작 템플릿이 사용되는지 확인합니다.

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

# AWS Support 셀프 서비스 런북 사용
<a name="automation-tutorial-support-runbooks"></a>

이 섹션에서는 AWS Support 팀에서 만든 몇 가지 셀프 서비스 자동화를 사용하는 방법을 설명합니다. 이러한 자동화는 AWS 리소스를 관리하는 데 도움이 됩니다.

**Support Automation Workflows**  
SAW(Support Automation Workflows)는 AWS Support 팀에서 작성하고 유지 관리하는 Automation 실행서입니다. 이러한 실행서는 AWS 리소스의 일반적인 문제를 해결하고, 네트워크 문제를 사전에 모니터링 및 식별하고, 로그를 수집 및 분석하는 등의 작업을 수행하는 데 도움이 됩니다.

SAW 실행서는 **`AWSSupport`** 접두사를 사용합니다. 예를 들어 [https://docs.aws.amazon.com/systems-manager-automation-runbooks/latest/userguide/automation-awssupport-activatewindowswithamazonlicense.html](https://docs.aws.amazon.com/systems-manager-automation-runbooks/latest/userguide/automation-awssupport-activatewindowswithamazonlicense.html)입니다.

또한 Business Support\$1 이상의 AWS Support 플랜을 사용하는 고객은 **`AWSPremiumSupport`** 접두사를 사용하는 런북에도 액세스할 수 있습니다. 예를 들어 [https://docs.aws.amazon.com/systems-manager-automation-runbooks/latest/userguide/automation-awspremiumsupport-troubleshootEC2diskusage.html](https://docs.aws.amazon.com/systems-manager-automation-runbooks/latest/userguide/automation-awspremiumsupport-troubleshootEC2diskusage.html)입니다.

AWS Support에 대한 자세한 내용은 [AWS Support 시작하기](https://docs.aws.amazon.com/awssupport/latest/user/getting-started.html)를 참조하세요.

**Topics**
+ [

# 연결할 수 없는 인스턴스에서 EC2Rescue 도구 실행
](automation-ec2rescue.md)
+ [

# EC2 인스턴스에서 암호 및 SSH 키 재설정
](automation-ec2reset.md)

# 연결할 수 없는 인스턴스에서 EC2Rescue 도구 실행
<a name="automation-ec2rescue"></a>

EC2Rescue를 사용하면 Linux 및 Windows Server용 Amazon Elastic Compute Cloud(Amazon EC2) 인스턴스에 대한 문제를 진단하고 해결할 수 있습니다. [Linux Server용 EC2Rescue 사용](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Linux-Server-EC2Rescue.html) 및 [Windows Server용 EC2Rescue 사용](https://docs.aws.amazon.com/AWSEC2/latest/WindowsGuide/Windows-Server-EC2Rescue.html)에서 설명한 대로 이 도구를 직접 실행할 수 있습니다. 또는 Systems Manager Automation 및 **`AWSSupport-ExecuteEC2Rescue`** 실행서를 사용하여 도구를 자동으로 실행할 수 있습니다. Automation은 AWS Systems Manager의 도구입니다. **`AWSSupport-ExecuteEC2Rescue`** 실행서는 EC2Rescue를 사용하는 데 일반적으로 필요한 단계를 자동화하는 Systems Manager 작업, CloudFormation 작업 및 Lambda 함수를 조합하여 수행하도록 설계되었습니다.

**`AWSSupport-ExecuteEC2Rescue`** 실행서를 사용하여 다양한 유형의 운영 체제(OS) 문제를 해결하고, 수정할 수도 있습니다. 루트 볼륨이 암호화된 인스턴스는 지원되지 않습니다. 전체 목록은 다음 항목을 참조하십시오.

**Windows**: [명령줄에서 EC2Rescue for Windows Server 사용](https://docs.aws.amazon.com/AWSEC2/latest/WindowsGuide/ec2rw-cli.html#ec2rw-rescue)의 *복구 작업*을 참조하세요.

**Linux** 및 **macOS**: 일부 Linux용 EC2Rescue 모듈은 문제를 감지하여 수정을 시도합니다. 자세한 내용은 GitHub에서 각 모델에 대한 [https://github.com/awslabs/aws-ec2rescue-linux/tree/master/docs](https://github.com/awslabs/aws-ec2rescue-linux/tree/master/docs) 설명서를 참조하세요.

## 작동 방식
<a name="automation-ec2rescue-how"></a>

Automation과 **`AWSSupport-ExecuteEC2Rescue`** 실행서를 사용한 인스턴스 문제 해결은 다음과 같이 수행됩니다.
+ 연결할 수 없는 인스턴스의 ID를 지정하고 자동화를 시작합니다.
+ 시스템에서 임시 VPC를 만든 다음, 일련의 Lambda 함수를 실행하여 VPC를 구성합니다.
+ 시스템에서 원본 인스턴스와 동일한 가용 영역에 있는 임시 VPC의 서브넷을 식별합니다.
+ 시스템에서 SSM이 활성화된 임시 헬퍼 인스턴스를 시작합니다.
+ 시스템에서 원본 인스턴스를 중지한 후 백업을 만듭니다. 그런 다음 헬퍼 인스턴스에 원본 루트 볼륨을 연결합니다.
+ 시스템에서 Run Command를 사용하여 헬퍼 인스턴스에서 EC2Rescue를 실행합니다. EC2Rescue는 연결된 원본 루트 볼륨의 문제를 확인하고 수정하려 시도합니다. 마치면 EC2Rescue가 원본 인스턴스에 루트 볼륨을 다시 연결합니다.
+ 시스템에서 원본 인스턴스를 다시 시작하고, 임시 인스턴스를 종료합니다. 또한 자동화가 시작될 때 생성된 Lambda 함수와 임시 VPC를 종료합니다.

## 시작하기 전 준비 사항
<a name="automation-ec2rescue-begin"></a>

다음 자동화를 실행하기 전에 다음을 수행합니다.
+ 연결할 수 없는 인스턴스의 인스턴스 ID를 복사합니다. 절차에서 이 ID를 지정할 것입니다.
+ 원할 경우, 연결할 수 없는 인스턴스와 동일한 가용 영역에 있는 서브넷 ID를 수집할 수도 있습니다. 이 서브넷에 EC2Rescue 인스턴스가 생성됩니다. 서브넷을 지정하지 않으면 Automation 프로세스에 따라 AWS 계정에 새로운 임시 VPC가 생성됩니다. AWS 계정에 사용 가능한 VPC가 하나 이상 있는지 확인합니다. 기본적으로 리전 하나에 VPC를 다섯 개 만들 수 있습니다. 리전에 이미 VPC를 다섯 개 만든 경우, 자동화가 인스턴스를 변경하지 않고 실패합니다. Amazon VPC 할당량에 대한 자세한 내용은 *Amazon VPC 사용 설명서*의 [VPC 및 서브넷](https://docs.aws.amazon.com/vpc/latest/userguide/amazon-vpc-limits.html#vpc-limits-vpcs-subnets)을 참조하세요.
+ 필요에 따라 Automation의 AWS Identity and Access Management(IAM) 역할을 생성하고 지정할 수 있습니다. 이 역할을 지정하지 않으면 자동화가 자동화를 실행한 사용자의 맥락에서 실행됩니다.

### `AWSSupport-EC2Rescue`에 인스턴스에서 작업을 수행할 권한 부여
<a name="automation-ec2rescue-access"></a>

EC2Rescue는 자동화 중에 인스턴스에서 일련의 작업을 수행할 권한이 필요합니다. 이러한 작업은 AWS Lambda, IAM 및 Amazon EC2 서비스를 호출하여 인스턴스 관련 문제를 안전하게 해결하려고 시도합니다. AWS 계정 및/또는 VPC에서 관리자 수준 권한이 있는 경우 이 섹션의 설명과 같이 권한을 구성하지 않고 자동화를 실행할 수 있습니다. 관리자 수준 권한이 없는 경우, 사용자 또는 관리자가 다음 옵션 중 하나를 사용하여 권한을 구성해야 합니다.
+ [IAM 정책을 사용하여 권한 부여](#automation-ec2rescue-access-iam)
+ [CloudFormation 템플릿을 사용하여 권한 부여](#automation-ec2rescue-access-cfn)

#### IAM 정책을 사용하여 권한 부여
<a name="automation-ec2rescue-access-iam"></a>

사용자, 그룹 또는 역할에 다음 IAM 정책을 인라인 정책으로 연결하거나, 새 IAM 관리형 정책을 생성하고 이를 사용자, 그룹 또는 역할에 연결할 수 있습니다. 사용자, 그룹 또는 역할에 인라인 정책 추가에 대한 자세한 내용은 [인라인 정책 작업](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_inline-using.html)을 참조하세요. 새 관리형 정책 만들기에 대한 자세한 내용은 [관리형 정책 작업](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_managed-using.html)을 참조하십시오.

**참고**  
새 IAM 관리형 정책을 생성하는 경우 인스턴스가 Systems Manager API와 통신할 수 있도록 **AmazonSSMAutomationRole** 관리형 정책도 여기에 연결해야 합니다.

**AWSSupport-EC2Rescue의 IAM 정책**

*계정 ID*를 자신의 정보로 바꿉니다.

------
#### [ JSON ]

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Action": [
                "lambda:InvokeFunction",
                "lambda:DeleteFunction",
                "lambda:GetFunction"
            ],
            "Resource": "arn:aws:lambda:*:111122223333:function:AWSSupport-EC2Rescue-*",
            "Effect": "Allow"
        },
        {
            "Action": [
                "s3:GetObject",
                "s3:GetObjectVersion"
            ],
            "Resource": [
                "arn:aws:s3:::awssupport-ssm.*/*.template",
                "arn:aws:s3:::awssupport-ssm.*/*.zip"
            ],
            "Effect": "Allow"
        },
        {
            "Action": [
                "iam:CreateRole",
                "iam:CreateInstanceProfile",
                "iam:GetRole",
                "iam:GetInstanceProfile",
                "iam:PutRolePolicy",
                "iam:DetachRolePolicy",
                "iam:AttachRolePolicy",
                "iam:PassRole",
                "iam:AddRoleToInstanceProfile",
                "iam:RemoveRoleFromInstanceProfile",
                "iam:DeleteRole",
                "iam:DeleteRolePolicy",
                "iam:DeleteInstanceProfile"
            ],
            "Resource": [
                "arn:aws:iam::111122223333:role/AWSSupport-EC2Rescue-*",
                "arn:aws:iam::111122223333:instance-profile/AWSSupport-EC2Rescue-*"
            ],
            "Effect": "Allow"
        },
        {
            "Action": [
                "lambda:CreateFunction",
                "ec2:CreateVpc",
                "ec2:ModifyVpcAttribute",
                "ec2:DeleteVpc",
                "ec2:CreateInternetGateway",
                "ec2:AttachInternetGateway",
                "ec2:DetachInternetGateway",
                "ec2:DeleteInternetGateway",
                "ec2:CreateSubnet",
                "ec2:DeleteSubnet",
                "ec2:CreateRoute",
                "ec2:DeleteRoute",
                "ec2:CreateRouteTable",
                "ec2:AssociateRouteTable",
                "ec2:DisassociateRouteTable",
                "ec2:DeleteRouteTable",
                "ec2:CreateVpcEndpoint",
                "ec2:DeleteVpcEndpoints",
                "ec2:ModifyVpcEndpoint",
                "ec2:Describe*",
                "autoscaling:DescribeAutoScalingInstances"
            ],
            "Resource": "*",
            "Effect": "Allow"
        }
    ]
}
```

------

#### CloudFormation 템플릿을 사용하여 권한 부여
<a name="automation-ec2rescue-access-cfn"></a>

CloudFormation은 미리 구성된 템플릿을 사용하여 IAM 역할과 정책을 만드는 과정을 자동화합니다. 다음 절차에 따라 CloudFormation을 사용하여 EC2Rescue Automation에 필요한 IAM 역할과 정책을 생성합니다.

**EC2Rescue에 필요한 IAM 역할과 정책을 생성하려면**

1. [https://docs.aws.amazon.com/systems-manager/latest/userguide/samples/AWSSupport-EC2RescueRole.zip](https://docs.aws.amazon.com/systems-manager/latest/userguide/samples/AWSSupport-EC2RescueRole.zip)을 다운로드하여 로컬 시스템의 디렉터리에 `AWSSupport-EC2RescueRole.json` 파일의 압축을 풉니다.

1. AWS 계정가 특수 파티션인 경우 템플릿을 편집하여 ARN 값을 파티션 값으로 변경합니다.

   예를 들어 중국 리전의 경우 `arn:aws`의 모든 사례를 `arn:aws-cn`으로 변경합니다.

1. AWS Management Console에 로그인하여 [https://console.aws.amazon.com/cloudformation](https://console.aws.amazon.com/cloudformation/)에서 CloudFormation 콘솔을 엽니다.

1. **스택 생성**, **새 리소스 사용(표준)**를 선택합니다.

1. **스택 생성** 페이지에서 **Prerequisite - Prepare template(사전 조건 - 템플릿 준비)**에 대해 **Template is ready(템플릿 준비됨)**를 선택합니다.

1. **템플릿 지정**에서 **템플릿 파일 업로드**를 선택합니다.

1. **파일 선택**을 선택한 다음 압축을 푼 디렉터리에서 `AWSSupport-EC2RescueRole.json` 파일을 찾아 선택합니다.

1. **다음**을 선택합니다.

1. **Specify stack details(스택 세부 정보 지정)** 페이지의 **스택 이름** 필드에 이 스택을 식별할 이름을 입력하고 **다음**을 선택합니다.

1. (선택 사항) **태그** 영역에서 하나 이상의 태그 키 이름/값 쌍을 스택에 적용합니다.

   태그는 리소스에 할당하는 선택적 메타데이터입니다. 태그를 사용하면 용도, 소유자 또는 환경을 기준으로 하는 등 리소스를 다양한 방식으로 분류할 수 있습니다. 예를 들어, 스택에 태그를 지정하여 실행되는 작업 유형, 대상 유형이나 기타 관련 리소스, 해당 스택이 실행되는 환경을 식별할 수 있습니다.

1. **다음(Next)**을 선택합니다.

1. **검토** 페이지에서 스택 세부 정보를 검토하고 아래로 스크롤하여 **CloudFormation에서 IAM 리소스를 생성할 수 있음을 승인합니다** 옵션을 선택합니다.

1. **스택 생성**을 선택합니다.

   CloudFormation에 몇 분간 **CREATE\$1IN\$1PROGRESS** 상태가 표시됩니다. 스택이 생성된 후 상태가 **CREATE\$1COMPLETE**로 바뀝니다. 새로 고침 아이콘을 선택하여 생성 프로세스의 상태를 확인할 수도 있습니다.

1. **스택** 목록에서 방금 생성한 스택 옆의 옵션 버튼을 선택한 후 **출력** 탭을 선택합니다.

1. **값**을 기록해 둡니다. 이는 AssumeRole의 ARN입니다. [자동화 실행](#automation-ec2rescue-executing) 단원에 나온 절차에서 자동화를 실행할 때 이 ARN을 지정합니다.

## 자동화 실행
<a name="automation-ec2rescue-executing"></a>

**중요**  
다음 자동화는 연결할 수 없는 인스턴스를 중지합니다. 인스턴스가 중지되면 연결된 인스턴스 스토어 볼륨(있는 경우)의 데이터가 손실될 수 있습니다. 또한 인스턴스가 중지되면 연결된 탄력적 IP가 없는 경우 퍼블릭 IP가 변경될 수도 있습니다.

**`AWSSupport-ExecuteEC2Rescue` Automation을 실행하려면**

1. [https://console.aws.amazon.com/systems-manager/](https://console.aws.amazon.com/systems-manager/)에서 AWS Systems Manager 콘솔을 엽니다.

1. 왼쪽 탐색 창에서 **Automation**을 선택합니다.

1. **자동화 실행(Execute automation)**을 선택합니다.

1. **자동화 문서** 섹션의 목록에서 **Owned by Amazon(Amazon 소유)**을 선택합니다.

1. 실행서 목록에서 [`AWSSupport-ExecuteEC2Rescue`]의 카드에 있는 버튼을 선택하고 [**다음(Next)**]을 선택합니다.

1. **Execute automation document(자동화 문서 실행)** 페이지에서 **Simple execution(단순 실행)**을 선택합니다.

1. **문서 세부 정보** 섹션에서 **문서 버전**이 가장 높은 기본 버전으로 설정되어 있는지 확인합니다. 예를 들어, **\$1DEFAULT** 또는 **3(기본값)**입니다.

1. **입력 파라미터** 섹션에서 다음 파라미터를 지정합니다.

   1. **UnreachableInstanceId**에서 연결할 수 없는 인스턴스의 ID를 지정합니다.

   1. (선택 사항) **EC2RescueInstanceType**에서 EC2Rescue 인스턴스의 인스턴스 유형을 지정합니다. 기본 인스턴스 유형은 `t2.medium`입니다.

   1. **AutomationAssumeRole**의 경우 이 주제의 앞부분에서 설명한 CloudFormation 절차를 사용하여 이 자동화에 대한 역할을 생성한 경우 CloudFormation 콘솔에서 생성한 AssumeRole의 ARN을 선택합니다.

   1. (선택 사항) **LogDestination**에서 인스턴스의 문제를 해결하는 동안 운영 체제 수준 로그를 수집하려면 S3 버킷을 지정합니다. 지정된 버킷으로 로그가 자동으로 업로드됩니다.

   1. **SubnetId**에서, 연결할 수 없는 인스턴스와 동일한 가용 영역에 있는 기존 VPC의 서브넷을 지정합니다. 기본적으로 Systems Manager는 새로운 VPC를 생성하지만, 원하는 사용자는 기존 VPC의 서브넷을 지정할 수 있습니다.
**참고**  
버킷이나 서브넷 ID를 지정하는 옵션이 표시되지 않는 경우 실행서의 최신 **기본** 버전을 사용하고 있는지 확인합니다.

1. (옵션) [**태그(Tags)**] 영역에서 하나 이상의 태그 키 이름/값 페어(예: `Key=Purpose,Value=EC2Rescue`)를 적용하여 자동화를 식별할 수 있습니다.

1. **실행**을 선택합니다.

실행서가 자동화의 일부로 백업 AMI를 생성합니다. 자동화에 의해 생성된 다른 모든 리소스는 자동으로 삭제되지만, 이 AMI는 계정에 계속 유지됩니다. 다음 명명 규칙을 사용하여 AMI 이름이 지정됩니다.

백업 AMI: AWSSupport-EC2Rescue:*UnreachableInstanceId*

Automation 실행 ID를 검색하여 Amazon EC2 콘솔에 있는 이 AMI를 찾을 수 있습니다.

# EC2 인스턴스에서 암호 및 SSH 키 재설정
<a name="automation-ec2reset"></a>

`AWSSupport-ResetAccess` 런북을 사용하여 Windows Server용 Amazon Elastic Compute Cloud(Amazon EC2) 인스턴스의 로컬 관리자 암호 생성을 자동으로 재활성화하고 Linux용 EC2 인스턴스에 새로운 SSH 키를 생성할 수 있습니다. `AWSSupport-ResetAccess` 실행서는 로컬 관리자 암호를 재설정하는 데 일반적으로 필요한 단계를 자동화하는 AWS Systems Manager 작업, AWS CloudFormation 작업 및 AWS Lambda 함수를 조합하여 수행하도록 설계되었습니다.

`AWSSupport-ResetAccess` 런북과 함께 AWS Systems Manager의 도구인 Automation을 사용하여 다음 문제를 해결할 수 있습니다.

**Windows**

*EC2 키 페어 분실*: 이 문제를 해결하려면 **AWSSupport-ResetAccess** 실행서를 사용하여 현재 인스턴스에서 암호 지원 AMI를 생성한 후 이 AMI에서 인스턴스를 새로 시작하고 키 페어를 선택합니다.

*로컬 관리자 암호 분실*: 이 문제를 해결하려면 `AWSSupport-ResetAccess` 실행서를 사용하여, 현재 EC2 키 페어로 복호화할 수 있는 새로운 암호를 생성합니다.

**Linux**

*EC2 키 페어를 분실한 경우 또는 분실한 키를 사용하여 인스턴스에 대한 SSH 액세스를 구성한 경우*: 이 문제를 해결하려면 `AWSSupport-ResetAccess` 실행서를 사용하여 현재 인스턴스에 대한 SSH 키를 새로 생성합니다. 이렇게 하면 인스턴스에 다시 연결할 수 있습니다.

**참고**  
Windows Server용 EC2 인스턴스가 Systems Manager용으로 구성된 경우 EC2Rescue 및 AWS Systems Manager Run Command를 사용하여 로컬 관리자 암호를 재설정할 수도 있습니다. 자세한 내용은 *Amazon EC2 사용 설명서*의 [Systems Manager Run Command를 통해 Windows Server용 EC2Rescue 사용](https://docs.aws.amazon.com/AWSEC2/latest/WindowsGuide/ec2rw-ssm.html)를 참조하세요.

**관련 정보**  
*Amazon EC2 사용 설명서*의 [PuTTY를 사용하여 Windows에서 Linux 인스턴스에 연결](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/putty.html)

## 작동 방식
<a name="automation-ec2reset-how"></a>

Automation과 `AWSSupport-ResetAccess` 실행서를 사용한 인스턴스 문제 해결은 다음과 같이 수행됩니다.
+ 인스턴스의 ID를 지정하고 실행서를 실행합니다.
+ 시스템에서 임시 VPC를 만든 다음, 일련의 Lambda 함수를 실행하여 VPC를 구성합니다.
+ 시스템에서 원본 인스턴스와 동일한 가용 영역에 있는 임시 VPC의 서브넷을 식별합니다.
+ 시스템에서 SSM이 활성화된 임시 헬퍼 인스턴스를 시작합니다.
+ 시스템에서 원본 인스턴스를 중지한 후 백업을 만듭니다. 그런 다음 헬퍼 인스턴스에 원본 루트 볼륨을 연결합니다.
+ 시스템에서 Run Command를 사용하여 헬퍼 인스턴스에서 EC2Rescue를 실행합니다. Windows에서 EC2Rescue는 연결된, 원래 루트 볼륨에 있는 EC2Config 또는 EC2Launch를 사용하여 로컬 관리자에 대한 암호 생성을 활성화합니다. Linux에서, EC2Rescue는 새로운 SSH 키를 생성하여 투입하고, 암호화된 프라이빗 키를 Parameter Store에 저장합니다. 마치면 EC2Rescue가 원본 인스턴스에 루트 볼륨을 다시 연결합니다.
+ 암호 생성이 활성화되어 있으므로 시스템에서 인스턴스의 새 Amazon Machine Image(AMI)를 생성합니다. 이 AMI를 사용하여 새 EC2 인스턴스를 생성하고 필요 시 새 키 페어를 연결할 수 있습니다.
+ 시스템에서 원본 인스턴스를 다시 시작하고, 임시 인스턴스를 종료합니다. 또한 자동화가 시작될 때 생성된 Lambda 함수와 임시 VPC를 종료합니다.
+ **Windows**: 해당 인스턴스가 인스턴스에 지정된 현재 키 페어를 사용하여 Amazon EC2 콘솔로부터 디코딩할 수 있는 새로운 암호를 생성합니다.

  **Linux**: Systems Manager 파라미터 스토어에 **/ec2rl/openssh/*instance ID*/key**로 저장된 SSH 키를 사용하여 인스턴스에 SSH로 액세스할 수 있습니다.

## 시작하기 전 준비 사항
<a name="automation-ec2reset-begin"></a>

다음 자동화를 실행하기 전에 다음을 수행합니다.
+ 관리자 암호를 재설정하려는 인스턴스의 인스턴스 ID를 복사합니다. 절차에서 이 ID를 지정할 것입니다.
+ 원할 경우, 연결할 수 없는 인스턴스와 동일한 가용 영역에 있는 서브넷 ID를 수집할 수도 있습니다. 이 서브넷에 EC2Rescue 인스턴스가 생성됩니다. 서브넷을 지정하지 않으면 Automation 프로세스에 따라 AWS 계정에 새로운 임시 VPC가 생성됩니다. AWS 계정에 사용 가능한 VPC가 하나 이상 있는지 확인합니다. 기본적으로 리전 하나에 VPC를 다섯 개 만들 수 있습니다. 리전에 이미 VPC를 다섯 개 만든 경우, 자동화가 인스턴스를 변경하지 않고 실패합니다. Amazon VPC 할당량에 대한 자세한 내용은 *Amazon VPC 사용 설명서*의 [VPC 및 서브넷](https://docs.aws.amazon.com/vpc/latest/userguide/amazon-vpc-limits.html#vpc-limits-vpcs-subnets)을 참조하세요.
+ 필요에 따라 Automation의 AWS Identity and Access Management(IAM) 역할을 생성하고 지정할 수 있습니다. 이 역할을 지정하지 않으면 자동화가 자동화를 실행한 사용자의 맥락에서 실행됩니다.

### AWSSupport-EC2Rescue에 인스턴스에서 작업을 수행할 권한 부여
<a name="automation-ec2reset-access"></a>

EC2Rescue는 자동화 중에 인스턴스에서 일련의 작업을 수행할 권한이 필요합니다. 이러한 작업은 AWS Lambda, IAM 및 Amazon EC2 서비스를 호출하여 인스턴스 관련 문제를 안전하게 해결하려고 시도합니다. AWS 계정 및/또는 VPC에서 관리자 수준 권한이 있는 경우 이 섹션의 설명과 같이 권한을 구성하지 않고 자동화를 실행할 수 있습니다. 관리자 수준 권한이 없는 경우, 사용자 또는 관리자가 다음 옵션 중 하나를 사용하여 권한을 구성해야 합니다.
+ [IAM 정책을 사용하여 권한 부여](#automation-ec2reset-access-iam)
+ [CloudFormation 템플릿을 사용하여 권한 부여](#automation-ec2reset-access-cfn)

#### IAM 정책을 사용하여 권한 부여
<a name="automation-ec2reset-access-iam"></a>

사용자, 그룹 또는 역할에 다음 IAM 정책을 인라인 정책으로 연결하거나, 새 IAM 관리형 정책을 생성하고 이를 사용자, 그룹 또는 역할에 연결할 수 있습니다. 사용자, 그룹 또는 역할에 인라인 정책 추가에 대한 자세한 내용은 [인라인 정책 작업](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_inline-using.html)을 참조하세요. 새 관리형 정책 만들기에 대한 자세한 내용은 [관리형 정책 작업](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_managed-using.html)을 참조하십시오.

**참고**  
새 IAM 관리형 정책을 생성하는 경우 인스턴스가 Systems Manager API와 통신할 수 있도록 **AmazonSSMAutomationRole** 관리형 정책도 여기에 연결해야 합니다.

**`AWSSupport-ResetAccess`에 대한 IAM 정책**

*계정 ID*를 자신의 정보로 바꿉니다.

------
#### [ JSON ]

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Action": [
                "lambda:InvokeFunction",
                "lambda:DeleteFunction",
                "lambda:GetFunction"
            ],
            "Resource": "arn:aws:lambda:*:111122223333:function:AWSSupport-EC2Rescue-*",
            "Effect": "Allow"
        },
        {
            "Action": [
                "s3:GetObject",
                "s3:GetObjectVersion"
            ],
            "Resource": [
                "arn:aws:s3:::awssupport-ssm.*/*.template",
                "arn:aws:s3:::awssupport-ssm.*/*.zip"
            ],
            "Effect": "Allow"
        },
        {
            "Action": [
                "iam:CreateRole",
                "iam:CreateInstanceProfile",
                "iam:GetRole",
                "iam:GetInstanceProfile",
                "iam:PutRolePolicy",
                "iam:DetachRolePolicy",
                "iam:AttachRolePolicy",
                "iam:PassRole",
                "iam:AddRoleToInstanceProfile",
                "iam:RemoveRoleFromInstanceProfile",
                "iam:DeleteRole",
                "iam:DeleteRolePolicy",
                "iam:DeleteInstanceProfile"
            ],
            "Resource": [
                "arn:aws:iam::111122223333:role/AWSSupport-EC2Rescue-*",
                "arn:aws:iam::111122223333:instance-profile/AWSSupport-EC2Rescue-*"
            ],
            "Effect": "Allow"
        },
        {
            "Action": [
                "lambda:CreateFunction",
                "ec2:CreateVpc",
                "ec2:ModifyVpcAttribute",
                "ec2:DeleteVpc",
                "ec2:CreateInternetGateway",
                "ec2:AttachInternetGateway",
                "ec2:DetachInternetGateway",
                "ec2:DeleteInternetGateway",
                "ec2:CreateSubnet",
                "ec2:DeleteSubnet",
                "ec2:CreateRoute",
                "ec2:DeleteRoute",
                "ec2:CreateRouteTable",
                "ec2:AssociateRouteTable",
                "ec2:DisassociateRouteTable",
                "ec2:DeleteRouteTable",
                "ec2:CreateVpcEndpoint",
                "ec2:DeleteVpcEndpoints",
                "ec2:ModifyVpcEndpoint",
                "ec2:Describe*"
            ],
            "Resource": "*",
            "Effect": "Allow"
        }
    ]
}
```

------

#### CloudFormation 템플릿을 사용하여 권한 부여
<a name="automation-ec2reset-access-cfn"></a>

CloudFormation은 미리 구성된 템플릿을 사용하여 IAM 역할과 정책을 만드는 과정을 자동화합니다. 다음 절차에 따라 CloudFormation을 사용하여 EC2Rescue Automation에 필요한 IAM 역할과 정책을 생성합니다.

**EC2Rescue에 필요한 IAM 역할과 정책을 생성하려면**

1. [https://docs.aws.amazon.com/systems-manager/latest/userguide/samples/AWSSupport-EC2RescueRole.zip](https://docs.aws.amazon.com/systems-manager/latest/userguide/samples/AWSSupport-EC2RescueRole.zip)을 다운로드하여 로컬 시스템의 디렉터리에 `AWSSupport-EC2RescueRole.json` 파일의 압축을 풉니다.

1. AWS 계정가 특수 파티션인 경우 템플릿을 편집하여 ARN 값을 파티션 값으로 변경합니다.

   예를 들어 중국 리전의 경우 `arn:aws`의 모든 사례를 `arn:aws-cn`으로 변경합니다.

1. AWS Management Console에 로그인하여 [https://console.aws.amazon.com/cloudformation](https://console.aws.amazon.com/cloudformation/)에서 CloudFormation 콘솔을 엽니다.

1. **스택 생성**, **새 리소스 사용(표준)**를 선택합니다.

1. **스택 생성** 페이지에서 **Prerequisite - Prepare template(사전 조건 - 템플릿 준비)**에 대해 **Template is ready(템플릿 준비됨)**를 선택합니다.

1. **템플릿 지정**에서 **템플릿 파일 업로드**를 선택합니다.

1. **파일 선택**을 선택한 다음 압축을 푼 디렉터리에서 `AWSSupport-EC2RescueRole.json` 파일을 찾아 선택합니다.

1. **다음**을 선택합니다.

1. **Specify stack details(스택 세부 정보 지정)** 페이지의 **스택 이름** 필드에 이 스택을 식별할 이름을 입력하고 **다음**을 선택합니다.

1. (선택 사항) **태그** 영역에서 하나 이상의 태그 키 이름/값 쌍을 스택에 적용합니다.

   태그는 리소스에 할당하는 선택적 메타데이터입니다. 태그를 사용하면 용도, 소유자 또는 환경을 기준으로 하는 등 리소스를 다양한 방식으로 분류할 수 있습니다. 예를 들어, 스택에 태그를 지정하여 실행되는 작업 유형, 대상 유형이나 기타 관련 리소스, 해당 스택이 실행되는 환경을 식별할 수 있습니다.

1. **다음(Next)**을 선택합니다.

1. **검토** 페이지에서 스택 세부 정보를 검토하고 아래로 스크롤하여 **CloudFormation에서 IAM 리소스를 생성할 수 있음을 승인합니다** 옵션을 선택합니다.

1. CloudFormation에 몇 분간 **CREATE\$1IN\$1PROGRESS** 상태가 표시됩니다. 스택이 생성된 후 상태가 **CREATE\$1COMPLETE**로 바뀝니다. 새로 고침 아이콘을 선택하여 생성 프로세스의 상태를 확인할 수도 있습니다.

1. 스택 목록에서 방금 생성한 스택 옆에 있는 옵션을 선택한 다음, **출력** 탭을 선택합니다.

1. **값**을 복사합니다. 이는 AssumeRole의 ARN입니다. 자동화를 실행할 때 이 ARN을 지정합니다.

## 자동화 실행
<a name="automation-ec2reset-executing"></a>

다음 절차에서는 AWS Systems Manager 콘솔을 사용하여 `AWSSupport-ResetAccess` 실행서를 실행하는 방법을 설명합니다.

**중요**  
다음 자동화는 인스턴스를 중지합니다. 인스턴스가 중지되면 연결된 인스턴스 스토어 볼륨(있는 경우)의 데이터가 손실될 수 있습니다. 또한 인스턴스가 중지되면 연결된 탄력적 IP가 없는 경우 퍼블릭 IP가 변경될 수도 있습니다. 이렇게 구성이 변경되지 않도록 하려면 Run Command를 사용하여 액세스를 재설정하십시오. 자세한 내용은 *Amazon EC2 사용 설명서*의 [Systems Manager Run Command를 통해 Windows Server용 EC2Rescue 사용](https://docs.aws.amazon.com/AWSEC2/latest/WindowsGuide/ec2rw-ssm.html)를 참조하세요.

**AWSSupport-ResetAccess 자동화를 실행하는 방법**

1. [https://console.aws.amazon.com/systems-manager/](https://console.aws.amazon.com/systems-manager/)에서 AWS Systems Manager 콘솔을 엽니다.

1. 왼쪽 탐색 창에서 **Automation**을 선택합니다.

1. **자동화 실행(Execute automation)**을 선택합니다.

1. **자동화 문서** 섹션의 목록에서 **Owned by Amazon(Amazon 소유)**을 선택합니다.

1. 실행서 목록에서 [**AWSSupport-ResetAccess**]의 카드에 있는 버튼을 선택하고 [**다음(Next)**]을 선택합니다.

1. **Execute automation document(자동화 문서 실행)** 페이지에서 **Simple execution(단순 실행)**을 선택합니다.

1. **문서 세부 정보** 섹션에서 **문서 버전**이 가장 높은 기본 버전으로 설정되어 있는지 확인합니다. 예를 들어, **\$1DEFAULT** 또는 **3(기본값)**입니다.

1. **입력 파라미터** 섹션에서 다음 파라미터를 지정합니다.

   1. **InstanceID**에서 연결할 수 없는 인스턴스의 ID를 지정합니다.

   1. **SubnetId**에서, 지정한 인스턴스와 동일한 가용 영역에 있는 기존 VPC의 서브넷을 지정합니다. 기본적으로 Systems Manager는 새로운 VPC를 생성하지만, 원하는 사용자는 기존 VPC의 서브넷을 지정할 수 있습니다.
**참고**  
서브넷 ID를 지정하는 옵션이 표시되지 않는 경우 실행서의 최신 [**기본(Default)**] 버전을 사용하고 있는지 확인합니다.

   1. **EC2RescueInstanceType**에서 EC2Rescue 인스턴스의 인스턴스 유형을 지정합니다. 기본 인스턴스 유형은 `t2.medium`입니다.

   1. [**AssumeRole**]의 경우 이 주제의 앞부분에서 설명한 CloudFormation 절차를 사용하여 이 Automation에 대한 역할을 생성한 경우 CloudFormation 콘솔에서 기록한 AssumeRole ARN을 지정합니다.

1. (옵션) [**태그(Tags)**] 영역에서 하나 이상의 태그 키 이름/값 페어(예: `Key=Purpose,Value=ResetAccess`)를 적용하여 자동화를 식별할 수 있습니다.

1. **실행**을 선택합니다.

1. 자동화 진행 상황을 모니터링하려면 실행 중인 자동화를 선택한 후 [**단계(Steps)**] 탭을 선택합니다. 자동화가 종료되면 [**설명(Descriptions)**] 탭을 선택한 후 [**출력 보기(View output)**]를 선택하여 결과를 봅니다. 개별 단계의 출력을 보려면 **단계** 탭을 선택한 다음, 단계 옆에 있는 **출력 보기**를 선택합니다.

실행서가 자동화의 일부로 백업 AMI와 암호 사용 AMI를 생성합니다. 자동화에 의해 생성된 다른 모든 리소스는 자동으로 삭제되지만, 이러한 AMIs는 계정에 계속 유지됩니다. AMIs는 다음 명명 규칙을 사용하여 이름이 지정됩니다.
+ 백업 AMI: `AWSSupport-EC2Rescue:InstanceID`
+ 암호가 설정된 AMI: AWSSupport-EC2Rescue: *인스턴스스 ID*의 암호가 설정된 AMI

Automation 실행 ID를 검색하여 이 AMIs를 찾을 수 있습니다.

Linux의 경우 인스턴스의 새로운 SSH 프라이빗 키는 암호화되어 Parameter Store에 저장됩니다. 파라미터 이름은 **/ec2rl/openssh/*instance ID*/key**입니다.

# 입력 변환기를 사용하여 Automation에 데이터 전달
<a name="automation-tutorial-eventbridge-input-transformers"></a>

이 AWS Systems Manager Automation 자습서에서는 Amazon EventBridge의 입력 변환기 기능을 사용하여 인스턴스 상태 변경 이벤트에서 Amazon Elastic Compute Cloud(Amazon EC2) 인스턴스의 `instance-id`를 추출하는 방법을 보여줍니다. Automation은 AWS Systems Manager의 도구입니다. 입력 변환기를 사용하여 `AWS-CreateImage` 실행서 대상에 `InstanceId` 입력 파라미터로 해당 데이터를 전달합니다. 인스턴스 상태가 `stopped`로 변경될 때 규칙이 트리거됩니다.

입력 변환기 작업에 대한 자세한 내용은 *Amazon EventBridge User Guide*의 [Tutorial: Use Input Transformer to Customize What is Passed to the Event Target](https://docs.aws.amazon.com/eventbridge/latest/userguide/eventbridge-input-transformer-tutorial.html)을 참조하세요.

**시작하기 전 준비 사항**  
Systems Manager Automation 서비스 역할에 EventBridge에 필요한 권한 및 신뢰 정책을 추가했는지 확인합니다. 자세한 내용은 *Amazon EventBridge User Guide*의 [Overview of Managing Access Permissions to Your EventBridge Resources](https://docs.aws.amazon.com/eventbridge/latest/userguide/iam-access-control-identity-based-eventbridge.html)를 참조하세요.

**자동화와 함께 입력 변환기를 사용하려면**

1. [https://console.aws.amazon.com/events/](https://console.aws.amazon.com/events/)에서 Amazon EventBridge 콘솔을 엽니다.

1. 탐색 창에서 **규칙**을 선택합니다.

1. **규칙 생성**을 선택합니다.

1. 규칙에 대해 이름과 설명을 입력하세요.

   규칙은 동일한 리전과 동일한 이벤트 버스의 다른 규칙과 동일한 이름을 가질 수 없습니다.

1. **이벤트 버스**에서 이 규칙과 연결할 이벤트 버스를 선택합니다. 이 규칙이 자신의 AWS 계정에서 오는 일치하는 이벤트에 응답하도록 하려면 **default**(기본)를 선택합니다. 계정의 AWS 서비스이(가) 이벤트를 출력하면 항상 계정의 기본 이벤트 버스로 이동합니다.

1. **규칙 유형**에서 **이벤트 패턴이 있는 규칙**을 선택합니다.

1. **다음**을 선택합니다.

1. **이벤트 소스(Event source)**에서 **AWS 이벤트 또는 EventBridge 파트너 이벤트(Events or EventBridge partner events)**를 선택합니다.

1. **이벤트 패턴** 섹션에서 **이벤트 패턴 양식**을 선택합니다.

1. **이벤트 소스(Event source)**에서 **AWS 서비스(services)**를 선택합니다.

1. **AWS service**(서비스)에서 **EC2**를 선택합니다.

1. **이벤트 유형**에서 **EC2 인스턴스 상태 변경 알림**을 선택합니다.

1. **이벤트 유형 사양 1**에서 **특정 상태**를 선택한 다음 **중지됨**을 선택합니다.

1. **이벤트 유형 사양 2**에서 **모든 인스턴스**를 선택하거나, **특정 인스턴스 ID**를 선택하고 모니터링할 인스턴스의 ID를 입력합니다.

1. **다음**을 선택합니다.

1. **대상 유형**에서 **AWS서비스**를 선택합니다.

1. **Target**(대상)에서 **Systems Manager Automation**을 선택합니다.

1. **문서**에 대해 **AWS-CreateImage**를 선택합니다.

1. **Configure automation parameter(s)**(자동화 파라미터 구성) 섹션에서 **Input Transformer**(입력 변환기)를 선택합니다.

1. **Input path**(입력 경로)에서 **\$1"instance":"\$1.detail.instance-id"\$1**을(를) 입력합니다.

1. **Template**(템플릿)에서 **\$1"InstanceId":[<instance>]\$1**을(를) 입력합니다.

1. **Execution role**(실행 역할)에서 **Use existing role**(기존 역할 사용)을 선택하고 Automation 서비스 역할을 선택합니다.

1. **다음**을 선택합니다.

1. (선택 사항)규칙에 대해 하나 이상의 태그를 입력하세요. 자세한 내용은 *Amazon EventBridge User Guide*의 [Tagging Your Amazon EventBridge Resources](https://docs.aws.amazon.com/eventbridge/latest/userguide/eventbridge-tagging.html)를 참조하세요.

1. **다음**을 선택합니다.

1. 규칙의 세부 정보를 검토하고 **규칙 생성**을 선택합니다.

# Systems Manager Automation에서 반환된 상태에 대해 알아보기
<a name="automation-statuses"></a>

AWS Systems Manager Automation은 자동화를 실행할 때 및 전체 자동화에 대해 자동화 작업 또는 단계가 거치는 다양한 상태에 대한 자세한 상태 정보를 보고합니다. Automation은 AWS Systems Manager의 도구입니다. 다음 방법을 사용하여 자동화 상태를 모니터링할 수 있습니다.
+ Systems Manager Automation 콘솔에서 [**실행 상태(Execution status)**]를 모니터링합니다.
+ 선호하는 명령줄 도구를 사용합니다. AWS Command Line Interface(AWS CLI)에 대해 [describe-automation-step-executions](https://docs.aws.amazon.com/cli/latest/reference/ssm/describe-automation-step-executions.html) 또는 [get-automation-execution](https://docs.aws.amazon.com/cli/latest/reference/ssm/get-automation-execution.html)을 사용할 수 있습니다. AWS Tools for Windows PowerShell에 대해 [Get-SSMAutomationStepExecution](https://docs.aws.amazon.com/powershell/latest/reference/items/Get-SSMAutomationStepExecution.html) 또는 [Get-SSMAutomationExecution](https://docs.aws.amazon.com/powershell/latest/reference/items/Get-SSMAutomationExecution.html)을 사용할 수 있습니다.
+ 작업 또는 자동화 상태 변경에 응답하도록 Amazon EventBridge를 구성합니다.

자동화에서의 타임아웃 처리에 대한 자세한 내용은 [실행서에서 시간 제한 처리](automation-handling-timeouts.md) 섹션을 참조하세요.

## 자동화 상태 정보
<a name="automation-statuses-about"></a>

Automation은 전체 자동화 외에도 개별 자동화 작업에 대한 상태 세부 정보를 보고합니다.

전체 자동화 상태는 다음 표와 같이 개별 작업 또는 단계에서 보고되는 상태와 다를 수 있습니다.


**작업의 세부 상태**  

| Status | 세부 정보 | 
| --- | --- | 
| 보류중 | 단계 실행이 시작되지 않았습니다. 자동화에서 조건부 작업을 사용하는 경우 단계를 실행하기 위한 조건이 충족되지 않으면 자동화가 완료된 후 단계가 이 상태로 유지됩니다. 단계가 실행되기 전에 자동화가 취소된 경우에도 단계는 이 상태로 유지됩니다. | 
| InProgress | 작업이 실행 중입니다. | 
| 대기 중(Waiting) | 단계가 입력을 기다리고 있습니다. | 
| Success | 단계가 성공적으로 완료되었습니다. 이것은 종료 상태입니다. | 
| TimedOut | 지정된 시간 제한 기간 전에 단계 또는 승인이 완료되지 않았습니다. 이것은 종료 상태입니다. | 
| 취소 중 | 요청자가 취소한 후 단계를 중지하는 중입니다. | 
| 취소됨 | 단계가 완료되기 전에 요청자가 단계를 중지했습니다. 이것은 종료 상태입니다. | 
| 실패 |  단계가 성공적으로 완료되지 않았습니다. 이것은 종료 상태입니다.  | 
| Exited |  `aws:loop` 작업에 의해서만 반환됩니다. 루프가 완전히 완료되지 않았습니다. `nextStep`, `onCancel` 또는 `onFailure` 속성을 사용하여 루프 내부의 단계가 외부 단계로 이동했습니다.  | 


**자동화에 대한 세부 상태**  

| Status | 세부 정보 | 
| --- | --- | 
| 보류중 | 자동화 실행이 시작되지 않았습니다. | 
| InProgress | 자동화가 실행 중입니다. | 
| 대기 중(Waiting) | 자동화가 입력을 기다리고 있습니다. | 
| Success | 자동화가 성공적으로 완료되었습니다. 이것은 종료 상태입니다. | 
| TimedOut | 지정된 시간 제한 기간 전에 단계 또는 승인이 완료되지 않았습니다. 이것은 종료 상태입니다. | 
| 취소 중 | 요청자가 취소한 후 자동화를 중지하는 중입니다. | 
| 취소됨 | 자동화가 완료되기 전에 요청자가 자동화를 중지했습니다. 이것은 종료 상태입니다. | 
| 실패 |  자동화가 성공적으로 완료되지 않았습니다. 이것은 종료 상태입니다.  | 

# Systems Manager Automation 문제 해결
<a name="automation-troubleshooting"></a>

다음 정보를 사용하면 AWS Systems Manager의 도구인 AWS Systems Manager Automation 관련 문제를 해결하는 데 도움이 됩니다. 이 주제에는 자동화 오류 메시지를 기반으로 문제를 해결하기 위한 특정 작업이 포함됩니다.

**Topics**
+ [

## 일반적인 Automation 오류
](#automation-trbl-common)
+ [

## Automation 실행 시작이 실패함
](#automation-trbl-access)
+ [

## 실행이 시작되었지만 상태가 실패인 경우
](#automation-trbl-exstrt)
+ [

## 실행이 시작되었지만 시간 초과됨
](#automation-trbl-to)

## 일반적인 Automation 오류
<a name="automation-trbl-common"></a>

이 섹션에는 일반적인 자동화 오류에 대한 정보가 나와 있습니다.

### VPC not defined 400
<a name="automation-trbl-common-vpc"></a>

기본적으로 Automation이 `AWS-UpdateLinuxAmi` 실행서 또는 `AWS-UpdateWindowsAmi` 실행서를 실행하면 시스템이 기본 VPC(172.30.0.0/16)에 임시 인스턴스를 생성합니다. 기본 VPC를 삭제했다면 다음 오류 메시지를 받게 됩니다.

`VPC not defined 400`

이 문제를 해결하려면 `SubnetId` 입력 파라미터의 값을 지정해야 합니다.

## Automation 실행 시작이 실패함
<a name="automation-trbl-access"></a>

Automation에 대한 AWS Identity and Access Management(IAM) 역할 및 정책을 제대로 구성하지 않은 경우 자동화는 액세스 거부 오류 또는 유효하지 않은 수임 역할 오류와 함께 실패할 수 있습니다.

### 액세스 거부됨
<a name="automation-trbl-access-denied"></a>

다음 예제는 자동화 시작이 액세스 거부 오류와 함께 실패한 경우에 대해 설명합니다.

**Systems Manager API에 대한 액세스가 거부됨**  
**오류 메시지**: `User: user arn isn't authorized to perform: ssm:StartAutomationExecution on resource: document arn (Service: AWSSimpleSystemsManagement; Status Code: 400; Error Code: AccessDeniedException; Request ID: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx)`
+ 가능한 원인 1: 자동화를 시작하려고 하는 사용자에게 `StartAutomationExecution` API를 호출할 수 있는 권한이 없습니다. 이 문제를 해결하려면 자동화를 시작하는 데 사용된 사용자에게 필요한 IAM 정책을 연결합니다.
+ 가능한 원인 2: 자동화를 시작하려고 하는 사용자에게 `StartAutomationExecution` API를 호출할 수 있는 권한이 있지만, 특정 런북을 사용하여 API를 호출할 수 있는 권한은 없습니다. 이 문제를 해결하려면 자동화를 시작하는 데 사용된 사용자에게 필요한 IAM 정책을 연결합니다.

**PassRole 권한이 누락되었기 때문에 액세스 거부됨**  
**오류 메시지**: `User: user arn isn't authorized to perform: iam:PassRole on resource: automation assume role arn (Service: AWSSimpleSystemsManagement; Status Code: 400; Error Code: AccessDeniedException; Request ID: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx)`

자동화를 시작하려고 하는 사용자에게 수임 역할에 대한 PassRole 권한이 없습니다. 이 문제를 해결하려면 자동화를 시작하려고 시도하는 사용자의 역할에 iam:PassRole 정책을 연결합니다. 자세한 내용은 [작업 2: Automation 역할에 iam:PassRole 정책 연결하기](automation-setup-iam.md#attach-passrole-policy) 섹션을 참조하세요.

### 유효하지 않은 수임 역할
<a name="automation-trbl-ar"></a>

Automation을 실행할 때 assume 역할은 실행서에 제공되거나 해당 실행서에 대한 파라미터 값으로 전달됩니다. 수임 역할이 지정되지 않거나 제대로 구성되지 않으면 다양한 유형의 오류가 발생할 수 있습니다.

**형식이 잘못된 Assume Role**  
**오류 메시지**: `The format of the supplied assume role ARN isn't valid.` assume role의 형식이 잘못 지정되었습니다. 이 문제를 해결하려면 유효한 수임 역할이 실행서에 지정되어 있는지 또는 자동화 시작 시 런타임 파라미터로 지정되어 있는지 확인합니다.

**수임 역할을 수임할 수 없음**  
**오류 메시지**: `The defined assume role is unable to be assumed. (Service: AWSSimpleSystemsManagement; Status Code: 400; Error Code: InvalidAutomationExecutionParametersException; Request ID: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx)`
+ 가능한 원인 1: 수임 역할이 존재하지 않습니다. 이 문제를 해결하려면 역할을 생성하십시오. 자세한 내용은 [Automation 설정](automation-setup.md) 섹션을 참조하세요. 이 역할 생성에 대한 특정 정보는 [작업 1: Automation을 위한 서비스 역할 생성](automation-setup-iam.md#create-service-role) 주제에 설명되어 있습니다.
+ 가능한 원인 2: 수임 역할이 Systems Manager 서비스와 신뢰 관계를 갖지 않습니다. 이 문제를 해결하려면 신뢰 관계를 생성하십시오. 자세한 내용은 *IAM User Guide*의 [I Can't Assume A Role](https://docs.aws.amazon.com/IAM/latest/UserGuide/troubleshoot_roles.html#troubleshoot_roles_cant-assume-role)을 참조하세요.

## 실행이 시작되었지만 상태가 실패인 경우
<a name="automation-trbl-exstrt"></a>

### 작업별 오류
<a name="automation-trbl-actspec"></a>

실행서에는 단계와 단계 실행이 순서대로 포함되어 있습니다. 각 단계는 하나 이상의 AWS 서비스 API를 호출합니다. API는 해당 단계의 입력, 동작 및 출력을 결정합니다. 단계 실패를 유발할 수 있는 오류는 여러 위치에서 발생합니다. 오류 메시지는 오류가 언제 어디에서 발생했는지 나타냅니다.

Amazon Elastic Compute Cloud(Amazon EC2) 콘솔에서 오류 메시지를 보려면 실패한 단계의 [**출력 보기(View Outputs)**] 링크를 선택합니다. AWS CLI에서 오류 메시지를 보려면 `get-automation-execution`을 호출하고 실패한 `StepExecution`에서 `FailureMessage` 속성을 찾습니다.

다음 예제에서는 `aws:runInstance` 작업과 연결된 단계가 실패했습니다. 각 예제에서는 다른 유형의 오류를 살펴봅니다.

**이미지 누락**  
**오류 메시지**: `Automation Step Execution fails when it's launching the instance(s). Get Exception from RunInstances API of ec2 Service. Exception Message from RunInstances API: [The image id '[ami id]' doesn't exist (Service: AmazonEC2; Status Code: 400; Error Code: InvalidAMIID.NotFound; Request ID: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx)]. Please refer to Automation Service Troubleshooting Guide for more diagnosis details.`

`aws:runInstances` 작업이 존재하지 않는 `ImageId`에 대한 입력을 받았습니다. 이 문제를 해결하려면 실행서 또는 파라미터 값을 정확한 AMI ID로 업데이트합니다.

**수임 역할 정책에 충분한 권한이 없음**  
**오류 메시지**: `Automation Step Execution fails when it's launching the instance(s). Get Exception from RunInstances API of ec2 Service. Exception Message from RunInstances API: [You aren't authorized to perform this operation. Encoded authorization failure message: xxxxxxx (Service: AmazonEC2; Status Code: 403; Error Code: UnauthorizedOperation; Request ID: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx)]. Please refer to Automation Service Troubleshooting Guide for more diagnosis details.`

수임 역할에 EC2 인스턴스에서 `RunInstances` API를 호출할 수 있는 권한이 없습니다. 이 문제를 해결하려면 `RunInstances` API를 호출할 수 있는 권한이 있는 수임 역할에 IAM 정책을 연결합니다. 자세한 내용은 [콘솔을 사용하여 Automation을 위한 서비스 역할 생성](automation-setup-iam.md)을 참조하세요.

**예기치 않은 상태**  
**오류 메시지**: `Step fails when it's verifying launched instance(s) are ready to be used. Instance i-xxxxxxxxx entered unexpected state: shutting-down. Please refer to Automation Service Troubleshooting Guide for more diagnosis details.`
+ 가능한 원인 1: 인스턴스 또는 Amazon EC2 서비스에 문제가 있습니다. 이 문제를 해결하려면 인스턴스에 로그인하거나 인스턴스 시스템 로그를 검토하여 인스턴스가 종료되기 시작한 이유를 이해하십시오.
+ 가능한 원인 2: `aws:runInstances` 작업에 지정된 사용자 데이터 스크립트에 문제가 있거나 구문이 부정확합니다. 사용자 데이터 스크립트의 구문을 확인하십시오. 또한 사용자 데이터 스크립트가 인스턴스를 종료시키지 않는지, 아니면 인스턴스를 종료시키는 다른 스크립트를 호출하지 않는지 확인하십시오.

**작업 특정 오류 참조**  
단계가 실패하면 해당 오류 메시지가 오류 발생 시 호출 중이었던 서비스를 나타낼 수 있습니다. 다음 표에는 각 작업에 의해 호출된 서비스가 나와 있습니다. 또한 각 서비스에 대한 정보로 연결되는 링크도 제공합니다.


****  

| 작업 | 이 작업에 의해 AWS 서비스이(가) 호출됨 | 이 서비스에 대한 정보 | 콘텐츠 문제 해결 | 
| --- | --- | --- | --- | 
|  `aws:runInstances`  |  Amazon EC2  |  [Amazon EC2 사용 설명서](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/)  |  [EC2 인스턴스 문제 해결](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-troubleshoot.html)  | 
|  `aws:changeInstanceState`  |  Amazon EC2  |  [Amazon EC2 사용 설명서](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/)  |  [EC2 인스턴스 문제 해결](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-troubleshoot.html)  | 
|  `aws:runCommand`  |  Systems Manager  |   [AWS Systems Manager Run Command](run-command.md)  |   [Systems Manager Run Command 문제 해결](troubleshooting-remote-commands.md)  | 
|  `aws:createImage`  |  Amazon EC2  |  [https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/AMIs.html](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/AMIs.html)  |  | 
|  `aws:createStack`  |  CloudFormation  |  [AWS CloudFormation 사용자 안내서](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/Welcome.html)  |  [CloudFormation 문제 해결](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/troubleshooting.html)  | 
|  `aws:deleteStack`  |  CloudFormation  |  [AWS CloudFormation 사용자 안내서](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/Welcome.html)  |  [CloudFormation 문제 해결](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/troubleshooting.html)  | 
|  `aws:deleteImage`  |  Amazon EC2  |  [Amazon 머신 이미지](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/AMIs.html)  |  | 
|  `aws:copyImage`  |  Amazon EC2  |  [https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/AMIs.html](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/AMIs.html)  |  | 
|  `aws:createTag`  |  Amazon EC2, Systems Manager  |  [EC2 리소스 및 태그](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EC2_Resources.html)  |  | 
|  `aws:invokeLambdaFunction`  |  AWS Lambda  |  [AWS Lambda 개발자 안내서](https://docs.aws.amazon.com/lambda/latest/dg/)  |  [Lambda 문제 해결](https://docs.aws.amazon.com/lambda/latest/dg/monitoring-functions.html)  | 

### Automation 서비스 내부 오류
<a name="automation-trbl-err"></a>

**오류 메시지**: `Internal Server Error. Please refer to Automation Service Troubleshooting Guide for more diagnosis details.`

Automation 서비스 문제로 인해 지정된 실행서가 제대로 실행되지 않습니다. 이 문제를 해결하려면 AWS Support에 연락하십시오. 가능할 경우 실행 ID와 고객 ID를 제공하십시오.

## 실행이 시작되었지만 시간 초과됨
<a name="automation-trbl-to"></a>

**오류 메시지**: `Step timed out while step is verifying launched instance(s) are ready to be used. Please refer to Automation Service Troubleshooting Guide for more diagnosis details.`

`aws:runInstances` 작업의 단계가 시간 초과되었습니다. 이 오류는 단계 작업이 실행되는 시간이 해당 단계의 `timeoutSeconds`에 지정된 값보다 오래 걸리는 경우에 발생할 수 있습니다. 이 문제를 해결하려면 `aws:runInstances` 작업에서 `timeoutSeconds` 파라미터에 더 긴 값을 지정합니다. 이렇게 해도 문제가 해결되지 않으면 단계가 실행되는 시간이 예상보다 오래 걸리는 이유를 조사합니다.