

• 2026 年 4 月 30 日之後， AWS Systems Manager CloudWatch Dashboard 將不再可用。客戶可以繼續使用 Amazon CloudWatch 主控台來檢視、建立和管理其 Amazon CloudWatch 儀表板，就像現在一樣。如需詳細資訊，請參閱 [Amazon CloudWatch Dashboard 文件](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch_Dashboards.html)。

本文為英文版的機器翻譯版本，如內容有任何歧義或不一致之處，概以英文版為準。

# AWS Systems Manager 自動化
<a name="systems-manager-automation"></a>

自動化是 中的工具 AWS Systems Manager，可簡化常見的維護、部署和修復任務， AWS 服務 例如 Amazon Elastic Compute Cloud (Amazon EC2)、Amazon Relational Database Service (Amazon RDS)、Amazon Redshift、Amazon Simple Storage Service (Amazon S3) 等。若要開始使用自動化，請開啟 [Systems Manager 主控台](https://console.aws.amazon.com/systems-manager/automation)。在導覽窗格中，選擇 **Automation** (自動化)。

Automation 可幫助您建置用於大規模部署、設定和管理 AWS 資源的自動化解決方案。您可以藉助 Automation 精密控制自動化的並行。這意味著您可以指定要同時視為目標的資源數量，以及在停止自動化之前容許發生的錯誤數量。

為了協助您開始使用自動化， AWS 開發和維護數個預先定義的 Runbook。根據自己的使用案例，您可以使用這些預先定義的 Runbook 來執行各種任務，也可以建立自訂 Runbook 來滿足您的需求。若要監控自動化的進度和狀態，可以使用 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 提供這些好處：
+ **Runbook 內容中的指令碼支援**

  您可以使用 `aws:executeScript` 動作，直接從 Runbook 執行自訂 Python 和 PowerShell 函數。這為您提供了更大的靈活性來建立自訂 Runbook，因為您可以完成其他 Automation 動作不支援的各種任務。您還可以更好地控制 Runbook 的邏輯。如需如何使用此動作以及如何幫助改進現有自動化解決方案的範例，請參閱 [撰寫 Automation Runbook](automation-authoring-runbooks.md)。
+  ** AWS 區域 從集中位置跨多個 AWS 帳戶 和 執行自動化** 

  管理員可以從 Systems Manager 主控台對多個帳戶和區域的資源執行自動化。
+  **強化操作安全性** 

  管理員有一個集中位置來授予和撤銷 Runbook 的存取權。使用 only AWS Identity and Access Management (IAM) 政策，您可以控制組織中哪些個別使用者或群組可以使用自動化，以及他們可以存取哪些 Runbook。
+  **自動化 IT 常見任務** 

  自動化常見任務有助於提高運營效率、強制執行組織標準以及減少操作員錯誤。例如，您可以使用 `AWS-UpdateCloudFormationStackWithApproval` Runbook 來更新使用 AWS CloudFormation 範本部署的資源。更新會套用新的範本。您可以設定自動化以請求一個或多個 使用者在更新開始之前核准。
+  **安全執行大量破壞性工作** 

  Automation 包括速率控制等功能，這些功能允許您藉由指定並行值和錯誤閾值來控制自動化在機群中的部署。如需有關使用速率控制功能的詳細資訊，請參閱 [大規模執行自動化操作](running-automations-scale.md)。
+ **簡化複雜任務**

  Automation 提供了預先定義的 Runbook，可簡化複雜而耗時的任務，例如建立黃金 Amazon Machine Images (AMIs)。例如，您可以使用 `AWS-UpdateLinuxAmi` 和 `AWS-UpdateWindowsAmi` Runbook 從來源 AMI 建立黃金 AMIs。使用這些 Runbook，您可以在更新套用前後執行自訂指令碼。您也可以包含或排除安裝特定軟體套件。如需執行這些 Runbook 的範例，請參閱 [教學課程](automation-tutorials.md)。
+ **定義輸入限制條件**

  您可以在自訂 Runbook 中定義限制條件，從而限制 Automation 要接受的特定輸入參數的值。例如：`allowedPattern` 將僅接受與您定義的規則運算式相符之輸入參數的值。如果在輸入參數中指定 `allowedValues`，則系統只接受您在 Runbook 中指定的值。
+  **在 Amazon CloudWatch Logs 中記錄自動化動作的輸出** 

  為了滿足組織中的操作或安全需求，您可能需要提供在 Runbook 執行期間的指令碼記錄。您可使用 CloudWatch Logs 從各種 AWS 服務中監控、存放及存取日誌檔案。您可以將 `aws:executeScript` 動作中的輸出傳送到 CloudWatch Logs 日誌群組，以便進行偵錯和故障診斷。日誌資料可以傳送到您的日誌群組，無論是否使用 KMS 金鑰進行 AWS KMS 加密。如需詳細資訊，請參閱[使用 CloudWatch Logs 記錄自動化動作輸出](automation-action-logging.md)。
+  **Amazon EventBridge 整合** 

  Automation 作為 Amazon EventBridge 規則中的*目標*類型受到支援。這意味著您可以使用事件觸發 Runbook。如需詳細資訊，請參閱 [使用 Amazon EventBridge 監控 Systems Manager](monitoring-eventbridge-events.md) 及 [參考：Systems Manager 的 Amazon EventBridge 事件模式和類型](reference-eventbridge-events.md)。
+ **共用組織最佳實務**

  您可以在跨帳戶和區域共用的 Runbook 中定義資源管理、操作任務等項目的最佳實務。

## 誰應該使用 Automation？
<a name="automation-who"></a>
+ 任何想要大規模改善營運效率、減少與手動介入相關的錯誤，以及縮短解決常見問題的時間 AWS 的客戶。
+ 希望自動化部署和組態任務的基礎設施專家。
+ 希望可靠地解決常見問題、提高疑難排解效率和減少重複性操作的管理員。
+ 希望自動化通常手動執行之任務的使用者。

## 什麼是自動化？
<a name="what-is-an-automation"></a>

*自動化*包含在 Runbook 中定義並由 Automation 服務執行的所有任務。Automation 使用下列元件來執行自動化。


****  

| 概念 | 詳細資訊 | 
| --- | --- | 
|  Automation Runbook  |  Systems Manager Automation Runbook 會定義自動化 (Systems Manager 在受管節點 AWS 和資源上執行的動作）。自動化包含數個預先定義的 Runbook，供您用來執行常見任務，像是重新啟動一個或多個 Amazon EC2 執行個體，或建立 Amazon Machine Image (AMI)。您也可以建立自己的 Runbook。Runbook 使用 YAML 或 JSON，並包含您指定的步驟與參數。步驟會循序執行。如需詳細資訊，請參閱[建立您自己的執行手冊](automation-documents.md)。 Runbook 是類型 `Automation` 的 Systems Manager 文件，而不是 `Command`、`Policy`、`Session` 文件)。Runbook 支援結構描述版本 0.3。命令文件使用結構描述版本 1.2、2.0 或 2.2。政策文件使用結構描述版本 2.0 或更新版本。  | 
|  自動化動作  |  Runbook 中定義的自動化包含一個或多個步驟。每個步驟皆與一個特定動作關聯。動作會決定輸入、行為和步驟的輸出。Runbook 的 `mainSteps` 章節中會定義步驟。自動化支援 20 個不同的動作類型。如需更多資訊，請參閱[Systems Manager Automation 動作參考](automation-actions.md)。  | 
|  自動化配額  |  每個 AWS 帳戶 可以同時執行 100 個自動化。這包括子系自動化 (由另一個自動化啟動的自動化)，以及速率控制自動化。如果您嘗試執行超過此數量的自動化，Systems Manager 會將額外自動化新增至佇列並顯示待定狀態。此配額可以使用適應性並行來調整。如需詳細資訊，請參閱 [允許 Automation 適應並行需求](adaptive-concurrency.md)。如需有關執行自動化的詳細資訊，請參閱 [執行由 Systems Manager Automation 提供支援的自動化操作](running-simple-automations.md)。  | 
|  自動化佇列配額  |  如果您嘗試執行的自動化超過並行自動化限制，則後續的自動化會新增至佇列。每個 AWS 帳戶 可將 5,000 個自動化排入佇列。自動化完成時 (或達到結束狀態)，佇列中的第一個自動化就會啟動。  | 
|  速率控制自動化配額  |  每個 AWS 帳戶 可以同時執行 25 個速率控制自動化。如果您嘗試執行的速率控制自動化超過並行速率控制自動化限制，則 Systems Manager 會將後續速率控制自動化新增至佇列並顯示「待處理」狀態。如需執行速率控制自動化的詳細資訊，請參閱 [大規模執行自動化操作](running-automations-scale.md)。  | 
|  速率控制自動化佇列配額  |  如果您嘗試執行的自動化超過並行速率控制自動化限制，則後續的自動化會新增至佇列。每個 AWS 帳戶 都可以將 1，000 個速率控制自動化排入佇列。自動化完成時 (或達到結束狀態)，佇列中的第一個自動化就會啟動。  | 

**Topics**
+ [Automation 對我組織有何好處？](#automation-benefits)
+ [誰應該使用 Automation？](#automation-who)
+ [什麼是自動化？](#what-is-an-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 Runbook Reference](automation-documents-reference.md)
+ [教學課程](automation-tutorials.md)
+ [了解 Systems Manager Automation 傳回的狀態](automation-statuses.md)
+ [故障診斷 Systems Manager Automation](automation-troubleshooting.md)

# 設定自動化
<a name="automation-setup"></a>

若要在 中設定 Automation 工具 AWS Systems Manager，您必須驗證使用者對 Automation 服務的存取權，並依情況設定角色，以便服務可以對您的資源執行動作。我們也建議您在 Automation 偏好設定中選擇使用自適應並行模式。自適應並行會自動擴展自動化配額來滿足您的需求。如需詳細資訊，請參閱[允許 Automation 適應並行需求](adaptive-concurrency.md)。

若要確保適當存取 AWS Systems Manager 自動化，請檢閱下列使用者和服務角色需求。

## 驗證 Runbook 的使用者存取權
<a name="automation-setup-user-access"></a>

驗證您是否有使用 Runbook 的許可。如果使用者、群組或角色獲指派管理員許可，則您可以存取 Systems Manager Automation。如果您沒有管理員許可，則管理員必須指派 `AmazonSSMFullAccess` 受管政策或提供相當許可的政策給使用者、群組或角色，藉此給予您許可。

**重要**  
IAM 政策 `AmazonSSMFullAccess` 會授予 Systems Manager 動作的許可。不過，有些 Runbook 需要其他服務的許可，例如文件 `AWS-ReleaseElasticIP`，而這需要 `ec2:ReleaseAddress` 的 IAM 許可。因此，您必須檢閱執行手冊中採取的動作，以確保使用者、群組或角色獲指派必要許可，可執行執行手冊中包含的動作。

## 設定自動化的服務角色 (擔任角色) 存取權
<a name="automation-setup-configure-role"></a>

自動化可在服務角色 (或*擔任角色*) 的內容下啟動。這可讓服務代表您執行動作。如果您未指定擔任角色，自動化會使用呼叫自動化的使用者內容。

然而，以下情況仍需要您為自動化指定服務角色：
+ 當您想要限制使用者的資源許可，但您想要使用者執行需要更高許可的自動化時。在此案例中，您可以建立具更高許可的服務角色並允許使用者執行自動化。
+ 當您建立執行 Runbook 的 Systems Manager State Manager 關聯。
+ 當您有預期會執行超過 12 小時的操作時。
+ 當您執行非 Amazon 擁有的 Runbook 時，該 Runbook 會使用 `aws:executeScript`動作來呼叫 AWS API 操作或對 AWS 資源採取行動。如需相關資訊，請參閱[使用 Runbook 的許可](automation-document-script-considerations.md#script-permissions)。

如果需要為自動化建立服務角色，您可以使用以下其中一個方法。

**Topics**
+ [驗證 Runbook 的使用者存取權](#automation-setup-user-access)
+ [設定自動化的服務角色 (擔任角色) 存取權](#automation-setup-configure-role)
+ [使用 建立自動化的服務角色 CloudFormation](automation-setup-cloudformation.md)
+ [使用主控台建立用於自動化的服務角色](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
<a name="automation-setup-cloudformation"></a>

您可以從 AWS CloudFormation 範本為 中的工具 Automation AWS Systems Manager建立服務角色。在您建立服務角色之後，您可以使用參數 `AutomationAssumeRole` 在 Runbook 中指定服務角色。

## 使用 建立服務角色 CloudFormation
<a name="create-iam-service-role"></a>

使用下列程序建立 Systems Manager Automation 所需的 AWS Identity and Access Management (IAM) 角色 CloudFormation。

**建立必要的 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. 在 https：//[https://console.aws.amazon.com/cloudformation](https://console.aws.amazon.com/cloudformation/) 開啟 CloudFormation 主控台。

1. 選擇 **Create Stack** (建立堆疊)。

1. 在 **Specify template (指定範本)** 區段中，選擇 **Upload a template file (上傳範本檔案)**。

1. 選擇**瀏覽**，然後選擇`AWS-SystemsManager-AutomationServiceRole.yaml` CloudFormation 範本檔案。

1. 選擇**下一步**。

1. 在 **Specify stack details (指定堆疊詳細資訊)** 頁面，於 **Stack name (堆疊名稱)** 欄位輸入名稱。

1. 在 **Configure stack options (設定堆疊選項)** 頁面上，您不需要進行任何選取。選擇**下一步**。

1. 在**檢閱**頁面上，向下捲動並選擇**我確認 CloudFormation 可能會建立 IAM 資源**選項。

1. 選擇**建立**。

CloudFormation 會顯示 **CREATE\$1IN\$1PROGRESS** 狀態大約三分鐘。在堆疊建立且您的角色可使用之後，狀態會變更為 **CREATE\$1COMPLETE (CREATE\$1COMPLETE)**。

**重要**  
如果您執行可使用 AWS Identity and Access Management (IAM) 服務角色叫用其他服務的自動化工作流程，請注意您必須為該服務角色設定可叫用這些服務的許可。此要求適用於所有 AWS Automation Runbook (`AWS-*` Runbook)，例如 `AWS-ConfigureS3BucketLogging`、 `AWS-CreateDynamoDBBackup`和 `AWS-RestartEC2Instance` Runbook。此要求也適用於您建立的任何自訂 Automation Runbook， AWS 服務 透過使用呼叫其他 服務的動作來叫用其他 。例如，如果您使用 `aws:executeAwsApi`、`aws:createStack` 或 `aws:copyImage` 動作，為服務角色設定可叫用這些服務的許可。您可新增 IAM 內嵌政策到角色，以啟用其他 AWS 服務 的許可。如需詳細資訊，請參閱[（選用） 新增自動化內嵌政策或客戶受管政策以叫用其他 AWS 服務](automation-setup-iam.md#add-inline-policy)。

## 複製自動化的角色資訊
<a name="copy-iam-role-info"></a>

使用下列程序，從 CloudFormation 主控台複製自動化服務角色的相關資訊。使用 Runbook 時，必須指定這些角色。

**注意**  
如果您執行 `AWS-UpdateLinuxAmi` 或 `AWS-UpdateWindowsAmi` Runbook，則不需要使用此程序複製角色資訊。這些 Runbook 已將所需的角色指定為預設值。這些 Runbook 中指定的角色使用 IAM 受管政策。

**複製角色名稱**

1. 在 https：//[https://console.aws.amazon.com/cloudformation](https://console.aws.amazon.com/cloudformation/) 開啟 CloudFormation 主控台。

1. 選取您在上一個程序中建立的自動化 **Stack name (堆疊名稱)**。

1. 選擇 **Resources** (資源) 標籤。

1. 為 **AutomationServiceRole** 選擇 **Physical ID** (實體 ID) 連結。IAM 主控台會開啟自動化服務角色的摘要。

1. 複製 **Role ARN (角色 ARN)** 旁邊的 Amazon Resource Name (ARN)。ARN 的格式類似如下：`arn:aws:iam::12345678:role/AutomationServiceRole`

1. 將 ARN 貼入文字檔案以供日後使用。

您已完成自動化服務角色的設定。您現在可以在 Runbook 中使用 Automation 服務角色 ARN。

# 使用主控台建立用於自動化的服務角色
<a name="automation-setup-iam"></a>

如果您需要為 中的工具 Automation 建立服務角色 AWS Systems Manager，請完成下列任務。如需 Automation 需要服務角色之時機的詳細資訊，請參閱 [設定自動化](automation-setup.md)。

**Topics**
+ [任務 1：建立自動化的服務角色](#create-service-role)
+ [任務 2：將 iam:PassRole 政策連接至自動化角色](#attach-passrole-policy)

## 任務 1：建立自動化的服務角色
<a name="create-service-role"></a>

使用下列處理程序以建立 Systems Manager Automation 的服務角色 (或*擔任角色*)。

**注意**  
您也可以在 Runbook 中使用此角色，例如 `AWS-CreateManagedLinuxInstance` Runbook。在 Runbook 中使用此角色或 (IAM) 角色的 Amazon Resource Name AWS Identity and Access Management (ARN)，可讓自動化在您的環境中執行動作，例如啟動新的執行個體並代表您執行動作。

**建立 IAM 角色並允許 Automation 擔任角色**

1. 在以下網址開啟 IAM 主控台：[https://console.aws.amazon.com/iam/](https://console.aws.amazon.com/iam/)。

1. 在導覽窗格中，選擇 **Roles (角色)**，然後選擇 **Create role (建立角色)**。

1. 在 **Select type of trusted entity** (選擇可信任執行個體類型) 下，選擇 **AWS service** ( 服務)。

1. 在 **Choose a use case (選擇使用案例)** 區段中，選擇 **Systems Manager (系統管理員)**，然後選擇 **Next: Permissions (下一步：許可)**。

1. 在 **Attached permissions policy (已連接許可政策)** 頁面，搜尋 **AmazonSSMAutomationRole** 政策，選取該政策，接著選擇 **Next: Review (下一步：檢閱)**。

1. 在 **Review** (檢閱) 頁面，於 **Role name** (角色名稱) 方塊輸入名稱，接著輸入描述。

1. 選擇 **Create role** (建立角色)。系統會讓您回到 **Roles (角色)** 頁面。

1. 在 **Roles (角色)** 頁面，選擇您剛建立的角色，以開啟 **Summary (摘要)** 頁面。請記下 **Role Name (角色名稱)** 和 **Role ARN (角色 ARN)**。將 **iam:PassRole** 政策連接至下個程序中的 IAM 帳戶時，您要指定角色 ARN。您也可以在 Runbook 中指定角色名稱和 ARN。

**注意**  
`AmazonSSMAutomationRole` 政策會將自動化角色許可指派給您帳戶中的 AWS Lambda 函數子集。這些函數會以 "Automation" 開頭。如果您打算使用 Automation 搭配 Lambda 函數，Lambda ARN 必須使用以下格式：  
`"arn:aws:lambda:*:*:function:Automation*"`  
如果您現有的 Lambda 函數之 ARN 不使用此格式，則您還必須將額外的 Lambda 政策連接至您的自動化角色，例如 **AWSLambdaRole** 政策。額外的政策或角色必須針對 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` 值不包含帳戶 ID (例如 Amazon Simple Storage Service (Amazon S3) 儲存貯體 ARN)，則必須使用這兩個全域條件內容索引鍵來限制許可。如果同時使用這兩個全域條件內容索引鍵，且 `aws:SourceArn` 值包含帳戶 ID，則在相同政策陳述式中使用 `aws:SourceAccount` 值和 `aws:SourceArn` 值中的帳戶時，必須使用相同的帳戶 ID。如果您想要僅允許一個資源與跨服務存取相關聯，則請使用 `aws:SourceArn`。如果您想要允許該帳戶中的任何資源與跨服務使用相關聯，請使用 `aws:SourceAccount`。`aws:SourceArn` 的值必須是自動化執行的 ARN。如果不知道資源的完整 ARN，或者如果您指定了多個資源，請使用 `aws:SourceArn` 全域條件內容索引鍵，同時使用萬用字元 (`*`) 表示 ARN 的未知部分。例如 `arn:aws:ssm:*:123456789012:automation-execution/*`。

下列範例示範如何使用 Automation 的 `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. 在導覽窗格中，選擇 **Roles** (角色)。

1. 在帳戶的角色清單中選擇 Automation 服務角色的名稱。

1. 選擇 **Trust Relationships (信任關係)** 標籤，然後選擇 **Edit Trust Relationship (編輯信任關係)**。

1. 使用 Automation 的 `aws:SourceArn` 和 `aws:SourceAccount` 全域條件內容索引鍵來編輯信任政策，幫助預防混淆代理人問題。

1. 若要儲存變更，請選擇 **Update Trust Policy** (更新信任政策)。

### （選用） 新增自動化內嵌政策或客戶受管政策以叫用其他 AWS 服務
<a name="add-inline-policy"></a>

如果您執行 AWS 服務 使用 IAM 服務角色叫用其他 的自動化，則服務角色必須設定具有叫用這些服務的許可。此需求適用於所有 AWS Automation Runbook (`AWS-*` Runbook)，例如 `AWS-ConfigureS3BucketLogging`、 `AWS-CreateDynamoDBBackup`和 `AWS-RestartEC2Instance` Runbook。此要求也適用於您所建立會透過呼叫其他服務的動作來叫用其他 AWS 服務 的任何自訂 Runbooks。例如，如果您使用 `aws:executeAwsApi`、`aws:CreateStack` 或 `aws:copyImage` 等動作，則您必須為服務角色設定可叫用這些服務的許可。您可以將 IAM 內嵌政策或客戶受管政策新增至角色， AWS 服務 以將許可授予其他 。

**嵌入服務角色的內嵌政策 (IAM 主控台)**

1. 登入 AWS 管理主控台 ，並在 https：//[https://console.aws.amazon.com/iam/](https://console.aws.amazon.com/iam/) 開啟 IAM 主控台。

1. 在導覽窗格中，選擇**角色**。

1. 在清單中，選擇您要編輯的角色名稱。

1. 選擇**許可**索引標籤。

1. 在**新增許可**下拉式選單中，選擇**連接政策**或**建立內嵌政策**。

1. 如果選擇**連接政策**，請選取您要新增之政策旁邊的核取方塊，然後選擇**新增許可**。

1. 如果選擇**建立政策**，請選擇 **JSON** 索引標籤。

1. 為 AWS 服務 您要叫用的 輸入 JSON 政策文件。以下是兩個 JSON 政策文件範例。

   **Amazon Simple Storage Service (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 使用者指南**》中的 [IAM JSON 政策參考](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies.html)。

1. 完成時，請選擇 **Review policy (檢閱政策)**。[Policy Validator](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_policy-validator.html) (政策檢查工具) 會回報任何語法錯誤。

1. 在 **Review policy** (檢閱政策) 頁面，輸入您所建立政策的 **Name** (名稱)。檢閱政策 **Summary** (摘要) 來查看您的政策所授予的許可。然後選擇 **Create policy (建立政策)** 來儲存您的工作。

1. 在您建立內嵌政策後，它會自動嵌入您的角色中。

## 任務 2：將 iam:PassRole 政策連接至自動化角色
<a name="attach-passrole-policy"></a>

使用以下程序將 `iam:PassRole` 政策連接至您的自動化服務角色。這可讓 Automation 服務在執行自動化時，將角色傳遞至其他服務或 Systems Manager 工具。

**將 iam: PassRole 政策連接至您的自動化角色**

1. 在您剛建立的角色之 **Summary (摘要)** 頁面，選擇 **Permissions (許可)** 標籤。

1. 選擇**新增內嵌政策**。

1. 在 **Create policy (建立政策)** 頁面，選擇 **Visual editor (視覺化編輯器)** 標籤。

1. 選擇 **Service (服務)**，接著選擇 **IAM (IAM)**。

1. 選擇 **Select actions (選取動作)**。

1. 在 **Filter actions (篩選動作)** 文字方塊中輸入 **PassRole**，接著選擇 **PassRole** 選項。

1. 選擇**資源**。確認 **Specific (特定)** 已選取，接著選擇 **Add ARN (新增 ARN)**。

1. 在 **Specify ARN for role (指定角色的 ARN)** 欄位中，貼上您在任務 1 結尾複製的自動化角色 ARN。系統會填入 **Account (帳戶)** 和 **Role name with path (角色名稱與路徑)** 欄位。
**注意**  
如果您想要自動化服務角色將 IAM 執行個體設定檔角色連接到 EC2 執行個體，則必須新增 IAM 執行個體設定檔角色的 ARN。這可讓自動化服務角色傳遞 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)。 **

**注意**  
所有範例都包含虛構的帳戶 IDs。不應在 Amazon Resource Name (ARN) 中為 AWS 擁有的公有文件指定帳戶 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 管理主控台**

1. 在 https：//[https://console.aws.amazon.com/systems-manager/](https://console.aws.amazon.com/systems-manager/) 開啟 AWS Systems Manager 主控台。

1. 在導覽窗格中，選擇 **Automation** (自動化)。

1. 選擇 **Preferences (偏好)** 標籤，然後選擇 **Edit (編輯)**。

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 管理主控台**

1. 在 https：//[https://console.aws.amazon.com/systems-manager/](https://console.aws.amazon.com/systems-manager/) 開啟 AWS Systems Manager 主控台。

1. 在導覽窗格中，選擇 **Automation** (自動化)。

1. 選擇 **Preferences (偏好)** 標籤，然後選擇 **Edit (編輯)**。

1. 在**限流重試時間限制**欄位中，輸入介於 0 到 3,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 會允許您使用沒有日期和時間限制的執行手冊。透過整合自動化與 Change Calendar，您可以對 中的所有自動化實作變更控制 AWS 帳戶。透過此設定，您帳戶中的 AWS Identity and Access Management (IAM) 主體只能在變更行事曆允許的期間內執行自動化。若要進一步了解 Change Calendar 的使用，請參閱 [使用 Change Calendar](systems-manager-change-calendar-working.md)。

**開啟變更控制 (主控台)**

1. 在 https：//[https://console.aws.amazon.com/systems-manager/](https://console.aws.amazon.com/systems-manager/) 開啟 AWS Systems Manager 主控台。

1. 在導覽窗格中，選擇 **Automation** (自動化)。

1. 選擇 **Preferences (偏好)** 標籤，然後選擇 **Edit (編輯)**。

1. 選取**開啟 Change Calendar 整合**旁的核取方塊。

1. 在**選擇變更行事曆**下拉式清單中，選擇您希望 Automation 追蹤的變更行事曆。

1. 選擇**儲存**。

# 執行由 Systems Manager Automation 提供支援的自動化操作
<a name="running-simple-automations"></a>

執行自動化時，依預設，自動化會在啟動自動化的使用者內容中執行。這表示，如果您的使用者具有管理員許可，則自動化會以管理員許可執行，並能完全存取由自動化設定的資源。做為安全最佳實務，我們建議您在執行自動化時，使用以 AmazonSSMAutomationRole 受管政策設定的 IAM 服務角色，在此案例中稱為*擔任*角色。您可能需要將其他 IAM 政策新增至您的擔任角色，才能使用各種 Runbook。使用 IAM 服務角色執行自動化稱為*委託管理*。

在您使用服務角色時，自動化允許對 AWS 資源執行，但執行自動化的使用者限制了對這些資源的存取 (或無存取)。例如，您可以設定服務角色並搭配 Automation 使用，以重新啟動一個或多個 Amazon Elastic Compute Cloud (Amazon EC2) 執行個體。Automation 是 AWS Systems Manager中的工具。自動化會重新啟動執行個體，但服務角色不會提供存取這些執行個體的使用者許可。

您可以在執行自動化時指定執行時間的服務角色，或者您可以建立自訂 Runbook 並直接在 Runbook 中指定服務角色。如果您指定服務角色 (在執行時間或在 Runbook 中)，則服務會在指定服務角色的內容中執行。如果您不指定服務角色，則系統會在使用者的內容中建立暫時工作階段並執行自動化。

**注意**  
針對預期要執行超過 12 小時的自動化，您必須指定服務角色。如果您在使用者的內容中啟動長期執行自動化，使用者的暫時工作階段會在 12 小時後過期。

委派管理可確保您的 AWS 資源有更高層級的安全和控制。它也能夠強化稽核體驗，因為動作是由中央服務角色，而非多個 IAM 帳戶針對您的資源執行的。

**開始之前**  
在完成下列程序之前，您必須建立 IAM 服務角色並設定 Automation 的信任關係，這是其中的工具 AWS Systems Manager。如需詳細資訊，請參閱[任務 1：建立自動化的服務角色](automation-setup-iam.md#create-service-role)。

以下程序說明如何使用 Systems Manager 主控台或您偏好的命令行來執行簡易的自動化。

## 執行簡易自動化 (主控台)
<a name="simple-console"></a>

以下程序說明如何使用 Systems Manager 主控台來執行簡易的自動化。

**執行簡易自動化**

1. 在 https：//[https://console.aws.amazon.com/systems-manager/](https://console.aws.amazon.com/systems-manager/) 開啟 AWS Systems Manager 主控台。

1. 在導覽窗格中，選擇 **Automation (自動化)**，接著選擇 **Execute automation (執行自動化)**。

1. 在 **Automation document** (自動化文件) 清單中，選擇 Runbook。在 **Document categories** (文件類別) 窗格中選擇一個或多個選項，根據 SSM 文件的用途來進行篩選。若要檢視您擁有的 Runbook，請選擇 **Owned by me** (我所擁有的) 索引標籤。若要檢視與您帳戶共用的 Runbook，請選擇 **Shared with me** (與我共用的) 索引標籤。若要檢視所有 Runbook，請選擇 **All documents** (所有文件) 索引標籤。
**注意**  
您可以選擇 Runbook 名稱檢視 Runbook 資訊。

1. 在 **Document details** (文件詳細資訊) 部分，確認 **Document version** (文件版本) 設定為您想要執行的版本。系統包括以下版本選項：
   + **執行期的預設版本**：如果 Automation 執行手冊會定期更新且已指派新的預設版本，則請選擇此選項。
   + **執行期的最新版本**：如果 Automation 執行手冊會定期更新，而您想要執行最近更新的版本，請選擇此選項。
   + **1 (預設)**：選擇此選項以執行文件的第一個版本，也是預設版本。

1. 選擇**下一步**。

1. 在 **Execution Mode (執行模式)** 部分，選擇 **Simple execution (簡易執行)**。

1. 在 **Input parameters (輸入參數)** 部分，指定所需的輸入。或者，您也可以從 **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. 選擇 **Execute (執行)**。

主控台會顯示自動化的狀態。若自動化無法執行，請參閱 [故障診斷 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 Tools for PowerShell如果您尚未安裝和設定 AWS CLI 或 。

   如需相關資訊，請參閱[安裝或更新 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 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` Runbook 重新啟動指定 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 主控台來重新執行自動化執行。

**從 Automation 首頁重新執行自動化執行**

在 https：//[https://console.aws.amazon.com/systems-manager/](https://console.aws.amazon.com/systems-manager/) 開啟 AWS Systems Manager 主控台。

1. 在導覽窗格中，選擇 **Automation** (自動化)。

1. 在執行清單中，選取您想要重新執行的執行。

1. 選擇**重新執行執行**。

1. 在**執行自動化文件**頁面上，檢閱原始執行中預先填入的參數、執行模式和目標組態。

1. (選用) 針對您的重新執行，視需要修改任何參數、目標或其他設定。

1. 選擇**執行**，以使用新的執行 ID 開始重新執行。

**從執行詳細資訊頁面重新執行自動化執行**

在 https：//[https://console.aws.amazon.com/systems-manager/](https://console.aws.amazon.com/systems-manager/) 開啟 AWS Systems Manager 主控台。

1. 在導覽窗格中，選擇 **Automation** (自動化)。

1. 選擇您想要重新執行之自動化的執行 ID。

1. 在執行詳細資訊頁面上，選擇**重新執行執行**。

1. 在**執行自動化文件**頁面上，檢閱原始執行中預先填入的參數、執行模式和目標組態。

1. (選用) 針對您的重新執行，視需要修改任何參數、目標或其他設定。

1. 選擇**執行**，以使用新的執行 ID 開始重新執行。

**將自動化執行複製到新執行**

在 https：//[https://console.aws.amazon.com/systems-manager/](https://console.aws.amazon.com/systems-manager/) 開啟 AWS Systems Manager 主控台。

1. 在導覽窗格中，選擇 **Automation** (自動化)。

1. 選擇您想要複製之自動化的執行 ID。

1. 在執行詳細資訊頁面上，選擇**動作**，然後選擇**複製到新的**。

1. 在**執行自動化文件**頁面上，檢閱原始執行中預先填入的參數、執行模式和目標組態。

1. (選用) 針對您的新執行，視需要修改任何參數、目標或其他設定。

1. 選擇**執行**，以開始新執行。

# 執行需要核准的自動化
<a name="running-automations-require-approvals"></a>

下列程序說明如何使用 AWS Systems Manager 主控台和 AWS Command Line Interface (AWS CLI) 透過使用簡單執行的核准來執行自動化。自動化使用自動化動作 `aws:approve`，這會臨時暫停自動化，直到指定的委託人核准或拒絕動作為止。自動化會在目前的使用者內容中執行。這表示只要有使用 Runbook 和 Runbook 所呼叫任何動作的許可，您就不必設定其他的 IAM 許可。如果您在 IAM 中有管理員許可，您便已經有執行此 Runbook 的許可。

**開始之前**  
除了 Runbook 需要的標準輸入，`aws:approve` 動作需要以下兩個參數：
+ 核准者清單。核准者清單必須至少包含一個核准者，形式為使用者名稱或使用者 ARN。如果提供多個核准者，必須在 Runbook 指定對應的最低核准計數。
+ Amazon Simple Notification Service (Amazon SNS) 主題 ARN。Amazon SNS 主題名稱必須以 `Automation` 開頭。

此程序假設您已經建立一個 Amazon SNS 主題，其為交付核准請求所需。如需資訊，請參閱 *Amazon Simple Notification Service 開發人員指南*中的[建立主題](https://docs.aws.amazon.com/sns/latest/dg/sns-getting-started.html#CreateTopic)。

## 以核准者身分執行自動化 (主控台)
<a name="approval-console"></a>

**以核准者身分執行自動化**

以下程序說明如何使用 Systems Manager 主控台以核准者身分執行自動化。

1. 在 https：//[https://console.aws.amazon.com/systems-manager/](https://console.aws.amazon.com/systems-manager/) 開啟 AWS Systems Manager 主控台。

1. 在導覽窗格中，選擇 **Automation (自動化)**，接著選擇 **Execute automation (執行自動化)**。

1. 在 **Automation document** (自動化文件) 清單中，選擇 Runbook。在 **Document categories** (文件類別) 窗格中選擇一個或多個選項，根據 SSM 文件的用途來進行篩選。若要檢視您擁有的 Runbook，請選擇 **Owned by me** (我所擁有的) 索引標籤。若要檢視與您帳戶共用的 Runbook，請選擇 **Shared with me** (與我共用的) 索引標籤。若要檢視所有 Runbook，請選擇 **All documents** (所有文件) 索引標籤。
**注意**  
您可以選擇 Runbook 名稱檢視 Runbook 資訊。

1. 在 **Document details** (文件詳細資訊) 部分，確認 **Document version** (文件版本) 設定為您想要執行的版本。系統包括以下版本選項：
   + **執行期的預設版本**：如果 Automation 執行手冊會定期更新且已指派新的預設版本，則請選擇此選項。
   + **執行期的最新版本**：如果 Automation 執行手冊會定期更新，而您想要執行最近更新的版本，請選擇此選項。
   + **1 (預設)**：選擇此選項以執行文件的第一個版本，也是預設版本。

1. 選擇**下一步**。

1. 在 **Execute automation document (執行自動化文件)** 頁面上，選擇 **Simple execution (簡易執行)**。

1. 在 **Input Parameters (輸入參數)** 部分，指定所需的輸入參數。

   例如，如果您選擇 `AWS-StartEC2InstanceWithApproval` Runbook，則必須指定或選擇 **InstanceId** 參數的執行個體 ID。

1. 在**核准者**區段，指定自動化動作核准者的使用者名稱或使用者 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。

若您選擇核准自動化，自動化會繼續執行指定 Runbook 中所包含的步驟。主控台會顯示自動化的狀態。若自動化無法執行，請參閱 [故障診斷 Systems Manager Automation](automation-troubleshooting.md)。

**核准或拒絕自動化**

1. 在 https：//[https://console.aws.amazon.com/systems-manager/](https://console.aws.amazon.com/systems-manager/) 開啟 AWS Systems Manager 主控台。

1. 在導覽窗格中選擇 **Automation** (自動化)，然後選取在先前程序中執行的自動化。

1. 選擇 **Actions (動作)**，然後選擇 **Approve/Deny (核准/拒絕)**。

1. 選擇 **Approve (核准)** 或 **Deny (拒絕)**，並選擇性地提供註解。

1. 選擇**提交**。

## 以核准者身分執行自動化 (命令列)
<a name="approval-cli"></a>

下列程序說明如何使用 AWS CLI （在 Linux 或 Windows 上） 或 AWS Tools for PowerShell 搭配核准者執行自動化。

**以核准者身分執行自動化**

1.  AWS Tools for PowerShell如果您尚未安裝和設定 AWS CLI 或 。

   如需相關資訊，請參閱[安裝或更新 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. 執行以下命令，以核准者身分執行自動化。將每個*範例資源預留位置*取代為您自己的資訊。在文件名稱區段中，指定包含自動化動作 `aws:approve` 的 Runbook。

   在 `Approvers` 中，指定動作核准者的使用者名稱或使用者 ARN。在 `SNSTopic` 中，指定要用來傳送核准通知的 SNS 主題 ARN。Amazon SNS 主題名稱必須以 `Automation` 開頭。
**注意**  
核准者參數值的特定名稱和 SNS 主題取決於您所選擇 Runbook 中指定的值。

------
#### [ 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
   ```

------

**核准自動化**
+ 執行以下命令，核准自動化。將每個*範例資源預留位置*取代為您自己的資訊。

------
#### [ 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"}
  ```

------

  如果命令成功，則無輸出訊息。

**拒絕自動化**
+ 執行以下命令，拒絕自動化。將每個*範例資源預留位置*取代為您自己的資訊。

------
#### [ 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 自動化，您可以使用*目標*在 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. 在 https：//[https://console.aws.amazon.com/systems-manager/](https://console.aws.amazon.com/systems-manager/) 開啟 AWS Systems Manager 主控台。

1. 在導覽窗格中，選擇 **Automation (自動化)**，接著選擇 **Execute automation (執行自動化)**。

1. 在 **Automation document** (自動化文件) 清單中，選擇 Runbook。在 **Document categories** (文件類別) 窗格中選擇一個或多個選項，根據 SSM 文件的用途來進行篩選。若要檢視您擁有的 Runbook，請選擇 **Owned by me** (我所擁有的) 索引標籤。若要檢視與您帳戶共用的 Runbook，請選擇 **Shared with me** (與我共用的) 索引標籤。若要檢視所有 Runbook，請選擇 **All documents** (所有文件) 索引標籤。
**注意**  
您可以選擇 Runbook 名稱檢視 Runbook 資訊。

1. 在 **Document details** (文件詳細資訊) 部分，確認 **Document version** (文件版本) 設定為您想要執行的版本。系統包括以下版本選項：
   + **執行期的預設版本**：如果 Automation 執行手冊會定期更新且已指派新的預設版本，則請選擇此選項。
   + **執行期的最新版本**：如果 Automation 執行手冊會定期更新，而您想要執行最近更新的版本，請選擇此選項。
   + **1 (預設)**：選擇此選項以執行文件的第一個版本，也是預設版本。

1. 選擇**下一步**。

1. 在 **Execution Mode (執行模式)** 部分，選擇 **Rate Control (速率控制)**。如果想要使用目標和速率控制，就必須使用此模式或 **Multi-account and Region (多帳戶和區域)**。

1. 在 **Targets** (目標) 部分，選擇您想如何將要執行自動化的 AWS 資源設為目標。這些選項是必要的。

   1. 使用 **Parameter (參數)** 清單選擇一個參數。**Parameter** (參數) 清單中的項目，是由您在此程序一開始所選取自動化 Runbook 中的參數決定。藉由選擇參數，您就會定義自動化工作流程執行的資源類型。

   1. 使用 **Targets (目標)** 清單選擇您想要如何將資源設為目標。

      1. 如果您選擇使用參數值將資源設為目標，則請在 **Input parameters** (輸入參數) 區段為您所選的參數輸入參數值。

      1. 如果您選擇使用 將資源設為目標 AWS Resource Groups，請從資源群組清單中選擇**群組**的名稱。

      1. 如果您選擇使用標籤將資源設為目標，請在提供的欄位中輸入標籤索引鍵 (選用) 和標籤值。選擇**新增**。

      1. 如果您想要在目前 AWS 帳戶 和 中的所有執行個體上執行 Automation Runbook AWS 區域，請選擇**所有執行個體**。

1. 在 **Input parameters (輸入參數)** 部分，指定所需的輸入。或者，您也可以從 **AutomationAssumeRole** 清單中選擇 IAM 服務角色。
**注意**  
您可能不必選擇 **Input parameters** (輸入參數) 部分的其中一些選項。這是因為您使用標籤或資源群組將資源設為目標。例如，假設您選擇了 `AWS-RestartEC2Instance` Runbook，就不必在 **Input parameters** (輸入參數) 部分指定或選擇執行個體 ID。自動化執行會使用您指定的標籤或資源組找出要重新啟動的執行個體。

1. 使用**速率控制**區段中的選項，限制可在每個帳戶區域對內執行自動化 AWS 的資源數量。

   在 **Concurrency (並行)** 部分，選擇一個選項：
   + 選擇 **targets (目標)**，輸入可以同時執行自動化工作流程的目標絕對數量。
   + 選擇 **percentage (百分比)**，輸入可以同時執行自動化工作流程的目標集百分比。

1. 在 **Error threshold (錯誤閾值)** 部分，選擇一個選項：
   + 選擇 **errors (錯誤)**，輸入在自動化停止傳送工作流程至其他資源之前允許的錯誤絕對數量。
   + 選擇 **percentage (百分比)**，輸入在自動化停止傳送工作流程至其他資源之前允許的錯誤百分比。

1. (選用) 選擇要套用至您的自動化以便加以監控的 CloudWatch 警示。若要將 CloudWatch 警示連接至您的自動化，啟動自動化的 IAM 主體必須具備 `iam:createServiceLinkedRole` 動作的許可。如需有關 CloudWatch 警示的詳細資訊，請參閱[使用 Amazon CloudWatch 警示](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/AlarmThatSendsEmail.html)。請注意，如果您的警示啟用，則會停止自動化。如果您使用 AWS CloudTrail，您會在線索中看到 API 呼叫。

1. 選擇 **Execute (執行)**。

若要檢視由您的速率控制自動化啟動的自動化，請在導覽窗格中選擇 Automation，接著選取 **Show child automations** (顯示子系自動化)。

自動化執行完成後，您可以使用相同或修改後的參數將執行重新執行。如需詳細資訊，請參閱[重新執行自動化執行](automation-rerun-executions.md)。

## 以目標和速率控制執行自動化 (命令列)
<a name="scale-cli"></a>

下列程序說明如何使用 AWS CLI （在 Linux 或 Windows 上） 或 AWS Tools for PowerShell 執行具有目標和速率控制的自動化。

**以目標和速率控制執行自動化**

1.  AWS Tools for PowerShell如果您尚未安裝和設定 AWS CLI 或 。

   如需相關資訊，請參閱[安裝或更新 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
   ```

------

   請注意您要使用的 Runbook 名稱。

1. 執行以下命令來檢視您建立的 Runbook 詳細資訊。把 *Runbook 名稱*取代為您要檢視其詳細資料的 Runbook 名稱。此外，記下您希望用於`--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. 建立命令以使用您想要執行的目標和速率控制選項。將每個*範例資源預留位置*取代為您自己的資訊。

   「使用標籤設定目標」**

------
#### [ 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 帳戶 和 中的所有 Amazon EC2 執行個體 AWS 區域*

------
#### [ 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}
   ```

------
**注意**  
您也可以在主控台中監控自動化的狀態。在 **Automation executions** (自動化執行清單) 中，選擇您剛執行的自動化，接著選擇 **Execution steps** (執行步驟) 標籤。此索引標籤會顯示自動化動作的狀態。

# 對應自動化的目標
<a name="running-automations-map-targets"></a>

使用 `Targets` 參數迅速定義自動化以哪些資源為目標。例如，假設您想要執行自動化以重新啟動受管執行個體，您可以使用 `Targets` 參數指定 Amazon Elastic Compute Cloud (Amazon EC2) 標籤，以選定執行個體作為目標，而不必手動在主控台選擇或在命令中輸入數十個執行個體 ID。

當您執行使用目標的自動化時， 會為每個目標 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>

您可以指定單一標籤做為自動化目標。許多 AWS 資源支援標籤，包括 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 資源上執行自動化。標籤是一種索引鍵/值組，例如 Operating\$1System:Linux 或 Department:Finance。如果您將特定名稱指派到資源，則您也可以使用「Name」這個詞做為索引鍵，以資源的名稱做為值。

當您指定標籤做為自動化的目標，您也要指定目標參數。目標參數會使用 `TargetParameterName` 選項。藉由選擇目標參數，您就會定義自動化執行的資源類型。您以標籤指定的目標參數必須是在 Runbook 中定義的有效參數。例如，假設您想要使用標籤將數十個 EC2 執行個體設為目標，請選擇 `InstanceId` 目標參數。選擇此參數後，您就會將*執行個體*定義為自動化的資源類型。建立自訂執行手冊時，必須將**目標類型**指定為 `/AWS::EC2::Instance` 以確保僅使用執行個體。否則，具有相同標籤的所有資源都將會成為目標。把帶有標籤的執行個體設為目標時，可能會包括已終止的執行個體。

下列螢幕擷取畫面會使用 `AWS-DetachEBSVolume` Runbook。邏輯目標參數為 `VolumeId`。

![\[使用標籤作為 Systems Manager Automation 的目標\]](http://docs.aws.amazon.com/zh_tw/systems-manager/latest/userguide/images/automation-rate-control-tags-1-new.png)


`AWS-DetachEBSVolume` Runbook 還包含名為 **Target type** (目標類型) 的特殊屬性，設定為 `/AWS::EC2::Volume`。這表示如果標籤鍵對 `Finance:TestEnv` 傳回不同類型的資源 (例如 EC2 執行個體、Amazon EBS 磁碟區、Amazon EBS 快照)，則只會使用 Amazon EBS 磁碟區。

**重要**  
目標參數名稱都區分大小寫。如果您使用 AWS Command Line Interface (AWS CLI) 或 執行自動化 AWS Tools for Windows PowerShell，則必須完全依照 Runbook 中的定義輸入目標參數名稱。如果不這麼做，系統會傳回 `InvalidAutomationExecutionParametersException` 錯誤。您可以使用 [DescribeDocument](https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_DescribeDocument.html) API 操作查看特定 Runbook 中可用目標參數的資訊。以下是範例 AWS CLI 命令，該命令提供有關 `AWS-DeleteSnapshot` 文件的資訊。  

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

以下是一些使用 標籤以資源為目標的範例 AWS CLI 命令。

**範例 1：使用索引鍵/值組將標籤設為目標以重新啟動 Amazon EC2 執行個體**

此範例會重新啟動所有以 *Department* 為索引鍵和 *HumanResources* 為值標記的 Amazon EC2 執行個體。目標參數使用 Runbook 的 *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` Runbook 刪除所有索引鍵為 *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 Group 中的每個物件建立子系自動化。

例如，假設您的一個 Resource Groups 名稱為 PatchedAMIs。此 Resource Group 包括一份清單，有 25 個定期修補的 Windows Amazon Machine Images (AMIs)。如果您執行使用 `AWS-CreateManagedWindowsInstance` Runbook 的自動化並以此 Resource Group 為目標，則 Systems Manager 會為 25 個 AMIs 各建立一個子自動化。這表示以 PatchedAMIs 資源群組為目標後，自動化就會從已修補 AMIs 的清單建立 25 個執行個體。所有子自動化完成處理或達到最終狀態時，父自動化就會完成。

下列 AWS CLI 命令適用於 PatchAMIs 資源群組範例。命令會針對 `--target-parameter-name` 選項採用 *AmiId* 參數。命令不會包括其他參數以定義要從各個 AMI 建立哪種類型的執行個體。`AWS-CreateManagedWindowsInstance` Runbook 文件預設為 t2.medium 執行個體類型，所以此命令會為 Windows Server 建立 25 個 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/zh_tw/systems-manager/latest/userguide/images/automation-rate-control-resource-groups-new.png)


## 將參數值設為目標
<a name="target-parameter-values"></a>

您也可以將參數值設為目標。輸入 `ParameterValues` 做為索引鍵，接著在您想要執行自動化的地方輸入特定資源值。如果您指定多個值，Systems Manager 會於每個指定的值執行子自動化。

例如，假設您的 Runbook 包括 **InstanceID** 參數。如果您在執行自動化時以 **InstanceID** 參數的值為目標，則 Systems Manager 會針對每個指定的執行個體 ID 值執行子自動化。當自動化完成執行每個指定的執行個體，或是自動化失敗，父自動化就會完成。您最多可將 50 個參數值設為目標。

下列範例使用 `AWS-CreateImage` Runbook。指定的目標參數名稱為 *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` 選項指定多個參數值：將每個*範例資源預留位置*取代為您自己的資訊。

```
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 副檔名儲存檔案。您可以使用下列命令來呼叫檔案：將每個*範例資源預留位置*取代為您自己的資訊。

```
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) 儲存貯體下載檔案。使用以下命令格式。將每個*範例資源預留位置*取代為您自己的資訊。

```
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 的 Runbook。此 Runbook 定義了兩個輸入參數：`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` 中定義的五個 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 帳戶 和目前 的所有 Amazon EC2 執行個體 AWS 區域，您可以選擇 `AWS-RestartEC2Instance` Runbook，然後從**目標**清單中選擇**所有執行個體**。

![\[以執行手冊的所有 Amazon EC2 執行個體為目標\]](http://docs.aws.amazon.com/zh_tw/systems-manager/latest/userguide/images/automation-rate-control-target-all-instances.png)


在您選擇 **All instances** (所有執行個體) 後，Systems Manager 會填入帶有星號 (\$1) 的 **Instance** (執行個體) 欄位，且無法對欄位進行變更 (欄位會變灰)。Systems Manager 也會讓 **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 組織單位 OUs) 執行 AWS Systems Manager 自動化。Automation 是 AWS Systems Manager中的工具。在多個區域和帳戶或 OUs 中執行自動化可減少管理 AWS 資源所需的時間，同時增強運算環境的安全性。

例如，您可以使用自動化 Runbook 來執行下列動作：
+ 集中實作修補和安全性更新。
+ 糾正 VPC 組態或 Amazon S3 儲存貯體政策的合規偏離。
+ 大規模管理資源 (例如 Amazon Elastic Compute Cloud (Amazon EC2) EC2 執行個體)。

下圖顯示範例為使用者從中央帳戶的多個區域和帳戶中執行 `AWS-RestartEC2Instances` Runbook。自動化會使用目標區域和帳戶中的指定標籤找出執行個體。

![\[圖示為 Systems Manager Automation 在多個區域和多個帳戶中執行。\]](http://docs.aws.amazon.com/zh_tw/systems-manager/latest/userguide/images/automation-multi-region-and-multi-account.png)


**選擇自動化的中央帳戶**  
如果您想要跨 OU 執行自動化，則中央帳戶必須擁有列出 OU 中所有帳戶的許可。只有委派管理員帳戶或組織的管理帳戶才能執行此操作。我們建議您遵循 AWS Organizations 最佳實務，並使用委派的管理員帳戶。如需 AWS Organizations 最佳實務的詳細資訊，請參閱*AWS Organizations 《 使用者指南*》中的[管理帳戶的最佳實務](https://docs.aws.amazon.com/organizations/latest/userguide/orgs_best-practices_mgmt-acct.html)。若要建立 Systems Manager 的委派管理員帳戶，您可以使用 `register-delegated-administrator`命令搭配 AWS CLI ，如下列範例所示。

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

如果您想要在不受 AWS Organizations管理的多個帳戶執行自動化，則我們建議您為自動化管理建立專屬帳戶。從專用帳戶執行所有跨帳戶自動化功能，可簡化 IAM 許可管理、排解疑難，並在作業與管理之間建立分隔層。如果您使用 AWS Organizations，但只想要以個別帳戶為目標，而不是 OUs則建議使用此方法。

**執行自動化的運作方式**  
跨多個區域和帳戶或 OU 執行自動化的運作方式如下：

1. 登入您想要設定為自動化主帳戶的帳戶。

1. 使用本主題中的 [設定多區域和多帳戶自動化的管理帳戶許可](#setup-management-account-iam-roles) 處理程序，建立下列 IAM 角色。
   + `AWS-SystemsManager-AutomationAdministrationRole` - 此角色可給予使用者在多個帳戶 和 OU 中執行自動化的許可。
   + `AWS-SystemsManager-AutomationExecutionRole` - 此角色可給予使用者在目標帳戶中執行自動化的許可。

1. 選擇您想要執行自動化的 Runbook、區域、帳戶或 OU。
**注意**  
請確定目標 OU 包含所需的帳戶。如果您選擇自訂 Runbook，則 Runbook 必須與所有目標帳戶共用。如需共用 Runbook 的資訊，請參閱 [共用 SSM 文件](documents-ssm-sharing.md)。如需共用 Runbook 的詳細資訊，請參閱 [使用共用的 SSM 文件](documents-ssm-sharing.md#using-shared-documents)。

1. 執行自動化。

1. 使用來自主控台或 的 AWS Systems Manager [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 操作 AWS CLI 來監控自動化進度。在您的主要帳戶中自動化步驟的輸出將是子系自動化的 `AutomationExecutionId`。若要檢視在目標帳戶中建立之子系自動化的輸出，請務必在您的請求中指定適當的帳戶、區域和 `AutomationExecutionId`。

## 設定多區域和多帳戶自動化的管理帳戶許可
<a name="setup-management-account-iam-roles"></a>

依照以下步驟，使用 AWS CloudFormation建立 Systems Manager Automation 多區域和多帳戶自動化所需的 IAM 角色。此處理程序描述了如何建立 `AWS-SystemsManager-AutomationAdministrationRole` 角色。您只需要在自動化中央帳戶中建立此角色。此處理程序也描述了如何建立 `AWS-SystemsManager-AutomationExecutionRole` 角色。您必須在想要設為目標以執行多區域和多帳戶自動化的*每個*帳戶中建立此角色。建議您使用 CloudFormation StackSets 在帳戶中建立 `AWS-SystemsManager-AutomationExecutionRole` 角色，帳戶是您想要執行多區域和多帳戶自動化的目標帳戶。

**使用 建立多區域和多帳戶自動化所需的 IAM 管理角色 CloudFormation**

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. 在 https：//[https://console.aws.amazon.com/cloudformation](https://console.aws.amazon.com/cloudformation/) 開啟 CloudFormation 主控台。

1. 選擇 **Create Stack** (建立堆疊)。

1. 在 **Specify template** (指定範本) 區段中，選擇 **Upload a template file** (上傳範本檔案)。

1. 選擇**選擇檔案**，然後選擇 `AWS-SystemsManager-AutomationAdministrationRole.yaml`或 `AWS-SystemsManager-AutomationAdministrationRole (org).yaml` CloudFormation 範本檔案，視您在步驟 1 的選擇而定。

1. 選擇**下一步**。

1. 在 **Specify stack details (指定堆疊詳細資訊)** 頁面，於 **Stack name (堆疊名稱)** 欄位輸入名稱。

1. 選擇**下一步**。

1. 在 **Configure stack options** (設定堆疊選項) 頁面，針對您想要使用的任何選項輸入值。選擇**下一步**。

1. 在**檢閱**頁面上，向下捲動並選擇**我確認 CloudFormation 可能會使用自訂名稱選項建立 IAM 資源**。

1. 選擇**建立堆疊**。

CloudFormation 顯示大約三分鐘的 **CREATE\$1IN\$1PROGRESS** 狀態。狀態會變更為 **CREATE\$1COMPLETE (CREATE\$1COMPLETE)**。

您必須在您想要設為目標以執行多區域和多帳戶自動化的*每個*帳戶中重複下列程序。

**使用 建立多區域和多帳戶自動化所需的 IAM 自動化角色 CloudFormation**

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. 在 https：//[https://console.aws.amazon.com/cloudformation](https://console.aws.amazon.com/cloudformation/) 開啟 CloudFormation 主控台。

1. 選擇 **Create Stack** (建立堆疊)。

1. 在 **Specify template** (指定範本) 區段中，選擇 **Upload a template file** (上傳範本檔案)。

1. 選擇**選擇檔案**，然後選擇 `AWS-SystemsManager-AutomationExecutionRole.yaml`或 `AWS-SystemsManager-AutomationExecutionRole (org).yaml` CloudFormation 範本檔案，視您在步驟 1 的選擇而定。

1. 選擇**下一步**。

1. 在 **Specify stack details (指定堆疊詳細資訊)** 頁面，於 **Stack name (堆疊名稱)** 欄位輸入名稱。

1. 在 **Parameters** (參數) 區段的 **AdminAccountId** 欄位中，輸入自動化中央帳戶的 ID。

1. 如果您要為 AWS Organizations 環境設定此角色，則 區段中有另一個欄位，稱為 **OrganizationID**。輸入 AWS 組織的 ID。

1. 選擇**下一步**。

1. 在 **Configure stack options** (設定堆疊選項) 頁面，針對您想要使用的任何選項輸入值。選擇**下一步**。

1. 在**檢閱**頁面上，向下捲動並選擇**我確認 CloudFormation 可能會使用自訂名稱選項建立 IAM 資源**。

1. 選擇**建立堆疊**。

CloudFormation 顯示大約三分鐘的 **CREATE\$1IN\$1PROGRESS** 狀態。狀態會變更為 **CREATE\$1COMPLETE (CREATE\$1COMPLETE)**。

## 在多個區域和帳戶中執行自動化 (主控台)
<a name="multiple-console"></a>

以下程序說明如何使用 Systems Manager 主控台，從 Automation 管理帳戶中於多個區域和帳戶內執行自動化。

**開始之前**  
完成以下程序之前，請記下以下資訊：
+ 您用來執行多區域或多帳戶自動化的使用者或角色必須具有該 `AWS-SystemsManager-AutomationAdministrationRole` 角色的 `iam:PassRole` 許可。
+ 您要執行自動化的AWS 帳戶 IDs 或 OUs。
+ 您希望執行自動化的 [Systems Manager 支援區域](https://docs.aws.amazon.com/general/latest/gr/ssm.html#ssm_region)。
+ 您希望執行自動化的資源群組標籤鍵或標籤值，或是其名稱。

**在多個區域和帳戶中執行自動化**

1. 在 https：//[https://console.aws.amazon.com/systems-manager/](https://console.aws.amazon.com/systems-manager/) 開啟 AWS Systems Manager 主控台。

1. 在導覽窗格中，選擇 **Automation (自動化)**，接著選擇 **Execute automation (執行自動化)**。

1. 在 **Automation document** (自動化文件) 清單中，選擇 Runbook。在 **Document categories** (文件類別) 窗格中選擇一個或多個選項，根據 SSM 文件的用途來進行篩選。若要檢視您擁有的 Runbook，請選擇 **Owned by me** (我所擁有的) 索引標籤。若要檢視與您帳戶共用的 Runbook，請選擇 **Shared with me** (與我共用的) 索引標籤。若要檢視所有 Runbook，請選擇 **All documents** (所有文件) 索引標籤。
**注意**  
您可以選擇 Runbook 名稱檢視 Runbook 資訊。

1. 在 **Document details** (文件詳細資訊) 部分，確認 **Document version** (文件版本) 設定為您想要執行的版本。系統包括以下版本選項：
   + **執行期的預設版本**：如果 Automation 執行手冊會定期更新且已指派新的預設版本，則請選擇此選項。
   + **執行期的最新版本**：如果 Automation 執行手冊會定期更新，而您想要執行最近更新的版本，請選擇此選項。
   + **1 (預設)**：選擇此選項以執行文件的第一個版本，也是預設版本。

1. 選擇**下一步**。

1. 在 **Execute automation document (執行自動化文件)** 頁面，選擇 **Multi-account and Region (多帳戶和區域)**。

1. 在**目標帳戶和區域**區段中，使用**帳戶、組織單位 OUs) 和根**欄位來指定您要執行自動化的不同 AWS 帳戶 或 AWS 組織單位 (OUs)。使用逗號分隔多個帳戶或 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**，這樣自動化就只會同時在兩個帳戶區域對中執行。或者您也能指定可同時執行的帳戶區域對百分比。例如有 20 個帳戶區域對，假設您指定了 20%，則自動化會同時在最多五 (5) 個帳戶區域對中執行。
      + 選擇 **targets** (目標)，輸入可以同時執行自動化的帳戶區域對絕對數量。
      + 選擇 **percent** (百分比)，輸入可以同時執行自動化的帳戶區域對總數之百分比。

   1. 在 **Error threshold (錯誤閾值)** 部分，選擇一個選項：
      + 選擇 **errors** (錯誤)，輸入在 Automation 停止傳送自動化至其他資源之前允許的錯誤絕對數量。
      + 選擇 **percent** (百分比)，輸入在 Automation 停止傳送自動化至其他資源之前允許的錯誤百分比。

1. 在 **Targets** (目標) 部分，選擇您想如何將要執行自動化的 AWS 資源設為目標。這些選項是必要的。

   1. 使用 **Parameter (參數)** 清單選擇一個參數。**Parameter** (參數) 清單中的項目，是由您在此程序一開始所選取自動化 Runbook 中的參數決定。藉由選擇參數，您就會定義自動化工作流程執行的資源類型。

   1. 使用 **Targets (目標)** 清單選擇您想要如何將資源設為目標。

      1. 如果您選擇使用參數值將資源設為目標，則請在 **Input parameters** (輸入參數) 區段為您所選的參數輸入參數值。

      1. 如果您選擇使用 將資源設為目標 AWS Resource Groups，請從資源群組清單中選擇**群組**的名稱。

      1. 如果您選擇使用標籤將資源設為目標，請在提供的欄位中輸入標籤索引鍵 (選用) 和標籤值。選擇**新增**。

      1. 如果您想要在目前 AWS 帳戶 和 中的所有執行個體上執行 Automation Runbook AWS 區域，請選擇**所有執行個體**。

1. 在 **Input parameters (輸入參數)** 部分，指定所需的輸入。從 **AutomationAssumeRole** 清單中選擇 `AWS-SystemsManager-AutomationAdministrationRole` IAM 服務角色。
**注意**  
您可能不必選擇 **Input parameters** (輸入參數) 部分的其中一些選項。這是因為您使用標籤或資源群組在多個區域和帳戶中將資源設為目標。例如，假設您選擇了 `AWS-RestartEC2Instance` Runbook，就不必在 **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. 使用**速率控制**區段中的選項，限制可在每個帳戶區域對內執行自動化 AWS 的資源數量。

   在 **Concurrency (並行)** 部分，選擇一個選項：
   + 選擇 **targets (目標)**，輸入可以同時執行自動化工作流程的目標絕對數量。
   + 選擇 **percentage (百分比)**，輸入可以同時執行自動化工作流程的目標集百分比。

1. 在 **Error threshold (錯誤閾值)** 部分，選擇一個選項：
   + 選擇 **errors (錯誤)**，輸入在自動化停止傳送工作流程至其他資源之前允許的錯誤絕對數量。
   + 選擇 **percentage (百分比)**，輸入在自動化停止傳送工作流程至其他資源之前允許的錯誤百分比。

1. 選擇 **Execute (執行)**。

自動化執行完成後，您可以使用相同或修改後的參數將執行重新執行。如需詳細資訊，請參閱[重新執行自動化執行](automation-rerun-executions.md)。

## 在多個區域和帳戶中執行自動化 (命令列)
<a name="multiple-cli"></a>

下列程序說明如何使用 AWS CLI （在 Linux 或 Windows 上） AWS Tools for PowerShell 或從自動化管理帳戶在多個區域和帳戶中執行自動化。

**開始之前**  
完成以下程序之前，請記下以下資訊：
+ 您要執行自動化的AWS 帳戶 IDs 或 OUs。
+ 您希望執行自動化的 [Systems Manager 支援區域](https://docs.aws.amazon.com/general/latest/gr/ssm.html#ssm_region)。
+ 您希望執行自動化的資源群組標籤鍵或標籤值，或是其名稱。

**在多個區域和帳戶中執行自動化**

1.  AWS Tools for PowerShell如果您尚未安裝和設定 AWS CLI 或 。

   如需相關資訊，請參閱[安裝或更新 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 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 組織中三個區域中的 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 執行個體。
**注意**  
您可以使用 AWS CLI 和 AWS SDKs來使用 `TargetLocationMaxConcurrency`選項。

------
#### [ 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 SDKs時可使用 。

------
#### [ 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`和 `us-west-1`區域的 `us-east-2`和 `987654321098`帳戶中的 EC2 執行個體。執行個體必須使用標籤金鑰對值 `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**：此範例會重新啟動位於 `eu-central-1` 區域的 `123456789012` 和 `987654321098` 帳戶中的 EC2 執行個體。執行個體必須是`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
   ```

------
**注意**  
您也可以在主控台中監控自動化的狀態。在 **Automation executions** (自動化執行清單) 中，選擇您剛執行的自動化，接著選擇 **Execution steps** (執行步驟) 標籤。此索引標籤會顯示自動化動作的狀態。

**詳細資訊**  
[以 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>

您可以將 Runbook 指定為 Amazon EventBridge 事件的目標，藉此開始自動化。您可以根據排程或在特定的 AWS 系統事件發生時開始自動化。例如，假設您建立名稱為 *BootStrapInstances* 的 Runbook，而該文件在執行個體啟動時於執行個體上安裝軟體。若要指定 *BootStrapInstances* Runbook (和對應的工作流程) 做為 EventBridge 事件的目標，您要先建立新的 EventBridge 規則。(以下為範例規則：**Service name (服務名稱)**：EC2，**Event Type (事件類型)**：EC2 執行個體狀態－變更通知，**Specific state(s) (特定狀態)**：執行 **Any instance (任何執行個體)**。) 然後，您可以使用下列程序，使用 EventBridge 主控台和 AWS Command Line Interface () 將 *BootStrapInstances* Runbook 指定為事件的目標AWS CLI。新的執行個體啟動時，系統會執行自動化和安裝軟體。

如需建立 Runbook 的資訊，請參閱 [建立您自己的執行手冊](automation-documents.md)。

## 建立使用 Runbook (主控台) 的 EventBridge 事件
<a name="automation-cwe-target-console"></a>

使用以下程序設定來將 Runbook 做為 EventBridge 事件的目標。

**將 Runbook 設定為 EventBridge 事件的目標**

1. 前往 [https://console.aws.amazon.com/events/](https://console.aws.amazon.com/events/) 開啟 Amazon EventBridge 主控台。

1. 在導覽窗格中，選擇**規則**。

1. 選擇**建立規則**。

1. 輸入規則的名稱和描述。

   在同一個區域和同一個事件匯流排上，規則不能與另一個規則同名。

1. 針對**事件匯流排**，選擇要與此規則建立關聯的事件匯流排。如果您希望此規則回應來自您自己的相符事件 AWS 帳戶，請選取**預設值**。當您帳戶中 AWS 服務 的 發出事件時，一律會前往您帳戶的預設事件匯流排。

1. 選擇該規則的觸發方式。    
[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/systems-manager/latest/userguide/running-automations-event-bridge.html)

1. 選擇**下一步**。

1. 在**目標類型**欄位中，選擇 **AWS 服務**。

1. 針對 **Select a target** (選取目標)，請選擇 **Systems Manager Automation**。

1. 對於 **Document** (文件)，選擇叫用目標時要使用的 Runbook。

1. 在 **Configure automation parameter(s) (設定自動化參數)** 區段中，保留預設參數值 (若有) 或輸入您自己的值。
**注意**  
若要建立目標，您必須為每個必要參數指定值。如果不這麼做，系統會建立規則，但規則不會執行。

1. 對於許多目標類型而言，EventBridge 需要許可才能將事件傳送到目標。在這些情況下，EventBridge 可建立執行您的規則所需的 IAM 角色。執行以下任意一項：
   + 若要自動建立 IAM 角色，請選擇**為此特定資源建立新角色**。
   + 若要使用您早前建立的 IAM 角色，請選擇 **Use existing role** (使用現有角色) 並從下拉式清單中選取現有角色。請注意，您可能需要更新 IAM 角色的信任政策，使其包含 EventBridge。以下是範例：

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

****  

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

------

1. 選擇**下一步**。

1. (選用) 為規則輸入一或多個標籤。如需詳細資訊，請參閱《Amazon EventBridge 使用者指南**》中的[標記您的 Amazon EventBridge 資源](https://docs.aws.amazon.com/eventbridge/latest/userguide/eventbridge-tagging.html)。

1. 選擇**下一步**。

1. 檢閱規則的詳細資訊，然後選擇**建立規則**。

## 建立使用 Runbook (命令列) 的 EventBridge 事件
<a name="automation-cwe-target-commandline"></a>

下列程序說明如何使用 AWS CLI （在 Linux 或 Windows 上） 或 AWS Tools for PowerShell 建立 EventBridge 事件規則，並將 Runbook 設定為目標。

**將 Runbook 設定為 EventBridge 事件的目標**

1.  AWS Tools for PowerShell如果您尚未安裝和設定 AWS CLI 或 。

   如需相關資訊，請參閱[安裝或更新 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 事件規則。將每個*範例資源預留位置*取代為您自己的資訊。

   「依據排程觸發」**

------
#### [ 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"
   ```

------

   以下範例會建立 EventBridge 事件規則，在每天早上 9:00 (UTC) 開始。

------
#### [ 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"]}'
   ```

------

   以下範例建立 EventBridge 事件規則，當區域中的任何 EC2 執行個體變更狀態時會觸開啟規則。

------
#### [ 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. 建立命令，指定 Runbook 做為您在步驟 2 中所建立 EventBridge 事件規則的目標。將每個*範例資源預留位置*取代為您自己的資訊。

------
#### [ 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
   ```

------

   以下範例會建立 EventBridge 事件目標，使用 Runbook `AWS-StartEC2Instance` 文件啟動指定的執行個體 ID。

------
#### [ 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) 來使用手動執行模式執行自動化。透過使用手動執行模式，自動化開始在*等待*狀態中開始並在每個步驟之間的*等待*狀態中暫停。這讓您能夠控制自動化的進行，在您需要檢閱每個步驟的結果再繼續時很有用。

自動化會在目前的使用者內容中執行。這表示只要有使用 Runbook 和 Runbook 所呼叫任何動作的許可，您就不必設定其他的 IAM 許可。如果您在 IAM 中有管理員許可，您便已經有執行此自動化的許可。

## 逐步執行自動化 (主控台)
<a name="automation-working-executing-manually-console"></a>

以下程序會示範如何使用 Systems Manager 主控台逐步手動執行自動化。

**逐步執行自動化**

1. 在 https：//[https://console.aws.amazon.com/systems-manager/](https://console.aws.amazon.com/systems-manager/) 開啟 AWS Systems Manager 主控台。

1. 在導覽窗格中，選擇 **Automation (自動化)**，接著選擇 **Execute automation (執行自動化)**。

1. 在 **Automation document** (自動化文件) 清單中，選擇 Runbook。在 **Document categories** (文件類別) 窗格中選擇一個或多個選項，根據 SSM 文件的用途來進行篩選。若要檢視您擁有的 Runbook，請選擇 **Owned by me** (我所擁有的) 索引標籤。若要檢視與您帳戶共用的 Runbook，請選擇 **Shared with me** (與我共用的) 索引標籤。若要檢視所有 Runbook，請選擇 **All documents** (所有文件) 索引標籤。
**注意**  
您可以選擇 Runbook 名稱檢視 Runbook 資訊。

1. 在 **Document details** (文件詳細資訊) 部分，確認 **Document version** (文件版本) 設定為您想要執行的版本。系統包括以下版本選項：
   + **執行期的預設版本**：如果 Automation 執行手冊會定期更新且已指派新的預設版本，則請選擇此選項。
   + **執行期的最新版本**：如果 Automation 執行手冊會定期更新，而您想要執行最近更新的版本，請選擇此選項。
   + **1 (預設)**：選擇此選項以執行文件的第一個版本，也是預設版本。

1. 選擇**下一步**。

1. 在 **Execution Mode (執行模式)** 部分，選擇 **Manual execution (手動執行)**。

1. 在 **Input parameters (輸入參數)** 部分，指定所需的輸入。或者，您也可以從 **AutomationAssumeRole** 清單中選擇 IAM 服務角色。

1. 選擇 **Execute (執行)**。

1. 準備好開始自動化的第一步時，選擇 **Execute this step** (執行此步驟)。自動化會繼續進行步驟一，並在執行您於本程序步驟 3 中所選的 Runbook 指定的任何後續步驟之前暫停。如果 Runbook 有多個步驟，您必須為每個步驟選擇 **Execute this step** (執行此步驟)，自動化才會繼續。每次您選擇 **Execute this step** (執行此步驟) 時，動作便會執行。
**注意**  
主控台會顯示自動化的狀態。若自動化無法執行步驟，請參閱 [故障診斷 Systems Manager Automation](automation-troubleshooting.md)。

1. 在您完成 Runbook 指定的所有步驟後，請選擇 **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 Tools for PowerShell如果您尚未安裝和設定 AWS CLI 或 。

   如需相關資訊，請參閱[安裝或更新 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 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` Runbook 重新啟動指定 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. 當您準備好開始自動化的第一步時，請執行以下命令。將每個*範例資源預留位置*取代為您自己的資訊。自動化會繼續進行步驟一，並在執行您於本程序步驟 1 中所選的 Runbook 指定的任何後續步驟之前暫停。若 Runbook 有多個步驟，您必須為每個步驟執行以下命令，自動化才會繼續。

------
#### [ 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. 在所選擇 Runbook 中指定的所有步驟皆完成後，執行以下命令來完成自動化。將每個*範例資源預留位置*取代為您自己的資訊。

------
#### [ 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中的工具。透過建立與 Runbook 的State Manager關聯，您可以鎖定不同類型的 AWS 資源。例如，您可以建立在 AWS 資源上強制執行所需狀態的關聯，包括下列項目：
+ 將 Systems Manager 角色連接到 Amazon Elastic Compute Cloud (Amazon EC2) 執行個體以作為*受管執行個體*。
+ 為安全群組強制執行所需的輸入和輸出規則。
+ 建立或刪除 Amazon DynamoDB 備份。
+ 建立 Amazon Elastic Block Store (Amazon EBS) 快照。
+ 關閉 Amazon Simple Storage Service (Amazon S3) 儲存貯體上的讀取和寫入許可。
+ 啟動、重新啟動或停止受管執行個體和 Amazon Relational Database Service (Amazon RDS) 執行個體。
+ 將修補程式套用至 Linux、macOS、和 WiWindows AMIs。

使用下列程序建立使用 AWS Systems Manager 主控台和 AWS Command Line Interface () 執行自動化的State Manager關聯AWS CLI。如需有關關聯的一般資訊，以及有關建立使用 SSM `Command` 文件或 `Policy` 文件之關聯的資訊，請參閱[建立關聯](state-manager-associations-creating.md)。

**開始之前**  
使用 State Manager 執行自動化前，請注意以下重要的詳細資訊。
+ 在您建立使用執行手冊的關聯之前，請先確認您已設定 Automation ( AWS Systems Manager中的工具) 的許可。如需詳細資訊，請參閱[設定自動化](automation-setup.md)。
+ 使用 Runbook 的 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：//[https://console.aws.amazon.com/systems-manager/](https://console.aws.amazon.com/systems-manager/) 開啟 AWS Systems Manager 主控台。

1. 在導覽窗格中，選擇 **State Manager**，然後選擇 **Create association (建立關聯)**。

1. 在 **Name (名稱)** 欄位中指定名稱。此為選用操作，但建議您採用。

1. 在 **Document** (文件) 清單中，選擇 Runbook。使用搜尋列來篩選 **Document type : Equal : Automation** Runbook。若要查看更多 Runbook，請使用搜尋列右側的號碼。
**注意**  
您可以選擇 Runbook 名稱檢視 Runbook 資訊。

1. 選擇 **Simple execution (簡易執行)**，透過為這些目標指定資源 ID，在一或多個目標上執行自動化。選擇**速率控制**，透過指定標籤或 等目標選項，跨 AWS 資源機群執行自動化 AWS Resource Groups。您也可以透過指定並行和錯誤閾值，控制在資源上的自動化操作。

   如果選擇 **Rate control** (速率控制)，便會顯示 **Targets** (目標) 部分。

1. 在 **Targets (目標)** 部分，選擇將資源設為目標的方法。

   1. (必要) 在 **Parameter (參數)** 清單中，選擇一個參數。**Parameter** (參數) 清單中的項目，是由您在此程序一開始所選取 Runbook 中的參數決定。藉由選擇參數，您就會定義自動化執行的資源類型。

   1. (必要) 在 **Targets (目標)** 清單中，選擇將資源設為目標的方法。
      + **Resource Group (資源群組)**：從 **Resource Group (資源群組)** 清單中選擇群組名稱。如需在 Runbook AWS Resource Groups 中鎖定目標的詳細資訊，請參閱 [鎖定目標 AWS Resource Groups](running-automations-map-targets.md#target-resource-groups)。
      + **Tags (標籤)**：在提供的欄位中輸入標籤鍵和 (選擇性) 標籤值。選擇**新增**。如需有關在 Runbook 中鎖定標籤的詳細資訊，請參閱 [將標籤設為目標](running-automations-map-targets.md#target-tags)。
      + **Parameter Values (參數值)**：在 **Input parameters (輸入參數)** 部分輸入值。如果您指定多個值，Systems Manager 會於每個指定的值執行子自動化。

        例如，假設您的 Runbook 包括 **InstanceID** 參數。如果您在執行自動化時以 **InstanceID** 參數的值為目標，則 Systems Manager 會針對每個指定的執行個體 ID 值執行子自動化。當自動化完成執行每個指定的執行個體，或是自動化失敗，父自動化就會完成。您最多可將 50 個參數值設為目標。如需有關在 Runbook 中設定參數值目標的詳細資訊，請參閱 [將參數值設為目標](running-automations-map-targets.md#target-parameter-values)。

1. 在 **Input Parameters (輸入參數)** 部分，指定所需的輸入參數。

   如果選擇使用標籤或資源群組將資源設為目標，您可能不必選擇 **Input parameters** (輸入參數) 部分中的某些選項。例如，假設您選擇 `AWS-RestartEC2Instance` Runbook，而您選擇使用標籤將執行個體設為目標，則您不必在 **Input parameters** (輸入參數) 部分中指定或選擇執行個體 ID。自動化會使用您指定的標籤找出要重新啟動的執行個體。
**重要**  
您必須在 **AutomationAssumeRole** 欄位中指定角色 ARN。 State Manager會使用擔任角色來呼叫 Runbook 中 AWS 服務 指定的 ，並代表您執行自動化關聯。

1. 在 **Specify schedule (指定排程)** 部分，如果想以固定間隔執行關聯，請選擇 **On Schedule (依排程)**。如果選擇此選項，然後使用 Cron 或 Rate 運算式，利用提供的選項建立排程。如需 State Manager 適用的 Cron 和 Rate 運算式的詳細資訊，請參閱[關聯的 Cron 與 Rate 運算式](reference-cron-and-rate-expressions.md#reference-cron-and-rate-expressions-association)。
**注意**  
Rate 運算式是執行 Runbook 的 State Manager 關聯所偏好的排程機制。Rate 運算式可在您達到自動化同時執行最大數量下提供更多執行關聯的靈活性。使用速率排程時，Systems Manager 便能在收到同時自動化已達最大值且遭調節的通知後立即重試自動化。

   如果您希望執行一次關聯，請選擇 **No schedule (無排程)**。

1. （選用） 在**速率控制**區段中，選擇**並行**和**錯誤閾值**選項，以控制跨 AWS 資源的自動化部署。

   1. 在 **Concurrency (並行)** 部分，選擇一個選項：
      + 選擇 **targets** (目標)，輸入可以同時執行自動化的目標絕對數量。
      + 選擇 **percentage** (百分比)，輸入可以同時執行自動化的目標集百分比。

   1. 在 **Error threshold (錯誤閾值)** 部分，選擇一個選項：
      + 選擇 **errors** (錯誤)，輸入在 Automation 停止傳送自動化至其他資源之前允許的錯誤絕對數量。
      + 選擇 **percentage** (百分比)，輸入在 Automation 停止傳送自動化至其他資源之前允許的錯誤百分比。

   如需有關使用目標和速率控制與自動化的詳細資訊，請參閱[大規模執行自動化操作](running-automations-scale.md)。

1. 選擇 **Create Association (建立關聯)**。
**重要**  
建立關聯時，關聯便會立即在指定的目標上執行。接著關聯會依照您選擇的 Cron 或 Rate 運算式執行。如果您選擇 **No schedule** (無排程)，關聯不會再次執行。

## 建立執行自動化的關聯 (命令列)
<a name="create-automation-association-cli"></a>

下列程序說明如何使用 AWS CLI （在 Linux 或 上Windows Server) 或 AWS Tools for PowerShell 來建立執行自動化的State Manager關聯。

**開始之前**  
完成下列程序之前，應先確認已建立含有執行執行手冊所需許可的 IAM 服務角色，並為 Automation ( AWS Systems Manager中的工具) 設定了信任關係。如需詳細資訊，請參閱[任務 1：建立自動化的服務角色](automation-setup-iam.md#create-service-role)。

**建立執行自動化的關聯**

1.  AWS Tools for PowerShell如果您尚未安裝和設定 AWS CLI 或 。

   如需相關資訊，請參閱[安裝或更新 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
   ```

------

   記下您要用於關聯的 Runbook 名稱。

1. 執行以下命令來檢視您建立的 Runbook 詳細資訊。在下列命令中，用您自己的資訊取代 *Runbook name* (Runbook 名稱)。

------
#### [ 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 關聯建立執行自動化的命令。將每個*範例資源預留位置*取代為您自己的資訊。

   「使用標籤設定目標」**

------
#### [ 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 個排入佇列的自動化限制。如果使用 Runbook 的 State Manager 關聯顯示 **Failed** (失敗) 狀態和 **AutomationExecutionLimitExceeded** 詳細狀態，則表示可能已達到自動化的限制。因此，Systems Manager 會調節自動化。要解決此問題，請依照下列步驟：
+ 為您的關聯使用不同的 Rate 或 Cron 運算式。例如，如果關聯排程每隔 30 分鐘執行，則變更運算式可每一或二小時執行一次。
+ 刪除狀態為 **Pending** (待定) 的現有自動化。透過刪除這些自動化，即可清除目前的佇列。

# 使用維護時段排定自動化
<a name="scheduling-automations-maintenance-windows"></a>

您可以將 Runbook 設為維護時段的已註冊任務，以啟動自動化。透過將 Runbook 註冊為已註冊任務，維護時段便能在排程的維護時段期間執行自動化。

例如，假設您建立了名為 `CreateAMI` 的 Runbook，該 Runbook 會建立註冊為維護時段目標的執行個體 Amazon Machine Image (AMI)。若要指定 `CreateAMI` Runbook (和對應的自動化) 做為維護時段的已註冊任務，您必須先建立維護時段和註冊目標。然後您可以使用以下程序來指定 `CreateAMI` 文件做為維護時段內的已註冊任務。當維護時段在排程的期間啟動時，系統將執行自動化，並建立已註冊目標的 AMI。

如需建立 Automation Runbook 的資訊，請參閱 [建立您自己的執行手冊](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：//[https://console.aws.amazon.com/systems-manager/](https://console.aws.amazon.com/systems-manager/) 開啟 AWS Systems Manager 主控台。

1. 在左側導覽窗格中，選擇 **Maintenance Windows**，然後選擇您希望註冊自動化任務的維護時段。

1. 選擇**動作**。然後選擇 **Register Automation task** (註冊自動化任務)，使用 Runbook 在目標上執行您所選的自動化。

1. 在 **Name (名稱)** 中，輸入任務的名稱。

1. 在**描述**中，輸入描述。

1. 在 **Document** (文件) 中，選擇定義要執行任務的 Runbook。

1. 在 **Document Version** (文件版本) 中，選擇要使用的 Runbook 版本。

1. 在 **Task priority** (任務優先順序) 中，為此任務選擇優先順序。`1` 是最高優先順序。維護時段內的任務都是以優先順序來排程；相同優先順序的任務會平行排程。

1. 在 **Targets** (目標) 區段中，如果您選擇的 Runbook 是在資源中執行任務中的一個，手動指定標籤或選取執行個體，以識別您要執行這項自動化的目標。
**注意**  
如果您想要透過輸入參數而非目標傳遞資源，則不需要指定維護時段目標。  
在許多情況下，您不需要明確指定自動化任務的目標。例如，假設您正在建立 Automation 類型任務來使用 `AWS-UpdateLinuxAmi` Runbook 更新 Linux 的 Amazon Machine Image (AMI)。當任務執行時，AMI 已更新為可用的最新版本 Linux 發行版本套件和 Amazon 軟體。從 AMI 建立的新執行個體已經安裝這些更新。因為在 Runbook 的輸入參數中指定了要更新的 AMI ID，所以不需要在維護時段任務中再次指定目標。

   如需不需要目標之維護時段任務的相關資訊，請參閱 [註冊不含目標的維護時段任務](maintenance-windows-targetless-tasks.md)。

1. (選用) 在 **Rate control (速率控制)** 中：
**注意**  
如果您正在執行的任務未指定目標，則不需要指定速率控制。
   + 在 **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** (輸入參數) 區段中，指定 Runbook 的參數。對於 Runbook，系統會自動填入一些值。您可以保留或取代這些值。
**重要**  
針對 Runbook，您可以選擇性指定自動化取得角色。若您沒有為此參數指定角色，自動化將取得您在步驟 11 中選擇的維護時段服務角色。因此，您必須確保您選擇的維護時段服務角色具有適當的 AWS Identity and Access Management (IAM) 許可，可執行 Runbook 中定義的動作。  
例如，Systems Manager 的服務連結角色不具備 IAM 許可 `ec2:CreateSnapshot`，該許可是執行 Runbook `AWS-CopySnapshot` 所需要的許可。在此案例中，您必須使用自訂的維護時段服務角色，或指定具備 `ec2:CreateSnapshot` 許可的自動化取得角色。如需相關資訊，請參閱[設定自動化](automation-setup.md)。

1. 在 **IAM service role** (IAM 服務角色) 區域，選擇角色以提供授權給 Systems Manager 並開始自動化。

   若要建立服務角色給維護視窗工作，請參閱 [設定 Maintenance Windows](setting-up-maintenance-windows.md)。

1. 選擇 **Register Automation task (註冊自動化任務)**。

## 向維護時段註冊自動化任務 (命令列)
<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 Tools for PowerShell如果您尚未安裝和設定 AWS CLI 或 。

   如需相關資訊，請參閱[安裝或更新 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 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` 的值。系統會插入預留位置值 `1`，這可能會在回應指令 (例如 [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)) 中回報。這些值不會影響任務的執行，可以忽略。  
如需不需要目標之維護時段任務的相關資訊，請參閱 [註冊不含目標的維護時段任務](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` 的值。系統會插入預留位置值 `1`，這可能會在回應指令 (例如 [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)) 中回報。這些值不會影響任務的執行，可以忽略。  
如需不需要目標之維護時段任務的相關資訊，請參閱 [註冊不含目標的維護時段任務](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` 的值。相反地，系統會插入預留位置值 1，這可能會在回應指令 (例如 `Get-SSMMaintenanceWindowTaskList` 和 `Get-SSMMaintenanceWindowTask`) 中回報。這些值不會影響任務的執行，可以忽略。  
如需不需要目標之維護時段任務的相關資訊，請參閱 [註冊不含目標的維護時段任務](maintenance-windows-targetless-tasks.md)。

------

   以下範例會將自動化設為維護時段的已註冊任務，其優先順序為 1。它還演示了為無目標維護時段任務省略的 `--targets`、`--max-errors` 和 `--max-concurrency` 選項。自動化會使用 `AWS-StartEC2Instance` Runbook 和指定的自動化取得角色，來啟動已向維護時段註冊為目標的 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 Runbook 中指定的自動化動作。Automation 是 AWS Systems Manager中的工具。這些動作無法用於其他類型的 Systems Manager (SSM) 文件中。如需其他 SSM 文件類型的外掛程式詳細資訊，請參閱 [命令文件外掛程式參考](documents-command-ssm-plugin-reference.md)。

Systems Manager Automation 會執行 Automation Runbook 中定義的步驟。每個步驟皆與一個特定動作關聯。動作會決定輸入、行為和步驟的輸出。Runbook 的 `mainSteps` 章節中會定義步驟。

您不需要指定動作或步驟的輸出。輸出是由與步驟關聯的動作預先定義。在 Runbook 中指定步驟輸入時，您可以參考先前步驟的一個或多個輸出。例如，您可以讓 `aws:runInstances` 輸出用於後續的 `aws:runCommand` 動作。您也可以參考 Runbook `Output` 區段中先前步驟的輸出。

**重要**  
如果您執行可使用 AWS Identity and Access Management (IAM) 服務角色叫用其他服務的自動化工作流程，請注意您必須為該服務角色設定可叫用這些服務的許可。此需求適用於所有 AWS Automation Runbook (`AWS-*` Runbook)，例如 `AWS-ConfigureS3BucketLogging`、 `AWS-CreateDynamoDBBackup`和 `AWS-RestartEC2Instance` Runbook。此要求也適用於您建立的任何自訂 Automation Runbook， AWS 服務 其會透過呼叫其他 服務的動作來叫用其他 。例如，如果您使用 `aws:executeAwsApi`、`aws:createStack` 或 `aws:copyImage` 動作，為服務角色設定可叫用這些服務的許可。您可新增 IAM 內嵌政策到角色，以啟用其他 AWS 服務 的許可。如需詳細資訊，請參閱[（選用） 新增自動化內嵌政策或客戶受管政策以叫用其他 AWS 服務](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 Webhook 整合](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-variables.md)

## 依所有動作共用的屬性
<a name="automation-common"></a>

一般屬性是可在所有動作中找到的參數或選項。某些選項會定義步驟的行為，例如，等待步驟完成的時間，以及如果步驟失敗時該怎麼做。以下為所有動作中常見的屬性。

[description](#descriptProp)  
您提供用於描述執行手冊或步驟之目的的資訊。  
類型：字串  
必要：否

[name](#nameProp)  
一種識別符，在 Runbook 的所有步驟名稱中必須獨一無二。  
類型：字串  
允許的模式：[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)  
指示自動化在失敗時應中止、繼續或前往不同的步驟。此選項的預設值為 abort。  
類型：字串  
有效值：Abort \$1 Continue \$1 step:*step\$1name*  
必要：否

[onCancel](#canProp)  
指出當使用者取消自動化時，自動化應移至哪個步驟。自動化會執行取消工作流程最多兩分鐘。  
類型：字串  
有效值：Abort \$1 step:*step\$1name*  
必要：否  
`onCancel` 屬性不支援移至下列動作：  
+ `aws:approve`
+ `aws:copyImage`
+ `aws:createImage`
+ `aws:createStack`
+ `aws:createTags`
+ `aws:loop`
+ `aws:pause`
+ `aws:runInstances`
+ `aws:sleep`

[isEnd](#endProp)  
此選項會在特定步驟結束時停止自動化。如果步驟執行失敗或成功，自動化就會停止。預設值為 false。  
類型：布林值  
有效值：true \$1 false  
必要：否

[nextStep](#nextProp)  
指定在成功完成步驟後要接著處理自動化中的哪個步驟。  
類型：字串  
必要：否

[isCritical](#critProp)  
指定某個步驟是成功完成自動化的關鍵。如果此指定步驟失敗，則自動化會將自動化的最終狀態回報為 Failed (失敗)。只有當您在步驟中明確定義此屬性時，才會評估此屬性。如果 `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>

暫時暫停自動化，直到指定的委託人核准或拒絕動作。達到所需的核准數量後，自動化會繼續。您可以將核准步驟插入 Runbook `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：//[https://console.aws.amazon.com/systems-manager/](https://console.aws.amazon.com/systems-manager/) 開啟 AWS Systems Manager 主控台。

1. 在導覽窗格中，選擇 **Automation** (自動化)。

1. 選擇狀態為 **Waiting (正在等待)** 自動化旁的選項。  
![\[存取核准/拒絕自動化頁面\]](http://docs.aws.amazon.com/zh_tw/systems-manager/latest/userguide/images/automation-approve-action-aws.png)

1. 選擇 **Approve/Deny (核准/拒絕)**。

1. 檢閱自動化的詳細資訊。

1. 選擇 **Approve (核准)** 或 **Deny (拒絕)**，輸入選擇性的註解，接著選擇 **Submit (提交)**。

**輸入範例**

------
#### [ 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 Resource Name (ARN)。當您在 Runbook 中指定 `aws:approve` 步驟，自動化會傳送訊息至此主題，讓委託人知道必須核准或拒絕自動化步驟。Amazon SNS 主題的標題必須以「Automation」為字首。  
類型：字串  
必要：否

訊息  
您想要在核准請求傳送時包含於 Amazon SNS 主題的資訊。訊息長度上限為 4096 個字元。  
類型：字串  
必要：否

MinRequiredApprovals  
繼續自動化所需的核准數量下限。如果您不指定值，系統會預設一個。此參數的值必須為正數。此參數的值不得超過由 `Approvers` 參數定義的核准者數量。  
類型：整數  
必要：否

Approvers  
能夠核准或拒絕動作的已 AWS 驗證主體清單。核准者的數量上限為 10。您可以使用以下任一格式指定委託人：  
+ 使用者名稱
+ 使用者 ARN
+ IAM 角色 ARN
+ IAM 擔任角色 ARN
類型：StringList  
必要：是

EnhancedApprovals  
此輸入僅用於 Change Manager 範本。能夠核准或拒絕動作、IAM 主體類型以及核准者人數下限的已驗證 AWS 主體清單。以下是範例：  

```
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 (等待)。等待表示自動化要等待核准者輸入。  
類型：字串

ApproverDecisions  
一種 JSON 對應，包括每個核准者的核准決定。  
類型：MapList

# `aws:assertAwsResourceProperty` – 宣告 AWS 資源狀態或事件狀態
<a name="automation-action-assertAwsResourceProperty"></a>

`aws:assertAwsResourceProperty` 動作可讓您針對特定自動化步驟宣告特定的資源狀態或事件狀態。

**注意**  
`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 操作之名稱。您可以檢視 API 操作 (也稱為方法)，方式是在以下[服務參考](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/index.html)頁面的左側導覽中選擇一項服務。在您想要呼叫之服務的 **Client (用戶端)** 部分選擇一個方法。例如，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)頁面的左側導覽中選擇一項服務。在您想要呼叫之服務的 **Client (用戶端)** 部分選擇一個方法。例如，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)頁面的左側導覽中選擇一項服務。在您想要呼叫之服務的 **Client (用戶端)** 部分選擇一個方法。例如，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` 動作可讓您建立動態自動化，以評估單一步驟中的不同選擇，接著根據該評估的結果跳至 Runbook 中的不同步驟。

指定步驟的 `aws:branch` 動作時，您要指定自動化必須評估的 `Choices`。`Choices` 可根據您在 Runbook 之 `Parameters` 區段所指定的值，或是產生做為先前步驟之輸出的動態值。自動化會使用布林值表達式評估每個選擇。如果第一個選擇為 true，則自動化會跳至針對該選擇指定的步驟。如果第一個選擇為 false，則自動化會評估下一個選擇。自動化會繼續評估每個選擇，直到處理的選擇是 true 為止。接著自動化會跳至選擇為 true 的指定步驟。

如果選擇均不為 true，則自動化會檢查步驟是否包含 `default` 值。如果沒有選擇為 true，則預設值會定義自動化應跳至的步驟。如果未針對步驟指定 `default` 值，則自動化會處理 Runbook 中的下一個步驟。

`aws:branch` 動作可結合使用 `And`、`Not`、`Or` 運算子來支援複雜的選擇評估。如需使用 `aws:branch` 的詳細資訊，包括使用不同運算子的範例 Runbook 和範例，請參閱 [在執行手冊中使用條件陳述式](automation-branch-condition.md)。

**Input**  
在步驟中指定一個或多個 `Choices`。`Choices` 可根據您在 Runbook 之 `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
```

選擇  
在決定要處理的下一個步驟時，自動化應評估的一個或多個運算式。選擇是使用布林值運算式評估。每個選擇都必須定義以下選項：  
+ **NextStep**：如果指定選擇為 true，在 Runbook 中要處理的下一個步驟。
+ **Variable** (變數)：指定 Runbook 之 `Parameters` 區段中定義的參數名稱。或指定 Runbook 中先前步驟的輸出物件。如需為 `aws:branch` 建立變數的詳細資訊，請參閱 [關於建立輸出變數](automation-branch-condition.md#branch-action-output)。
+ **Operation (運算)**：用於評估選擇的條件。`aws:branch` 動作支援以下運算：

**字串運算**
  + StringEquals
  + EqualsIgnoreCase
  + StartsWith
  + EndsWith
  + Contains

**數值運算**
  + NumericEquals
  + NumericGreater
  + NumericLesser
  + NumericGreaterOrEquals
  + NumericLesser
  + NumericLesserOrEquals

**布林運算**
  + BooleanEquals
**重要**  
當您建立 Runbook 時，系統會驗證 Runbook 中的每個操作。如果不支援操作，系統會在您嘗試建立 Runbook 時傳回錯誤。

預設  
自動化在 `Choices` 均不為 true 時應跳至某步驟的名稱。  
類型：字串  
必要：否

**注意**  
`aws:branch` 動作支援 `And`、`Or`、`Not` 運算子。如需使用運算子的 `aws:branch` 範例，請參閱 [在執行手冊中使用條件陳述式](automation-branch-condition.md)。

# `aws:changeInstanceState` – 變更或宣告執行個體狀態
<a name="automation-action-changestate"></a>

變更或宣告執行個體的狀態。

此動作可用於宣告模式 (不執行 API 以變更狀態，但會驗證執行個體處於所需的狀態)。若要使用宣告模式，請將 `CheckStateOnly` 參數設定為 true。此模式可用於在 Windows Server 上執行 Sysprep 命令，這是一種非同步命令，可在背景長時間執行。您可以確保執行個體在您建立 Amazon Machine Image (AMI) 之前停止。

**注意**  
此動作的預設逾時值為 3600 秒 (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`  
必要：是

Force  
如果設定，則會強制執行個體停止。執行個體沒有機會排清檔案系統快取或檔案系統中繼資料。如果使用此選項，您必須執行檔案系統檢查及修復程序。此選項不建議用於 Windows Server 的 EC2 執行個體。  
類型：布林值  
必要：否

AdditionalInfo  
預訂.  
類型：字串  
必要：否

**Output**  
無

# `aws:copyImage` – 複製或加密 Amazon Machine Image
<a name="automation-action-copyimage"></a>

將 Amazon Machine Image(AMI) 從任何 複製到 AWS 區域 目前的 區域。此動作也可以加密新的 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 已複製到您啟動自動化動作的區域。由於選用的 `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  
目標映像的描述。  
類型：字串  
必要：否

加密  
加密目標 AMI。  
類型：布林值  
必要：否

KmsKeyId  
在複製操作期間加密映像快照時， AWS KMS key 要使用的完整 Amazon Resource Name (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)。  
類型：字串  
必要：否Output

ImageId  
所複製映像的 ID。

ImageState  
所複製映像的狀態。  
有效值：`available` \$1 `pending` \$1 `failed`

# `aws:createImage` – 建立 Amazon Machine Image
<a name="automation-action-create"></a>

從正在執行、正在停止或已停止以及 `ImageState` 輪詢狀態為 `available` 的執行個體建立 Amazon Machine Image (AMI)。

**注意**  
`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) 動作停止執行個體，接著使用 `aws:createImage` 動作並將 **NoReboot** 選項設為 `true`。  
類型：布林值  
必要：否

BlockDeviceMappings  
執行個體的區塊型儲存設備。  
類型：映射  
必要：否Output

ImageId  
新建立映像的 ID。  
類型：字串

ImageState  
映像目前的狀態。如果狀態可用，則表示已成功註冊映像，且該映像可以用來啟動執行個體。  
類型：字串

# `aws:createStack` – 建立 CloudFormation 堆疊
<a name="automation-action-createstack"></a>

從範本建立 AWS CloudFormation 堆疊。

**注意**  
`aws:createStack` 動作支援自動限流重試。如需詳細資訊，請參閱[設定限流操作的自動重試](automation-throttling-retry.md)。

如需建立 CloudFormation 堆疊的補充資訊，請參閱《*AWS CloudFormation API 參考*》中的 [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 主控台尋找 SNS 主題 ARN，[https://console.aws.amazon.com/sns/v3/home](https://console.aws.amazon.com/sns/v3/home)。  
類型：字串的陣列  
陣列成員：最多 5 個項目。  
必要：否

OnFailure  
決定堆疊建立失敗時要採取的動作。您必須指定 `DO_NOTHING`、`ROLLBACK` 或 `DELETE`。  
條件：您可以指定 `OnFailure` 參數或 `DisableRollback` 參數，但不能同時指定兩者。  
預設：`ROLLBACK`  
類型：字串  
有效值：` DO_NOTHING | ROLLBACK | DELETE`  
必要：否

Parameters  
針對堆疊指定輸入參數的 `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 Resource Name (ARN)。CloudFormation 會使用該角色的憑證代表您進行呼叫。CloudFormation 一律會將此角色用於堆疊上的所有未來操作。只要使用者擁有在堆疊上操作的許可，即使使用者沒有傳遞此角色的許可，CloudFormation 也會使用此角色。確保角色授予最少量的權限。  
如果您不指定值，CloudFormation 會使用先前與堆疊關聯的角色。如果沒有可用的角色，CloudFormation 會使用從您的使用者登入資料產生的暫時工作階段。  
類型：字串  
長度限制︰長度下限為 20。長度上限為 2048。  
必要：否

StackName  
與堆疊關聯的名稱。在您建立堆疊的區域中，名稱必須是唯一的。  
堆疊名稱僅能使用英數字元 (區分大小寫) 和連字號。必須以字母字元開頭，且長度不可超過 128 個字元。
類型：字串  
必要：是

StackPolicyBody  
包含堆疊政策內文的結構。如需詳細資訊，請參閱[避免更新堆疊資源](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/protect-stack-resources.html)。  
條件：您可以指定 `StackPolicyBody` 參數或 `StackPolicyURL` 參數，但不能同時指定兩者。  
類型：字串  
長度限制：長度下限為 1。長度上限為 16384。  
必要：否

StackPolicyURL  
包含堆疊政策之檔案的位置。URL 指向的政策必須位於與堆疊在相同區域中的 S3 儲存貯體。堆疊政策允許的檔案大小上限為 16 KB。  
條件：您可以指定 `StackPolicyBody` 參數或 `StackPolicyURL` 參數，但不能同時指定兩者。  
類型：字串  
長度限制：長度下限為 1。長度上限為 1350。  
必要：否

Tags (標籤)  
要與此堆疊相關聯的索引鍵/值組。CloudFormation 也會將這些標籤散佈到堆疊中建立的資源。您最多可指定 10 個標籤。  
類型：[Tag (標籤)](https://docs.aws.amazon.com/AWSCloudFormation/latest/APIReference/API_Tag.html) 物件的陣列   
必要：否

TemplateBody  
包含範本內文的結構，長度下限為 1 位元組，上限為 51,200 位元組。如需詳細資訊，請參閱[範本剖析](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/template-anatomy.html)。  
條件：您可以指定 `TemplateBody` 參數或 `TemplateURL` 參數，但不能同時指定兩者。  
類型：字串  
長度限制：長度下限為 1。  
必要：否

TemplateURL  
包含範本內文之檔案的位置。URL 必須指向位於 S3 儲存貯體的範本。範本允許的大小上限為 460,800 位元組。如需詳細資訊，請參閱[範本剖析](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 自動化擔任角色。如需擔任角色的詳細資訊，請參閱 [任務 1：建立自動化的服務角色](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`

**Output**  
無

# `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) 和 [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。  
類型：字串  
必要：是

**Output**  
無

# `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 Resource Name (ARN)。CloudFormation 會使用該角色的憑證代表您進行呼叫。CloudFormation 一律會將此角色用於堆疊上的所有未來操作。只要使用者擁有在堆疊上操作的許可，即使使用者沒有傳遞此角色的許可，CloudFormation 也會使用此角色。確保角色授予最少量的權限。  
如果您不指定值，CloudFormation 會使用先前與堆疊關聯的角色。如果沒有可用的角色，CloudFormation 會使用從您的使用者登入資料產生的暫時工作階段。  
類型：字串  
長度限制︰長度下限為 20。長度上限為 2048。  
必要：否

StackName  
與堆疊關聯的名稱或唯一的堆疊 ID。  
類型：字串  
必要：是

## 安全考量
<a name="automation-action-deletestack-security"></a>

在您可以使用 `aws:deleteStack` 動作之前，您必須將以下政策指派至 IAM 自動化擔任角色。如需擔任角色的詳細資訊，請參閱 [任務 1：建立自動化的服務角色](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>

透過呼叫次要 Runbook 執行次要自動化。透過此動作，您可以為您最常用的操作建立 Runbook，並在自動化執行期間參考那些 Runbook。此動作可簡化您的 Runbook，讓您不需要在類似的 Runbook 之間重複步驟。

次要自動化會在啟動主要自動化的使用者之內容中執行。這表示次要自動化使用與啟動第一個自動化的使用者相同的 AWS Identity and Access Management (IAM) 角色或使用者。

**重要**  
如果由您指定參數的次要自動化使用擔任角色 (使用 iam:passRole 政策的角色)，則啟動主要自動化的使用者或角色必須擁有將擔任角色傳遞至次要自動化的許可。如需設定自動化之擔任角色的詳細資訊，請參閱 [使用主控台建立用於自動化的服務角色](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  
在步驟期間要執行的次要 Runbook 名稱。對於相同 中的 Runbook AWS 帳戶，指定 Runbook 名稱。對於從不同 共用的 Runbook AWS 帳戶，請指定 Runbook 的 Amazon Resource Name (ARN)。如需共用 Runbook 的詳細資訊，請參閱 [使用共用的 SSM 文件](documents-ssm-sharing.md#using-shared-documents)。  
類型：字串  
必要：是

DocumentVersion  
要執行的次要 Runbook 版本。如果未指定，自動化會執行預設 Runbook 版本。  
類型：字串  
必要：否

MaxConcurrency  
您可以平行執行此任務的目標數目上限。您可以指定數量如 10 或百分比如 10%。  
類型：字串  
必要：否

MaxErrors  
系統停止在其他目標上執行自動化前所允許的錯誤數量。您可以指定絕對數量的錯誤 (例如 10 個) 或目標集的百分比 (例如 10%)。例如，假設您指定 3，系統會在收到第四個錯誤時停止執行自動化。如果您指定 0，系統會在第一個錯誤結果傳回時停止其他目標上執行的自動化。如果您在 50 個資源上執行自動化，並將 `MaxErrors` 設為 10%，則系統會在收到第六個錯誤時停止對其他目標執行自動化。  
達到 `MaxErrors` 閾值時已經在執行的自動化允許完成，但其中某些自動化也可能會失敗。如果您需要確保不會有比指定 `MaxErrors` 多的失敗自動化操作，則將 `MaxConcurrency` 設定為 1，因此會一次進行一個自動化。  
類型：字串  
必要：否

RuntimeParameters  
次要 Runbook 的必要參數。映射使用以下格式：\$1"parameter1" : "value1", "parameter2" : "value2" \$1  
類型：映射  
必要：否

Tags (標籤)  
您指派給資源的選用中繼資料。您可以為自動化指定最多五個標籤。  
類型：MapList  
必要：否

TargetLocations  
位置是您想要執行自動化的 AWS 區域 和/或 AWS 帳戶 的組合。必須指定最少 1 個項目，且最多可指定 100 個項目。指定此參數的值時，輸出不會傳回至父系自動化。如有需要，您必須對 API 操作進行後續呼叫，才能從子系自動化擷取輸出。  
類型：MapList  
必要：否

TargetMaps  
文件參數到目標資源的鍵/值映射清單。不能同時指定 `Targets` 和 `TargetMaps`。  
類型：MapList  
必要：否

TargetParameterName  
作為速率控制自動化之目標資源使用的參數名稱。只在您指定 `Targets` 時需要  
類型：字串  
必要：否

目標  
至目標資源的鍵/值對映清單。只在您指定 `TargetParameterName` 時需要  
類型：MapList  
必要：否Output

Output  
由次要自動化產生的輸出。您可以使用以下格式參考輸出：*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。  
類型：字串

狀態  
次要自動化的 狀態。  
類型：字串

# `aws:executeAwsApi` – 呼叫並執行 AWS API 操作
<a name="automation-action-executeAwsApi"></a>

呼叫並執行 AWS API 操作。大部分 API 操作均有支援，但並非所有 API 操作都經過測試。不支援串流 API 操作，例如 [GetObject](https://docs.aws.amazon.com/AmazonS3/latest/API/RESTObjectGET.html) 操作。如果不確定想要使用的 API 操作是否為串流操作，請檢閱 [Boto3](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/index.html) 服務文件，以確定 API 是否需要串流輸入或輸出。我們會定期更新此動作所使用的 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 服務 命名空間。您可以在 的[可用服務](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/index.html)中檢視支援的 AWS 服務 命名空間清單 適用於 Python (Boto3) 的 AWS SDK。您可以在 **Client (用戶端)** 區段中找到此命名空間。例如，Systems Manager 的命名空間為 `ssm`。Amazon Elastic Compute Cloud (Amazon EC2) 的命名空間為 `ec2`。  
類型：字串  
必要：是

Api  
您想要執行的 API 操作之名稱。您可以檢視 API 操作 (也稱為方法)，方式是在以下[服務參考](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/index.html)頁面的左側導覽中選擇一項服務。在您想要呼叫之服務的 **Client (用戶端)** 部分選擇一個方法。例如，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)頁面的左側導覽中選擇一項服務。在您想要呼叫之服務的 **Client (用戶端)** 部分選擇一個方法。例如，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 操作的回應來指定。

名稱  
輸出的名稱。  
類型：字串  
必要：是

選擇器  
回應物件中特定屬性的 JSONPath。您可以檢視回應物件，方式是在以下[服務參考](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/index.html)頁面的左側導覽中選擇一項服務。在您想要呼叫之服務的 **Client (用戶端)** 部分選擇一個方法。例如，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** 列為回應物件。  
類型：整數、布林值、字串、StringList、StringMap 或 MapList  
必要：是

Type  
回應元素的資料類型。  
類型：Varies  
必要：是

# `aws:executeScript` – 執行指令碼
<a name="automation-action-executeScript"></a>

執行使用指定的執行時間和處理程序提供的 Python 或 PowerShell 指令碼。每個 `aws:executeScript` 動作最久可執行 600 秒 (10 分鐘)。您可以透過指定 `aws:executeScript` 步驟的 `timeoutSeconds` 參數來限制逾時。

在函數中使用傳回陳述式將輸出加入輸出承載。有關 `aws:executeScript` 動作定義輸出的範例，請參閱 [範例 2：指令碼式 Runbook](automation-authoring-runbooks-scripted-example.md)。您也可以把 Runbook 的 `aws:executeScript` 動作輸出傳送到您指定的 Amazon CloudWatch Logs 日誌群組。如需詳細資訊，請參閱[使用 CloudWatch Logs 記錄自動化動作輸出](automation-action-logging.md)。

如果您想要將`aws:executeScript`動作的輸出傳送至 CloudWatch Logs，或者您為`aws:executeScript`動作指定的指令碼呼叫 AWS API 操作，則一律需要 AWS Identity and Access Management (IAM) 服務角色 （或擔任角色） 才能執行 Runbook。

**注意**  
`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` 模組，如下列命令所示。將每個*範例資源預留位置*取代為您自己的資訊。
+ Amazon Simple Storage Service (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
```

如需在 Runbook 內容中安裝和匯入 `AWS.Tools` 模組，以及使用 PowerShell Core Cmdlet 的範例，請參閱 [Automation 執行手冊的視覺化設計體驗](automation-visual-designer.md)。

**Input**  
提供執行指令碼所需訊息。將每個*範例資源預留位置*取代為您自己的資訊。

**注意**  
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/zh_tw/systems-manager/latest/userguide/automation-action-executeScript.html)
類型：字串  
必要：是  
對於 python 執行時期，該環境提供 512 MB 的記憶體與 512 MB 的磁碟空間。對於 PowerShell 執行時期，該環境提供 1024 MB 的記憶體與 512 MB 的磁碟空間。

處理常式  
函數名稱。您必須確保處理常式中定義的函數有兩個參數，`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
```

指令碼  
您想要在自動化期間執行的內嵌指令碼。  
類型：字串  
必要：No (Python) \$1 Yes (PowerShell)

連接  
動作可呼叫的獨立指令碼檔案或 .zip 檔案的名稱。指定與您在 `Attachments` 請求參數中指定的文件附件檔案的 `Name` 相同的數值。如須詳細資訊，請參閱《*AWS Systems Manager API 參考*》的[附件](https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_CreateDocument.html#systemsmanager-CreateDocument-request-Attachments)。如果您使用附件提供指令碼，還必須定義 Runbook 頂層元素的 `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`  
類型：字串  
必要：否Output

酬載  
由函數傳回之物件的 JSON 表示法。最多會傳回 100 KB。如果輸出清單，則最多只能傳回 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**

   將您的指令碼檔案或 zip 套件上傳至自動化角色可存取的 S3 儲存貯體。請記下 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>

此範例示範如何使用包含多個 Python 模組的 zip 套件進行複雜的 S3 儲存貯體操作。

**套件結構**  
使用下列結構建立 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` 檔案。
+ 驗證您的匯入陳述式是否符合 zip 套件中的實際檔案與目錄結構。
+ 一致地使用相對匯入 (例如 `from .utils import helper`) 或絕對匯入 (例如 `from utils import helper`)。

**找不到附件錯誤**  
如果您的 Automation 無法找到附件：
+ 驗證 `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 操作的大部分參數。

**Required 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 Resource Name (ARN)。  
類型：字串  
必要：是

name  
執行的名稱。  
類型：字串  
必要：否

input  
包含執行之 JSON 輸入資料的字串。  
類型：字串  
必要：否

**輸出**  
以下是針對此動作預先定義的輸出。

executionArn  
執行的 ARN。  
類型：字串

input  
包含執行之 JSON 輸入資料的字串。長度限制適用於承載大小，並以 UTF-8 編碼表示為位元組。  
類型：字串

name  
執行的名稱。  
類型：字串

output  
執行的 JSON 輸出資料。長度限制適用於承載大小，在 UTF-8 編碼中表示為位元組。  
類型：字串

startDate  
開始執行的日期。  
類型：字串

stateMachineArn  
已執行的指定機器的 ARN。  
類型：字串

status  
當前執行狀態。  
類型：字串

stopDate  
如果執行已經結束，則為執行停止的日期。  
類型：字串

# `aws:invokeWebhook`：叫用 Automation Webhook 整合
<a name="invoke-webhook"></a>

叫用指定的 Automation Webhook 整合。如需有關建立 Automation 整合的詳細資訊，請參閱 [為 Automation 建立 Webhook 整合](creating-webhook-integrations.md)。

**注意**  
`aws:invokeWebhook` 動作支援自動限流重試。如需詳細資訊，請參閱[設定限流操作的自動重試](automation-throttling-retry.md)。

**注意**  
若要使用 `aws:invokeWebhook` 動作，使用者或服務角色必須允許執行以下動作：  
ssm:GetParameter
kms:解密
只有在您使用客戶受管金鑰來加密整合的 參數時，才需要 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`。您指定的整合必須已經存在。  
類型：字串  
必要：是

Body  
叫用 Webhook 整合時要傳送的承載。  
類型：字串  
必要：否Output

回應  
從 Webhook 提供者回應中收到的文字。

ResponseCode  
從 Webhook 提供者回應中收到的 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 服務大部分的呼叫參數。如需詳細資訊，請參閱[呼叫](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 函數的名稱。此函數必須存在。  
類型：字串  
必要：是

限定詞  
函數版本或別名名稱。  
類型：字串  
必要：否

InvocationType  
呼叫類型。預設值為 `RequestResponse`。  
類型：字串  
有效值：`Event` \$1 `RequestResponse` \$1 `DryRun`  
必要：否

LogType  
如果預設值為 `Tail`，則叫用類型必須是 `RequestResponse`。Lambda 會傳回由 Lambda 函數產生的最新 4 KB 日誌資料，且為 base64 編碼。  
類型：字串  
有效值：`None` \$1 `Tail`  
必要：否

ClientContext  
用戶端特定的資訊。  
必要：否

InputPayload  
將傳遞給處理常式的第一個參數的 YAML 或 JSON 物件。您可以使用此輸入將資料傳遞到函數。此輸入相比傳統 `Payload` 輸入提供了更多靈活性和支援。如果您為該動作同時定義 `InputPayload` 和 `Payload`，則 `InputPayload` 優先，並且不使用 `Payload` 值。  
類型：StringMap  
必要：否

酬載  
將傳遞給處理常式的第一個參數的 JSON 字串。這可以用來將輸入資料傳遞到函數。建議您使用 `InputPayload` 輸入，因為已新增其功能。  
類型：字串  
必要：否Output

StatusCode  
HTTP 狀態碼

FunctionError  
如果存在，則表示函數執行期間發生錯誤。錯誤詳細資訊包含在回應承載中。

LogResult  
Lambda 函數呼叫的 base64 編碼日誌。日誌僅在呼叫類型為 `RequestResponse` 時才會出現，且日誌經過請求。

酬載  
由 Lambda 函數傳回之物件的 JSON 表示法。承載僅在呼叫類型為 `RequestResponse` 時才會出現。

以下節錄自 `AWS-PatchInstanceWithRollback` Runbook，示範如何從 `aws:invokeLambdaFunction` 動作參照輸出。

------
#### [ 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>

此動作會迭代自動化執行手冊中的步驟子集。您可以選擇 `do while` 或 `for each` 樣式迴圈。若要建構 `do while` 迴圈，請使用 `LoopCondition` 輸入參數。若要建構 `for each` 迴圈，請使用 `Iterators` 和 `IteratorDataType` 輸入參數。使用 `aws:loop` 動作時，僅指定 `Iterators` 或 `LoopCondition` 輸入參數。迭代的數量的上限為 100。

`onCancel` 屬性只能針對迴圈內定義的步驟。`aws:loop` 動作不支援 `onCancel` 屬性。`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  
必要：否

迭代器資料類型  
用來指定 `Iterators` 的資料類型的選用參數。此參數的值可與 `Iterators` 輸入參數一起提供。如果您不指定此參數和 `Iterators` 的值，則您必須指定 `LoopCondition` 參數的值。  
類型：字串  
有效值：布林值 \$1 整數 \$1 字串 \$1 StringMap  
預設：字串  
必要：否

LoopCondition  
包含 `Variable` 和要評估的運算子條件。如果您不指定此參數的值，則您必須指定 `Iterators` 和 `IteratorDataType` 參數的值。您可以透過 `And`、`Not` 和 `Or` 運算子的組合來使用複雜的運算子評估。在迴圈中的步驟完成後，就會評估條件。如果條件為 `true` 且尚未達到 `MaxIterations` 值，則迴圈中的步驟會再次執行。運算子條件如下：  

**字串運算**
+ StringEquals
+ EqualsIgnoreCase
+ StartsWith
+ EndsWith
+ Contains

**數值運算**
+ NumericEquals
+ NumericGreater
+ NumericLesser
+ NumericGreaterOrEquals
+ NumericLesser
+ NumericLesserOrEquals

**布林運算**
+ BooleanEquals
類型：StringMap  
必要：否

MaxIterations  
迴圈中步驟執行的最大次數。達到此輸入指定的值後，即使 `LoopCondition` 仍然 `true`，或 `Iterators` 參數中仍有剩餘物件，迴圈也會停止執行。  
類型：整數  
有效值：1 - 100  
必要：否

步驟  
在迴圈中執行的步驟清單。這些函數就像一個巢狀的執行手冊。在這些步驟中，您可以使用語法 `for each`，存取 `{{loopStepName.CurrentIteratorValue}}` 迴圈的目前迭代器值。您還可以使用語法 `{{loopStepName.CurrentIteration}}`，存取這兩個迴圈類型的目前迭代的整數值。  
類型：步驟清單  
必要：是Output

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": {}
}
```

------Output

無  


# `aws:runCommand` – 在受管執行個體上執行命令
<a name="automation-action-runcommand"></a>

執行指定的命令。

**注意**  
自動化僅支援一個 AWS Systems Manager Run Command動作的*output*。Runbook 可以包含多個 Run Command 動作，但一次僅一個動作支援output。

**Input**  
此動作支援大部分的傳送命令參數。如需詳細資訊，請參閱 [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 Resource Name (ARN)。如需使用共用文件的詳細資訊，請參閱 [使用共用的 SSM 文件](documents-ssm-sharing.md#using-shared-documents)。  
類型：字串  
必要：是

InstanceIds  
您想要命令執行的執行個體 ID。您最多可以指定 50 個 ID。  
您也可以使用虛擬參數 `{{RESOURCE_ID}}` 取代執行個體 ID，在目標群組中的所有執行個體上執行命令。如需這些虛擬參數的詳細資訊，請參閱[註冊維護時段任務時使用虛擬參數](maintenance-window-tasks-pseudo-parameters.md)。  
另一種方法是使用 `Targets` 參數將命令傳送到執行個體機群。`Targets` 參數接受 Amazon Elastic Compute Cloud (Amazon EC2) 標籤。如需使用 `Targets` 參數的詳細資訊，請參閱 [大規模執行命令](send-commands-multiple.md)。  
類型：StringList  
必要：否 (如果您未指定 InstanceIds 或使用 `{{RESOURCE_ID}}` 虛擬參數，則必須指定 `Targets` 參數。)

Targets  
一系列的搜尋條件，使用您指定的鍵值組合將執行個體設為目標。若您沒有在呼叫中提供一或多個執行個體 ID，則 `Targets` 為必要項目。如需使用 `Targets` 參數的詳細資訊，請參閱 [大規模執行命令](send-commands-multiple.md)。  
類型：MapList (清單中的對應結構描述必須符合物件。) 如需詳細資訊，請參閱《AWS Systems Manager API 參考**》中的 [Target](https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_Target.html)。  
必要：否 (如果您未指定 `Targets`，則必須指定 InstanceIds 或使用 `{{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  
文件中指定的必要和選用參數。  
類型：映射  
必要：否

CloudWatchOutputConfig  
用於傳送命令輸出至 Amazon CloudWatch Logs 的組態選項。如需傳送命令輸出至 CloudWatch Logs 的詳細資訊，請參閱 [設定 Run Command 的 Amazon CloudWatch Logs](sysman-rc-setting-up-cwlogs.md)。  
類型：StringMap (映射的結構描述必須與物件相符。如需詳細資訊，請參閱《*AWS Systems Manager API 參考*》中的 [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  
用於命令輸出回應的 S3 儲存貯體名稱。您的受管節點必須具有 S3 儲存貯體許可，才能成功記錄輸出。  
類型：字串  
必要：否

OutputS3KeyPrefix  
字首。  
類型：字串  
必要：否

ServiceRoleArn  
 AWS Identity and Access Management (IAM) 角色的 ARN。  
類型：字串  
必要：否

TimeoutSeconds  
在執行個體 AWS Systems Manager SSM Agent上等待命令交付至 的時間，以秒為單位。如果在指定的值到達之前執行個體上的 SSM Agent 沒有收到命令，則命令的狀態會變更為 `Delivery Timed Out`。  
類型：整數  
必要：否  
有效值：30-2592000Output

CommandId  
命令的 ID。

狀態  
命令的狀態。

ResponseCode  
命令的回應代碼。如果執行的文件有 1 個以上步驟，則不會傳回此輸出的值。

Output  
命令的輸出。如果您使用命令將標籤或多個執行個體設為目標，則不會傳回 output 值。您可以使用 `GetCommandInvocation` 和 `ListCommandInvocations` API 操作來擷取個別執行個體的輸出。

# `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  
執行個體 (IAM) 執行個體描述檔的 Amazon Resource Name AWS Identity and Access Management (ARN)。  
類型：字串  
必要：否

IamInstanceProfileName  
執行個體之 IAM 執行個體設定檔的名稱。  
類型：字串  
必要：否

ImageId  
Amazon Machine Image (AMI) 的 ID。  
類型：字串  
必要：是

InstanceInitiatedShutdownBehavior  
指示執行個體在系統關機時停止或終止。  
類型：字串  
必要：否

InstanceType  
執行個體類型。  
如果不提供執行個體類型價值，則會使用 m1.small 執行個體類型。
類型：字串  
必要：否

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 編碼。  
類型：字串  
必要：否Output

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"
    }
}
```

------

**注意**  
自動化支援的延遲上限為 604799 秒 (7 天)。

持續時間  
ISO 8601 持續時間。您無法指定負數的持續時間。  
類型：字串  
必要：否

時間戳記  
ISO 8601 時間戳記。如果您不指定此參數的值，則您必須指定 `Duration` 參數的值。  
類型：字串  
必要：否Output

無  


# `aws:updateVariable` - 更新執行手冊變數的值
<a name="automation-action-update-variable"></a>

此動作會更新執行手冊變數的值。值的資料類型必須符合您希望更新的變數的資料類型。不支援資料類型轉換。`aws:updateVariable` 動作不支援 `onCancel` 屬性。

**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`  
類型：字串  
必要：是

Value  
要指派給變數的新值。該值必須與變數的資料類型相符。不支援資料類型轉換。  
類型：布林值 \$1 整數 \$1 MapList \$1 字串 \$1 StringList \$1 StringMap  
必要：是  
限制條件：  
+ MapList 最多可包含 200 個項目。
+ 鍵的長度最短可以是 1，最長可以是 50。
+ StringList 最少可以是 0 個項目，最多可以是 50 個項目。
+ 字串的長度最短可以是 1，最長可以是 512。Output

無  


# `aws:waitForAwsResourceProperty` – 等待 AWS 資源屬性
<a name="automation-action-waitForAwsResourceProperty"></a>

`aws:waitForAwsResourceProperty` 動作可讓您的自動化在繼續自動化之前等待特定的資源狀態或事件狀態。如需有關如何使用此動作的更多範例，請參閱 [其他執行手冊範例](automation-document-examples.md)。

**注意**  
此動作的預設逾時值為 3600 秒 (1 小時)。您可以透過指定 `aws:waitForAwsResourceProperty` 步驟的 `timeoutSeconds` 參數來限制或延長逾時。如需使用此動作的詳細資訊和範例，請參閱 [處理 Runbook 中的逾時](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 操作之名稱。您可以檢視 API 操作 (也稱為方法)，方式是在以下[服務參考](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/index.html)頁面的左側導覽中選擇一項服務。在您想要呼叫之服務的 **Client (用戶端)** 部分選擇一個方法。例如，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)頁面的左側導覽中選擇一項服務。在您想要呼叫之服務的 **Client (用戶端)** 部分選擇一個方法。例如，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)頁面的左側導覽中選擇一項服務。在您想要呼叫之服務的 **Client (用戶端)** 部分選擇一個方法。例如，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  
必要：是

# 自動化系統變數
<a name="automation-variables"></a>

AWS Systems Manager Automation Runbook 使用以下變數。如需這些變數的使用範例，請檢視 `AWS-UpdateWindowsAmi` Runbook 的 JSON 來源。

**檢視 `AWS-UpdateWindowsAmi` Runbook 的 JSON 來源**

1. 開啟位於 AWS Systems Managerhttps://console.aws.amazon.com/systems-manager/ 的主控台。[https://console.aws.amazon.com/systems-manager/](https://console.aws.amazon.com/systems-manager/)

1. 在導覽窗格中，選擇 **Documents (文件)**。

1. 在文件清單中，使用搜尋列或搜尋列右側的號碼選擇 Runbook `AWS-UpdateWindowsAmi`。

1. 選擇 **Content (內容)** 索引標籤。

**系統變數**  
Automation Runbook 目前支援以下系統變數。


****  

| 變數 | 詳細資訊 | 
| --- | --- | 
|  `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 (US-West) 區域的資源分割區為 `aws-us-gov`。  | 
|  `global:REGION`  |  Runbook 執行的區域。例如 us-east-2。  | 

**自動化變數**  
Runbook 支援以下自動化變數。


****  

| 變數 | 詳細資訊 | 
| --- | --- | 
|  `automation:EXECUTION_ID`  |  指派給目前自動化的唯一識別符。例如 `1a2b3c-1a2b3c-1a2b3c-1a2b3c1a2b3c1a2b3c`。  | 

**Topics**
+ [術語](#automation-terms)
+ [支援的案例](#automation-variables-support)
+ [不支援的案例](#automation-variables-unsupported)

## 術語
<a name="automation-terms"></a>

以下術語說明如何解決變數和參數。


****  

| 術語 | 定義 | 範例 | 
| --- | --- | --- | 
|  Constant ARN (常數 ARN)  |  不含變數的有效 Amazon Resource Name (ARN)。  |  `arn:aws:iam::123456789012:role/roleName`  | 
|  Runbook 參數  |  在 Runbook 層級定義的參數 (例如，`instanceId`)。此參數用於基本的字串替換。此值會在 Start Execution (開始執行) 時間提供。  |  <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>  | 
|  System variable (系統變數)  |  在 Runbook 任何部分評估時替換到 Runbook 的一般變數。  |  <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>  | 
|  Automation variable (自動化變數)  |  在文件任何部分評估時替換到 Runbook 且與自動化相關的變數。  |  <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` 提供的 Runbook 參數。  |  必須在 Runbook 的參數清單中定義。  |  <pre>{<br />  "description": "Test all Automation resolvable parameters",<br />  "schemaVersion": "0.3",<br />  "assumeRole": "{{dynamicARN}}",<br />  "parameters": {<br /> ...</pre>  | 
|  在開始時提供給 Runbook 參數的值。  |  客戶提供用於參數的值。在開始時間提供的任何輸入都必須在 Runbook 的參數清單中定義。  |  <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"] }`  | 
|  Runbook 內容中參考的 Systems Manager 參數。  |  變數存在於客戶帳戶內，或是可公開存取的參數，而且 Runbook 的 `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>  | 
|  在步驟定義中參考的系統變數  |  當自動化啟動時，系統變數會替換至 Runbook。插入 Runbook 的值與替換發生的時間相關。例如，由於執行步驟之間耗費的時間，因此在步驟 1 插入的時間變數值會不同於在步驟 3 插入的值。系統變數不必在 Runbook 的參數清單中設定。  |  <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>  | 
|  在步驟定義中參考的自動化變數。  |  自動化變數不必在 Runbook 的參數清單中設定。唯一支援的自動化變數為 **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}}`。客戶無法在 Runbook 參數使用此語法。在參照步驟執行時，會解決此問題。此參數不列於 Runbook 參數中。  |  <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>  | 
|  變數步驟定義  |  Runbook 步驟的定義是由變數建構。  |  <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>  | 
|  交互參照 Runbook 參數  |  使用者會在開始時間提供輸入參數，而這是 Runbook 中另一個參數的參考。  |  <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>  | 
|  多層級擴展  |  Runbook 會定義一個評估變數名稱的變數。這位於變數分隔符號內 (即 *\$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>  | 
|  參考 Runbook 步驟的輸出，其為不同的變數類型  |  使用者參考後續步驟內先前 Runbook 步驟的輸出。輸出為不符合後續步驟中動作需求的變數類型。  |  <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 Runbook 定義 Systems Manager 在自動化執行時，對受管執行個體和其他 AWS 資源執行*的動作*。Automation 是 AWS Systems Manager中的工具。Runbook 包含循序執行的一或多個步驟。每個步驟都是圍繞單一動作而建立的。來自一個步驟的輸出可以作為後續步驟中的輸入。

執行這些動作及其步驟的程序稱為*自動化*。

Runbook 支援的動作類型可讓您自動化 AWS 環境中的各種操作。例如，使用 `executeScript` 動作類型，您可以直接在 Runbook 中嵌入 Python 或 PowerShell 指令碼。(建立自訂 Runbook 時，您可以內嵌新增指令碼，或從 S3 儲存貯體或本機電腦連接指令碼。) 您可以使用 `createStack`和 `deleteStack`動作類型來自動化 AWS CloudFormation 資源的管理。此外，使用 `executeAwsApi`動作類型，步驟可以在任何 中執行*任何 *API 操作 AWS 服務，包括建立或刪除 AWS 資源、啟動其他程序、啟動通知等等。

如需自動化所支援的全部 20 個動作類型清單，請參閱 [Systems Manager Automation 動作參考](automation-actions.md)。

AWS Systems Manager 自動化提供數個執行手冊，其中包含預先定義的步驟，可用來執行常見的任務，例如重新啟動一或多個 Amazon Elastic Compute Cloud (Amazon EC2) 執行個體或建立 Amazon Machine Image()AMI。您也可以建立自己的 Runbook 並與其他 共用 AWS 帳戶，或公開給所有自動化使用者。

Runbook 使用 YAML 或 JSON 編寫而成。使用 Systems Manager Automation 主控台中的 **Document Builder** (文件建置器)，不過，您可以建立 Runbook，而無需以原生 JSON 或 YAML 撰寫。

**重要**  
如果您執行可使用 AWS Identity and Access Management (IAM) 服務角色叫用其他服務的自動化工作流程，請注意您必須為該服務角色設定可叫用這些服務的許可。此需求適用於所有 AWS Automation Runbook (`AWS-*` Runbook)，例如 `AWS-ConfigureS3BucketLogging`、 `AWS-CreateDynamoDBBackup`和 `AWS-RestartEC2Instance` Runbook。此要求也適用於您建立的任何自訂 Automation Runbook， AWS 服務 透過使用呼叫其他 服務的動作來叫用其他 。例如，如果您使用 `aws:executeAwsApi`、`aws:createStack` 或 `aws:copyImage` 動作，為服務角色設定可叫用這些服務的許可。您可新增 IAM 內嵌政策到角色，以啟用其他 AWS 服務 的許可。如需詳細資訊，請參閱[（選用） 新增自動化內嵌政策或客戶受管政策以叫用其他 AWS 服務](automation-setup-iam.md#add-inline-policy)。

如需您可以在 Runbook 中指定的動作的相關資訊，請參閱 [Systems Manager Automation 動作參考](automation-actions.md)。

如需有關使用 AWS Toolkit for Visual Studio Code 建立 Runbook 的資訊，請參閱*AWS Toolkit for Visual Studio Code 《 使用者指南*》中的[使用 Systems Manager Automation 文件](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 Runbook](automation-authoring-runbooks.md)
  + [識別您的使用案例](automation-authoring-runbooks.md#automation-authoring-runbooks-use-case)
  + [設定開發環境](automation-authoring-runbooks.md#automation-authoring-runbooks-environment)
  + [開發 Runbook 內容](automation-authoring-runbooks.md#automation-authoring-runbooks-developing-content)
  + [範例 1：建立父子 Runbook](automation-authoring-runbooks-parent-child-example.md)
    + [建立子系 Runbook](automation-authoring-runbooks-parent-child-example.md#automation-authoring-runbooks-child-runbook)
    + [建立父系 Runbook](automation-authoring-runbooks-parent-child-example.md#automation-authoring-runbooks-parent-runbook)
  + [範例 2：指令碼式 Runbook](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)
  + [使用 Runbook 的許可](automation-document-script-considerations.md#script-permissions)
  + [將指令碼新增至 Runbook](automation-document-script-considerations.md#adding-scripts)
  + [Runbook 的指令碼限制](automation-document-script-considerations.md#script-constraints)
+ [在執行手冊中使用條件陳述式](automation-branch-condition.md)
  + [使用 `aws:branch` 動作](automation-branch-condition.md#branch-action-explained)
    + [在 Runbook 中建立 `aws:branch` 步驟](automation-branch-condition.md#create-branch-action)
      + [關於建立輸出變數](automation-branch-condition.md#branch-action-output)
    + [範例 `aws:branch` Runbook](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 建立 Webhook 整合](creating-webhook-integrations.md)
  + [建立整合 (主控台)](creating-webhook-integrations.md#creating-integrations-console)
  + [建立整合 (命令列)](creating-webhook-integrations.md#creating-integrations-commandline)
  + [為整合建立 Webhook](creating-webhook-integrations.md#creating-webhooks)
+ [處理 Runbook 中的逾時](automation-handling-timeouts.md)

# Automation 執行手冊的視覺化設計體驗
<a name="automation-visual-designer"></a>

AWS Systems Manager 自動化提供低程式碼視覺化設計體驗，協助您建立自動化 Runbook。視覺化設計體驗提供拖放式介面，可選擇新增自己的程式碼，讓您可以更輕鬆地建立和編輯執行手冊。透過視覺化設計體驗，您可以執行下列操作：
+ 控制條件陳述式。
+ 控制每個動作篩選或轉換輸入和輸出的方式。
+ 設定錯誤處理。
+ 製作新執行手冊的原型。
+ 使用您的原型執行手冊做為 AWS Toolkit for Visual Studio Code本機開發的起點。

當您建立或編輯執行手冊時，可以從 [Automation 主控台](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/zh_tw/systems-manager/latest/userguide/images/visual_designer_overview.png)

+ **動作**瀏覽器包含**動作**、**AWS API** 和**執行手冊**索引標籤。
+ 在*畫布*上，您可以將動作拖放到工作流程圖形中、變更動作順序，以及選取要設定或檢視的動作。
+ 您可以在**表單**面板中檢視和編輯您在畫布上選取之任何動作的屬性。選取**內容**切換按鈕可檢視執行手冊的 YAML 或 JSON，並反白顯示目前選取的動作。

當您需要協助時，**資訊**連結會開啟包含內容資訊的面板。這些面板也包含 Systems Manager Automation 文件中相關主題的連結。

## 動作瀏覽器
<a name="visual-designer-actions"></a>

從**動作**瀏覽器，您可以選取要拖放到工作流程圖形的動作。您可以使用**動作**瀏覽器頂端的搜尋欄位來搜尋所有動作。**動作**瀏覽器包含下列索引標籤：
+ **動作**索引標籤提供自動化動作清單，您可以將這些動作拖放到畫布中執行手冊工作流程圖形中。
+ **AWS APIs** 索引標籤提供 AWS APIs 的清單，您可以在畫布中拖放至 Runbook 的工作流程圖表。
+ **執行手冊**索引標籤提供了多個即用型、可重複使用的執行手冊做為建置區塊，您可用於各種用例。例如，您可以使用執行手冊在工作流程的 Amazon EC2 執行個體上執行常見的修復任務，而不必重新建立相同的動作。

![\[視覺化設計體驗動作瀏覽器\]](http://docs.aws.amazon.com/zh_tw/systems-manager/latest/userguide/images/visual_designer_actions_multi_view.png)


## Canvas
<a name="visual-designer-canvas"></a>

選擇要新增至自動化的動作後，將其拖曳至畫布並放入工作流程圖形中。您也可以拖放動作，將其移動到執行手冊工作流程的不同位置。如果工作流程很複雜，則您可能無法在畫布面板中檢視所有工作流程。使用畫布頂端的控制項來放大或縮小。若要檢視工作流程的不同部分，可以在畫布中拖曳工作流程圖形。

從**動作**瀏覽器中拖曳動作，將其放入執行手冊的工作流程圖形中。有一條線會顯示它將放置在工作流程中的位置。若要變更動作的順序，可以將其拖曳至工作流程中的其他位置。新動作已新增至您的工作流程，其程式碼會自動產生。

![\[視覺化設計體驗畫布\]](http://docs.aws.amazon.com/zh_tw/systems-manager/latest/userguide/images/visual_designer_canvas.png)


## 表格
<a name="visual-designer-form"></a>

將動作新增至執行手冊工作流程之後，您可以對其進行設定，以符合您的用例。選擇您要設定的動作，您就會在**表單**面板中看到其參數和選項。您也可以選擇**內容**按鈕，查看 YAML 或 JSON 程式碼。與您已選取的動作相關聯的程式碼會反白顯示。

![\[視覺化設計體驗表單面板\]](http://docs.aws.amazon.com/zh_tw/systems-manager/latest/userguide/images/visual_designer_form.png)


![\[視覺化設計體驗內容面板\]](http://docs.aws.amazon.com/zh_tw/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` 自動化動作包含下列區域：
+ **執行期**是用於執行所提供指令碼的執行期語言。
+ **處理常式**是您的函數的名稱。您必須確保處理常式中定義的函數有兩個參數：`events` 和 `context`。PowerShell 執行期不支援此參數。
+ **指令碼**是您想要在工作流程期間執行的嵌入式指令碼。
+ (選用) **附件**適用於可由動作調用的獨立指令碼或 .zip 檔案。JSON 執行手冊需要此參數。

**輸出**索引標籤可協助您指定要從動作輸出的值。您可以在工作流程的後續動作中參考輸出值，或從動作產生輸出，以供日誌記錄之用。並非所有動作都支援輸出，因而並非所有動作都會有**輸出**索引標籤。例如，`aws:pause` 動作不支援輸出。對於支援輸出的動作，**輸出**索引標籤包含下列區段：
+ **名稱**是要用於輸出值的名稱。您可以在工作流程的後續動作中參考輸出。
+ **選取器**是以 `"$."` 開頭的 JSONPath 運算式字串，用於在 JSON 元素中選取一個或多個元件。
+ **類型**是輸出值的資料類型。例如，`String` 或 `Integer` 資料類型。

**組態**索引標籤包含所有自動化動作均可使用的屬性和選項。該動作由下列各部分組成：
+ **嘗試次數上限**屬性是動作失敗時重試的次數。
+ **逾時秒**屬性指定動作的逾時值。
+ **是關鍵**屬性決定動作失敗是否會停止整個自動化作業。
+ **下一步**屬性決定自動化在執行手冊中接下來執行的動作。
+ **失敗時**屬性決定如果動作失敗，自動化在執行手冊中接下來執行的動作。
+ **取消時**屬性會決定如果使用者取消動作，自動化在執行手冊中接下來執行的動作。

若要刪除動作，您可以使用退格鍵 (位於畫布上方的工具列)，或按一下滑鼠右鍵並選擇**刪除動作**。

隨著工作流程的增長，它可能不適應畫布。若要協助讓工作流程適應畫布，請嘗試下列選項之一：
+ 使用側面板上的控制項，調整面板的大小或關閉面板。
+ 使用畫布頂端的工具列可放大或縮小工作流程圖形。

## 更新執行手冊
<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. 選擇 **Create new version (建立新版本)**。

1. 視覺化設計體驗包含兩個窗格：程式碼窗格和視覺化工作流程窗格。在視覺化工作流程窗格中選擇**設計**，以透過視覺化設計體驗編輯工作流程。完成後，請選擇**建立新版本**，以儲存變更並退出。

1. (選用) 使用程式碼窗格編輯 YAML 或 JSON 中的執行手冊內容。

## 匯出執行手冊
<a name="visual-designer-export-runbook"></a>

若要匯出執行手冊工作流程的 YAML 或 JSON 程式碼，以及工作流程的圖表，請使用下列程序：

1. 在**文件**主控台中選擇您的執行手冊。

1. 選擇 **Create new version (建立新版本)**。

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 操作。在此範例中，您想要傳回或輸出 Amazon EC2 執行個體的 `State`，並根據輸出對執行手冊的工作流程進行分支。您可以選擇將輸出命名為 **InstanceState**，並使用 **String** 資料類型。

定義輸出實際值的程序會取決於動作而略有差異。例如，若您正在使用 `aws:executeScript` 動作，則必須在函數中使用 `return` 陳述式，為輸出提供資料。使用其他動作 (如 `aws:executeAwsApi`、`aws:waitForAwsResourceProperty` 和 `aws:assertAwsResourceProperty`) 會需要 `Selector`。或正如某些動作所參考的，`Selector` 或 `PropertySelector` 是用來處理來自 API 操作的 JSON 回應的 JSONPath 字串。了解來自 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/zh_tw/systems-manager/latest/userguide/images/visual_designer_error_handling.png)


## 出現錯誤時重試動作
<a name="retry-actions"></a>

若要在出現錯誤時重試動作，請指定**嘗試次數上限**屬性的值。預設值為 1. 如果指定的值大於 1，則在所有重試嘗試失敗之前，動作不會視為失敗。

## 逾時
<a name="timeout-seconds"></a>

您可設定動作逾時，以設定動作失敗前可執行的秒數上限。若要設定逾時，請在**逾時秒**屬性中輸入動作失敗之前，動作應等待的秒數。如果達到逾時且動作的 `Max attempts` 值大於 1，則在完成所有重試之前，步驟不會視為逾時。

## 失敗的動作
<a name="failure-actions"></a>

根據預設，當動作失敗時，Automation 會完全停止執行手冊的工作流程。您可以透過為執行手冊中動作的**失敗時**屬性指定替代值，以修改此行為。如果您希望工作流程繼續執行執行手冊中的下個步驟，則請選擇**繼續**。如果您希望工作流程跳至執行手冊中的其他後續步驟，則請選擇**步驟**，然後輸入步驟的名稱。

## 取消的動作
<a name="cancel-actions"></a>

根據預設，當使用者取消動作時，Automation 會完全停止執行手冊的工作流程。您可以透過為執行手冊中動作的**取消時**屬性指定替代值，以修改此行為。如果您希望工作流程跳至執行手冊中的其他後續步驟，則請選擇**步驟**，然後輸入步驟的名稱。

## 關鍵動作
<a name="critical-actions"></a>

您可以將某個動作指定為*關鍵*動作，這表示它會決定了自動化操作的整體報告狀態。如果此指定步驟失敗，則 Automation 會將最終狀態報告為 `Failed`，不論其他動作是否成功。若要將動作設定為關鍵，請將**為關鍵**屬性的預設值保留為 **True**。

## 結束動作
<a name="end-actions"></a>

**為結束**屬性會在指定動作結束時停止自動化。此屬性的預設值為 `false`。如果您為動作設定此屬性，則無論動作成功還是失敗，自動化都會停止。此屬性最常與 `aws:branch` 動作搭配使用，以處理非預期或未定義的輸入值。下列範例顯示預期執行個體狀態為 `running`、`stopping` 或 `stopped` 的執行手冊。如果執行個體處於不同的狀態，則自動化將結束。

![\[視覺化設計體驗是最終範例\]](http://docs.aws.amazon.com/zh_tw/systems-manager/latest/userguide/images/visual_designer_is_end_example.png)


# 教學課程：使用視覺化設計體驗建立執行手冊
<a name="visual-designer-tutorial"></a>

在本教學課程中，您將了解使用 Systems Manager Automation 提供的視覺化設計體驗的基礎概念。在視覺化設計體驗中，您可以建立使用多個動作的執行手冊。您可使用拖放功能來排列畫布上的動作。您也可搜尋、選取和設定這些動作。然後，您可檢視執行手冊工作流程自動產生的 YAML 程式碼，退出結束視覺化設計體驗，執行該執行手冊，以及檢閱執行詳細資料。

本教學課程還將向您展示如何更新執行手冊並查看新版本。在教學課程結束時，您可執行清理步驟並刪除執行手冊。

完成本教學課程之後，您就會知道如何使用視覺化設計體驗來建立執行手冊。您還將知道如何更新、執行和刪除您的執行手冊。

**注意**  
在您開始教學課程之前，請務必先完成 [設定自動化](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/zh_tw/systems-manager/latest/userguide/images/visual_designer_tutorial_name.png)

1. 在**表單**面板的**文件屬性**區段中，展開**輸入參數**下拉式清單，然後選取**新增參數**。

   1. 在**參數名稱**欄位中，輸入 **InstanceId**。

   1. 在**類型**下拉式清單中，選擇 **AWS::EC2::Instance**。

   1. 選取**必要**切換按鈕。  
![\[為您的執行手冊建立一個參數\]](http://docs.aws.amazon.com/zh_tw/systems-manager/latest/userguide/images/visual_designer_actions_tutorial_parameter.png)

1. 在 **AWS API** 瀏覽器中，在搜尋列輸入 **DescribeInstances**。

1. 將 **Amazon EC2 - DescribeInstances** 動作拖曳至空白畫布。

1. 對於**步驟名稱**，輸入值。在本教學課程中，您可以使用名稱 **GetInstanceState**。  
![\[選擇一個 Amazon EC2 描述執行個體 API 動作。\]](http://docs.aws.amazon.com/zh_tw/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/zh_tw/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. 在**預設規則**中，針對**預設步驟**選擇**移至結尾**。

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** 動作的**組態**索引標籤中，從**下一步**下拉式清單中選擇 **StartInstance**。

1. 將**在執行個體上執行命令**動作拖曳至 **\$1\$1 GetInstanceState.InstanceState \$1\$1 == "running"** 條件下方空白的**拖曳至此處**方塊。

1. 對於**步驟名稱**，輸入 **SayHello**。

   1. 在**輸入**索引標籤中，為**文件名稱**參數輸入 **AWS-RunShellScript**。

   1. 對於 **InstanceIds**，從下拉式清單中選擇**執行個體 ID** 文件輸入值。

   1. 展開**其他輸入**下拉式清單，然後在**輸入名稱**下拉清單中選擇**參數**。

   1. 在**輸入值**欄位中輸入 **`{"commands": "echo 'Hello World'"}`**。

1. 檢閱畫布中已完成的執行手冊，然後選取**建立手冊**以儲存教學執行手冊。  
![\[檢閱並建立執行手冊。\]](http://docs.aws.amazon.com/zh_tw/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>

建立您的執行手冊後，您可以執行自動化。

**若要執行新的自動化執行手冊**

1. 在 https：//[https://console.aws.amazon.com/systems-manager/](https://console.aws.amazon.com/systems-manager/) 開啟 AWS Systems Manager 主控台。

1. 在導覽窗格中，選擇 **Automation (自動化)**，接著選擇 **Execute automation (執行自動化)**。

1. 在 **Automation document** (自動化文件) 清單中，選擇 Runbook。在 **Document categories** (文件類別) 窗格中選擇一個或多個選項，根據 SSM 文件的用途來進行篩選。若要檢視您擁有的 Runbook，請選擇 **Owned by me** (我所擁有的) 索引標籤。若要檢視與您帳戶共用的 Runbook，請選擇 **Shared with me** (與我共用的) 索引標籤。若要檢視所有 Runbook，請選擇 **All documents** (所有文件) 索引標籤。
**注意**  
您可以選擇 Runbook 名稱檢視 Runbook 資訊。

1. 在 **Document details** (文件詳細資訊) 部分，確認 **Document version** (文件版本) 設定為您想要執行的版本。系統包括以下版本選項：
   + **執行期的預設版本**：如果 Automation 執行手冊會定期更新且已指派新的預設版本，則請選擇此選項。
   + **執行期的最新版本**：如果 Automation 執行手冊會定期更新，而您想要執行最近更新的版本，請選擇此選項。
   + **1 (預設)**：選擇此選項以執行文件的第一個版本，也是預設版本。

1. 選擇**下一步**。

1. 在**執行自動化執行手冊**章節中，選擇**簡易執行**。

1. 在 **Input parameters (輸入參數)** 部分，指定所需的輸入。或者，您也可以從 **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. 選擇 **Execute (執行)**。

## 步驟 5：清除
<a name="cleanup-tutorial-runbook"></a>

**若要刪除您的執行手冊**

1. 在 https：//[https://console.aws.amazon.com/systems-manager/](https://console.aws.amazon.com/systems-manager/) 開啟 AWS Systems Manager 主控台。

1. 在導覽窗格中，選擇 **Documents (文件)**。

1. 選擇**我所擁有**索引標籤。

1. 找到 **VisualDesignExperienceTutorial** 執行手冊。

1. 選取文件卡頁面上的按鈕，然後從**動作**下拉式清單中選擇**刪除文件**。

# 撰寫 Automation Runbook
<a name="automation-authoring-runbooks"></a>

Automation 中的每個 Runbook 都是其中的工具 AWS Systems Manager，可定義自動化。Automation Runbook 會定義在自動化期間執行的動作。在 Runbook 內容中，您可以定義 Systems Manager 在受管執行個體 AWS 和資源上執行的輸入參數、輸出和動作。

自動化包含數個預先定義的 Runbook，供您用來執行常見任務，像是重新啟動一個或多個 Amazon Elastic Compute Cloud (Amazon EC2) 執行個體，或建立 Amazon Machine Image (AMI)。不過，您的使用案例可能會超出預先定義 Runbook 的功能。如果是這種情況，您可以建立自己的 Runbook，並根據您的需求進行修改。

Runbook 包含自動化動作、這些動作的參數，以及您指定的輸入參數。Runbook 的內容是以 YAML 或 JSON 撰寫。如果您不熟悉 YAML 或 JSON，則建議在嘗試撰寫自己的執行手冊之前使用視覺化設計工具，或了解更多關於任一標記語言的資訊。如需有關視覺化設計工具的詳細資訊，請參閱 [Automation 執行手冊的視覺化設計體驗](automation-visual-designer.md)。

下列各節將協助您撰寫首個 Runbook。

## 識別您的使用案例
<a name="automation-authoring-runbooks-use-case"></a>

撰寫 Runbook 的第一個步驟是識別您的使用案例。例如，您排定了每天在所有生產 Amazon EC2 執行個體上執行的 `AWS-CreateImage` Runbook。在月底，您會決定是否擁有超過復原點所需數量的映像。接下來，在建立新 AMI 時，您想要自動刪除最舊的 Amazon EC2 執行個體 AMI。若要完成這項操作，您可以建立執行以下動作的新 Runbook：

1. 執行 `aws:createImage` 動作，並在映像描述中指定執行個體 ID。

1. 在 `available` 前，執行 `aws:waitForAwsResourceProperty` 動作來輪詢圖像的狀態。

1. 映像狀態為 `available` 後，`aws:executeScript` 動作會執行自訂 Python 指令碼，該指令碼會收集與您的 Amazon EC2 執行個體相關聯的所有映像 ID。指令碼會使用您在建立時指定之映像描述中的執行個體 ID 進行篩選。然後，指令碼會根據映像的 `creationDate` 對映像 ID 進行排序，並輸出最舊 AMI 的 ID。

1. 最後，`aws:deleteImage` 動作會使用上一個步驟輸出的 ID 刪除最舊的 AMI。

在這個案例中，您已經使用 `AWS-CreateImage` Runbook，但發現您的使用案例需要更大的靈活性。這是常見的情況，因為 Runbook 和自動化動作之間可能會有重疊。因此，您可能必須調整您用於處理使用案例的 Runbook 或動作。

例如，`aws:executeScript` 和 `aws:invokeLambdaFunction` 動作都允許您在自動化過程中執行自訂指令碼。若要在兩者之間進行選擇，因為其他支援的執行時間語言，您可能偏好 `aws:invokeLambdaFunction`。但是，您可能偏好 `aws:executeScript`，因為它允許您直接在 YAML Runbook 中撰寫指令碼內容，並提供指令碼內容作為 JSON Runbook 的附件。您也可以考慮 `aws:executeScript`，在 AWS Identity and Access Management (IAM) 設定更簡單。因為它使用 中提供的許可`AutomationAssumeRole`，`aws:executeScript`因此不需要額外的 AWS Lambda 函數執行角色。

在任何給定的情況下，相較於另一個動作，一個動作可能會提供更多的靈活性或新增的功能。因此，建議您檢閱要使用之 Runbook 或動作的可用輸入參數，以判斷哪個最適合您的使用案例和偏好設定。

## 設定開發環境
<a name="automation-authoring-runbooks-environment"></a>

識別您的使用案例以及您想要在 Runbook 中使用的預先定義 Runbook 或自動化動作之後，便是時候為 Runbook 內容設定開發環境了。若要開發您的 Runbook 內容，建議您使用 AWS Toolkit for Visual Studio Code ，而非 Systems Manager 文件主控台。

Toolkit for VS Code 是 Visual Studio 程式碼 (VS 程式碼) 的開放原始碼延伸項目，提供比 Systems Manager 文件主控台更多的功能。實用的功能包括 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 開發 Runbook 的相關資訊，請參閱《*AWS Toolkit for Visual Studio Code 使用者指南*》中的[使用 Systems Manager Automation 文件](https://docs.aws.amazon.com/toolkit-for-vscode/latest/userguide/systems-manager-automation-docs.html)。

## 開發 Runbook 內容
<a name="automation-authoring-runbooks-developing-content"></a>

識別使用案例並設定環境後，即可準備開發 Runbook 適用的內容。您的使用案例和偏好設定主要會決定您在 Runbook 內容中使用的自動化動作或 Runbook。與允許您完成類似任務的另一個動作相比，某些動作僅支援輸入參數的子集。其他動作具有特定輸出，例如 `aws:createImage`，其中一些動作允許您定義自己的輸出，例如 `aws:executeAwsApi`。

如果您不確定如何在 Runbook 中使用特定動作，建議您檢閱 [Systems Manager Automation 動作參考](automation-actions.md) 中動作的對應項目。也建議您檢閱預先定義的 Runbook 內容，以查看如何使用這些動作的真實世界範例。如需 Runbook 真實世界應用程式的更多範例，請參閱 [其他執行手冊範例](automation-document-examples.md)。

為了展示 Runbook 內容提供的簡單性和靈活性差異，下列教學課程提供如何分階段修補 Amazon EC2 執行個體群組的範例：
+ [範例 1：建立父子 Runbook](automation-authoring-runbooks-parent-child-example.md) – 在此範例中，兩個 Runbook 會用於父子關係中。父系 Runbook 會啟動子系 Runbook 的速率控制自動化。
+ [範例 2：指令碼式 Runbook](automation-authoring-runbooks-scripted-example.md) – 此範例示範如何透過將內容壓縮成單一 Runbook 並在 Runbook 中使用指令碼，來完成範例 1 的相同任務。

# 範例 1：建立父子 Runbook
<a name="automation-authoring-runbooks-parent-child-example"></a>

以下範例演示如何建立兩個 Runbook，以分階段修補加上標籤的 Amazon Elastic Compute Cloud (Amazon EC2) 執行個體群組。這些 Runbook 用於父子關係中，其中父系 Runbook 用來起始子系 Runbook 的速率控制自動化。如需速率控制自動化的詳細資訊，請參閱 [大規模執行自動化操作](running-automations-scale.md)。如需此範例中所使用自動化動作的詳細資訊，請參閱 [Systems Manager Automation 動作參考](automation-actions.md)。

## 建立子系 Runbook
<a name="automation-authoring-runbooks-child-runbook"></a>

此範例 Runbook 會處理以下案例。Emily 是 AnyCompany Consultants, LLC 的系統工程師。她需要針對託管主要和次要資料庫的 Amazon Elastic Compute Cloud (Amazon EC2) 執行個體群組設定修補。應用程式每天 24 小時存取這些資料庫，因此其中一個資料庫執行個體必須永遠可用。

她認為分階段修補執行個體是最好的方法。先修補資料庫執行個體的主要群組，然後再修補資料庫執行個體的次要群組。此外，為了避免讓先前停用的執行個體因執行而產生額外的成本，Emily 希望修補的執行個體在修補發生之前恢復到原始狀態。

Emily 透過與執行個體相關聯的標籤來識別資料庫執行個體的主要和次要群組。她決定建立啟動子系 Runbook 速率控制自動化的父系 Runbook。透過如此操作，她可以鎖定與資料庫執行個體之主要和次要群組相關聯的標籤，並管理子系自動化的並行性。在檢閱可用 Systems Manager (SSM) 文件以進行修補之後，她選擇 `AWS-RunPatchBaseline` 文件。透過使用此 SSM 文件，她的同事可以在修補操作完成後，檢閱相關聯的修補程式合規資訊。

若要開始建立她的 Runbook 內容，Emily 會檢閱可用的自動化動作，並開始撰寫子系 Runbook 的內容，如下所示：

1. 首先，她提供 Runbook 結構描述和描述的值，並定義子系 Runbook 的輸入參數。

   透過使用 `AutomationAssumeRole` 參數，Emily 和她的同事可以使用現有 IAM 角色，允許 Automation 代表他們執行 Runbook 中的動作。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 會繼續撰寫構成 Runbook `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 會檢閱已完成的子 Runbook 內容，並在 AWS 區域 與目標執行個體相同的 AWS 帳戶 和 中建立 Runbook。現在，她已準備好繼續建立父系 Runbook 的內容。以下是已完成的子系 Runbook 內容。

------
#### [ 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)。

## 建立父系 Runbook
<a name="automation-authoring-runbooks-parent-runbook"></a>

此範例 Runbook 會繼續上一節所述的案例。現在 Emily 已經建立子系 Runbook，她開始撰寫父系 Runbook 的內容，如下所示：

1. 首先，她提供 Runbook 結構描述和描述的值，並定義父系 Runbook 的輸入參數。

   透過使用 `AutomationAssumeRole` 參數，Emily 和她的同事可以使用現有 IAM 角色，允許 Automation 代表他們執行 Runbook 中的動作。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 會繼續撰寫構成 Runbook `mainSteps` 的動作。

   第一個動作會使用她剛才建立的、以與 `PatchGroupPrimaryKey` 和 `PatchGroupPrimaryValue` 輸入參數中指定標籤關聯之執行個體為目標的子系 Runbook，啟動速率控制自動化。她使用提供給輸入參數的值來指定與要修補之資料庫執行個體主要群組相關聯的標籤索引鍵和值。

   第一個自動化完成之後，第二個動作會使用以與 `PatchGroupSecondaryKey` 和 `PatchGroupSecondaryValue` 輸入參數中指定標籤關聯之執行個體為目標的子系 Runbook 啟動另一個速率控制自動化。她使用提供給輸入參數的值來指定與要修補之資料庫執行個體次要群組相關聯的標籤索引鍵和值。

------
#### [ 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 會檢閱完成的父系 Runbook 內容，並在 AWS 區域 與目標執行個體相同的 AWS 帳戶 和 中建立 Runbook。現在，她已經準備好測試她的 Runbook，以確保自動化能夠依需要操作，然後再將其實作到她的生產環境中。以下是已完成的父系 Runbook 內容。

------
#### [ 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：指令碼式 Runbook
<a name="automation-authoring-runbooks-scripted-example"></a>

此範例 Runbook 會處理以下案例。Emily 是 AnyCompany Consultants, LLC 的系統工程師。她先前已建立兩個 Runbook，用於父子關係，以修補託管主要和次要資料庫的 Amazon Elastic Compute Cloud (Amazon EC2) 執行個體群組。應用程式每天 24 小時存取這些資料庫，因此其中一個資料庫執行個體必須永遠可用。

根據此需求，她建置了一個解決方案，使用 `AWS-RunPatchBaseline` Systems Manager (SSM) 文件分階段修補執行個體。透過使用此 SSM 文件，她的同事可以在修補操作完成後，檢閱相關聯的修補程式合規資訊。

先修補資料庫執行個體的主要群組，然後再修補資料庫執行個體的次要群組。此外，為了避免讓先前停用的執行個體因執行而產生額外的成本，Emily 確保了在修補發生之前，自動化將修補的執行個體恢復到其原始狀態。Emily 使用與資料庫執行個體的主要和次要群組相關聯的標籤，來識別應依照想要的順序修補哪些執行個體。

她現有的自動化解決方案可以運作，但她想要盡可能改善解決方案。為了協助維護 Runbook 內容並簡化故障診斷工作，她想要將自動化壓縮成單一 Runbook，並簡化輸入參數的數目。此外，她想避免建立多個子系自動化。

Emily 檢閱可用的自動化動作之後，決定可以使用 `aws:executeScript` 動作來執行她的自訂 Python 指令碼，以改善解決方案。她現在開始撰寫 Runbook 的內容，如下所示：

1. 首先，她提供 Runbook 結構描述和描述的值，並定義父系 Runbook 的輸入參數。

   透過使用 `AutomationAssumeRole` 參數，Emily 和她的同事可以使用現有 IAM 角色，允許 Automation 代表他們執行 Runbook 中的動作。與[範例 1](automation-authoring-runbooks-parent-child-example.md) 不同，`AutomationAssumeRole` 參數現在是必要的，而不是選用的。由於此 Runbook 包含 `aws:executeScript` 動作，因此一律需要 AWS Identity and Access Management (IAM) 服務角色 （或擔任角色）。這個要求是必需的，因為一些為動作指定的 Python 指令碼會呼叫 AWS API 操作。

   Emily 使用 `PrimaryPatchGroupTag` 和 `SecondaryPatchGroupTag` 參數來指定與要修補之資料庫執行個體主要和次要群組相關聯的標籤。為簡化必要的輸入參數，她決定使用 `StringMap` 參數，而不是使用多個 `String` 參數 (如範例 1 Runbook 所用)。(選用) `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 會繼續撰寫構成 Runbook `mainSteps` 的動作。第一個步驟會收集與 `PrimaryPatchGroupTag` 參數中指定標籤相關聯之所有執行個體的 ID 並輸出 `StringMap` 參數，其中包含執行個體 ID 和執行個體的目前狀態。此動作的輸出會用於稍後的動作。

   請注意，`script` 輸入參數不支援 JSON Runbook。JSON Runbook 必須使用 `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 使用另外兩個指令碼來傳回 `PrimaryPatchGroupTag` 參數中指定之標籤鍵值的個別 `String` 值。這些動作傳回的值可讓她直接將值提供給 `Targets` 參數，用於 `AWS-RunPatchBaseline` 文件。自動化會繼續使用 `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 會複製其 Runbook 內容中先前的所有動作，以鎖定與 `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 會檢閱已完成的指令碼 Runbook 內容，並在 AWS 區域 與目標執行個體相同的 AWS 帳戶 和 中建立 Runbook。現在，她已經準備好測試她的 Runbook，以確保自動化能夠依需要操作，然後再將其實作到她的生產環境中。以下是已完成的指令碼式 Runbook 內容。

------
#### [ 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>

下列範例 Runbook 示範如何使用 AWS Systems Manager 自動化動作來自動化常見的部署、疑難排解和維護任務。

**注意**  
本節中的範例執行手冊是為了示範如何建立自訂執行手冊，以支援您的特定操作需求。這些 Runbook 並不適用於生產環境中。但是，您可加以自訂以供您自己使用。

**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 是 AWS Systems Manager中的工具。

下列範例 AWS Systems Manager Runbook 會執行這些動作：
+ 使用 Systems Manager Parameter Store 擷取最新的 Windows Server 2016 Amazon Machine Image (AMI)，以在啟動將會設定為網域控制站的 EC2 執行個體時使用。Parameter Store 是 AWS Systems Manager中的工具。
+ 使用`aws:executeAwsApi`自動化動作呼叫數個 AWS API 操作來建立 VPC 架構。網域控制站執行個體會在私有子網路中啟動，並使用 NAT 閘道連線到網際網路。如此可讓執行個體上的 SSM Agent 存取必要的 Systems Manager 端點。
+ 使用`aws:waitForAwsResourceProperty`自動化動作來確認先前動作啟動的執行個體為 `Online` AWS Systems Manager。
+ 使用 `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 是 AWS Systems Manager中的工具。

下列範例 AWS Systems Manager Runbook 會執行這些動作：
+ 使用 `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 是 AWS Systems Manager中的工具。

下列範例 AWS Systems Manager Runbook 會執行這些動作：
+ 使用 `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>

Automation 是 Systems Manager 中的工具，會在 中填入 AWS 管理主控台 符合您為輸入參數定義之 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/.*$`

以下為 Runbook 內容中定義之輸入參數類型的範例。

------
#### [ 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 公有 Runbook 不支援要在 AWS 資源上執行的所有動作，您可以建立自己的 Runbook。若要建立自訂 Runbook，您可以利用適當的自動化動作來手動建立本機 YAML 或 JSON 格式檔案。或者，您可以使用 Systems Manager Automation 主控台中的文件建置器來建置自訂執行手冊。

使用文件建置器，您可以將自動化動作新增至自訂執行手冊，並提供必要的參數，而不需使用 JSON 或 YAML 語法。新增步驟並建立 Runbook 之後，系統會將您新增的動作轉換成 YAML 格式，以便 Systems Manager 可以用來執行自動化。

Runbook 支援使用 Markdown (一種標示語言)，可讓您新增維基樣式的描述至 Runbook 內，以及在 Runbook 內新增個別步驟。如需使用 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)。

**使用文件建置器建立自訂 Runbook**

1. 在 https：//[https://console.aws.amazon.com/systems-manager/](https://console.aws.amazon.com/systems-manager/) 開啟 AWS Systems Manager 主控台。

1. 在導覽窗格中，選擇 **Documents (文件)**。

1. 選擇 **Create automation (建立自動化)**。

1. 對於 **Name** (名稱)，輸入 Runbook 的描述性名稱。

1. 對於 **Document description** (文件描述)，提供 Runbook 的 Markdown 樣式描述。您可以提供使用 Runbook、編號步驟或任何其他類型的資訊的指示來描述 Runbook。如需格式化內容的相關資訊，請參閱預設文字。
**提示**  
在 **Hide preview (隱藏預覽)** 和 **Show preview (顯示預覽)** 之間切換，即可在撰寫時查看描述內容的外觀。

1. (選用) 對於 **Assume role (擔任角色)**，輸入要代表您執行動作的服務角色的名稱或 ARN。如果您未指定角色，自動化會使用執行自動化之使用者的存取許可。
**重要**  
對於使用 `aws:executeScript` 動作的非 Amazon 擁有的 Runbook，必須指定角色。如需相關資訊，請參閱[使用 Runbook 的許可](automation-document-script-considerations.md#script-permissions)。

1. (選用) 對於 **Outputs** (輸出)，輸入用於此 Runbook 自動化以提供其他處理程序使用的任何輸出。

   例如，如果您的 Runbook 建立了新的 AMI，您可以指定 ["CreateImage.ImageId"]，然後使用此輸出在後續的自動化中建立新的執行個體。

1. (選用) 展開 **Input parameters (輸入參數)** 區段，並執行下列動作。

   1. 對於 **Parameter name** (參數名稱)，輸入您要建立的 Runbook 參數的描述性名稱。

   1. 對於 **Type (類型)**，選擇參數的類型，例如 `String` 或 `MapList`。

   1. 對於 **Required (必要)**，執行下列其中一項作業：
      + 如果必須在執行時間提供此 Runbook 參數的值，請選擇 **Yes** (是)。
      + 如果不需要參數，請選擇 **No** (否)，並 (選擇性地) 在 **Default value** (預設值) 中輸入預設參數值。

   1. 對於 **Description** (描述)，輸入 Runbook 參數的描述。
**注意**  
若要新增更多 Runbook 參數，請選擇 **Add a parameter** (新增參數)。若要移除 Runbook 參數，請選擇 **X** (移除) 按鈕。

1. (選用) 展開 **Target type** (目標類型) 區段，並選擇目標類型，以定義自動化可執行所在的資源類型。例如，若要在 EC2 執行個體上使用 Runbook，請選擇 `/AWS::EC2::Instance`。
**注意**  
如果您指定 '`/`' 的值，則 Runbook 可以在所有類型的資源上執行。如需有效資源類型的清單，請參閱《*AWS CloudFormation 使用者指南*》 中的 [AWS 資源類型參考](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-template-resource-type-ref.html)。

1. (選用) 展開 **Document tags** (文件標籤) 區段，並輸入要套用至 Runbook 的一或多個標籤鍵值組。標籤可讓您更容易識別、組織和搜尋資源。

1. 在 **Step 1 (步驟 1)** 區段中，提供下列資訊。
   + 對於 **Step name** (步驟名稱)，輸入自動化第一個步驟的描述性名稱。
   + 對於 **Action type (動作類型)**，選取要用於此步驟的動作類型。

     如需可用動作類型的清單和資訊，請參閱[Systems Manager Automation 動作參考](automation-actions.md)。
   + 對於 **Description (描述)**，輸入自動化步驟的描述。您可以使用 Markdown 來將文字格式化。
   + 根據選取的 **Action type (動作類型)**，在 **Step inputs (步驟輸入)** 區段中輸入動作類型的必要輸入。例如，如果您選取動作 `aws:approve`，則必須指定 `Approvers` 屬性的值。

     如需步驟輸入欄位的相關資訊，請參閱 [Systems Manager Automation 動作參考](automation-actions.md) 中您所選動作類型的項目。例如：[`aws:executeStateMachine` – 執行 AWS Step Functions 狀態機器](automation-action-executeStateMachine.md)。
   + (選用) 對於 **Additional inputs** (其他輸入)，提供 Runbook 所需的任何其他輸入值。可用的輸入類型取決於您為步驟選取的動作類型。(請注意，某些動作類型需要輸入值。)
**注意**  
若要新增更多輸入，請選擇 **Add optional input (新增選用輸入)**。若要移除輸入，請選擇 **X** (移除) 按鈕。
   + (選用) 對於 **Outputs** (輸出)，輸入用於此步驟以提供其他處理程序使用的任何輸出。
**注意**  
**Outputs (輸出)** 不適用所有動作類型。
   + (選用) 展開 **Common properties** (一般屬性) 區段，並指定所有 Automation 動作通用的動作屬性。例如，對於 **Timeout seconds** (逾時秒)，您可以以秒為單位提供值，以指定步驟在停止之前可以執行的時間長度。

     如需詳細資訊，請參閱[依所有動作共用的屬性](automation-actions.md#automation-common)。
**注意**  
若要新增更多步驟，請選取 **Add step** (新增步驟)，然後重複建立步驟的程序。若要移除步驟，請選擇 **Remove step** (移除步驟)。

1. 選擇 **Create automation** (建立自動化) 以儲存 Runbook。

## 建立執行指令碼的執行手冊
<a name="create-runbook-scripts"></a>

下列程序顯示如何在 AWS Systems Manager Automation 主控台中使用文件建置器，以建立可執行指令碼的自訂執行手冊。

您建立 Runbook 的第一個步驟會執行指令碼來啟動 Amazon Elastic Compute Cloud (Amazon EC2) 執行個體。第二個步驟會執行另一個指令碼來監控要變更為 `ok` 的執行個體狀態檢查。然後，會報告自動化的 `Success` 整體狀態。

**開始之前**  
請確認您已完成下列步驟：
+ 確認您具有管理員許可，或已獲授與適當的許可，才能存取 AWS Identity and Access Management (IAM) 中的 Systems Manager。

  如需相關資訊，請參閱[驗證 Runbook 的使用者存取權](automation-setup.md#automation-setup-user-access)。
+ 確認您的 AWS 帳戶帳戶中具有用於自動化的 IAM 服務角色 (也稱為*擔任角色*)。此角色是必要的，因為此演練使用 `aws:executeScript` 動作。

  如需建立此角色的詳細資訊，請參閱[設定自動化的服務角色 (擔任角色) 存取權](automation-setup.md#automation-setup-configure-role)。

  如需執行 `aws:executeScript` 之 IAM 服務角色需求的相關資訊，請參閱 [使用 Runbook 的許可](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. 在 https：//[https://console.aws.amazon.com/systems-manager/](https://console.aws.amazon.com/systems-manager/) 開啟 AWS Systems Manager 主控台。

1. 在導覽窗格中，選擇 **Documents (文件)**。

1. 選擇 **Create automation (建立自動化)**。

1. 對於 **Name** (名稱)，輸入 Runbook 的描述性名稱：**LaunchInstanceAndCheckStatus**。

1. (選用) 對於 **Document description** (文件描述)，使用 Markdown，以此 Runbook 的描述取代預設文字。下列是 範例。

   ```
   ##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** (擔任角色)，輸入對於自動化執行，用於自動化 (擔任角色) 的 IAM 服務角色的 ARN，格式為 **arn:aws:iam::111122223333:role/AutomationServiceRole**。將您的 AWS 帳戶 ID 替換為 111122223333。

   您指定的角色是用來提供開始自動化所需的許可。
**重要**  
對於使用 `aws:executeScript` 動作的非 Amazon 擁有的 Runbook，必須指定角色。如需相關資訊，請參閱[使用 Runbook 的許可](automation-document-script-considerations.md#script-permissions)。

1. 展開 **Input parameters (輸入參數)**，然後執行下列動作。

   1. 對於 **Parameter name (參數名稱)**，輸入 **imageId**。

   1. 針對 **Type (類型)**，選擇 **String**。

   1. 對於 **Required (必要)**，選擇 `No`。

   1. 對於 **Default value (預設值)**，輸入以下內容。

      ```
      {{ 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. 對於 **Description (描述)**，輸入以下內容。

      ```
      (Optional) The AMI ID to use for launching the instance. The default value uses the latest released Amazon Linux 2023 AMI ID.
      ```

1. 選擇 **Add a parameter (新增參數)** 來建立第二個參數 **tagValue**，然後輸入下列資訊。

   1. 對於 **Parameter name (參數名稱)**，輸入 **tagValue**。

   1. 針對 **Type (類型)**，選擇 **String**。

   1. 對於 **Required (必要)**，選擇 `No`。

   1. 對於 **Default value (預設值)**，輸入 **LaunchedBySsmAutomation**。這會將標籤金鑰對值 `Name:LaunchedBySsmAutomation` 新增至該執行個體。

   1. 對於 **Description (描述)**，輸入以下內容。

      ```
      (Optional) The tag value to add to the instance. The default value is LaunchedBySsmAutomation.
      ```

1. 選擇 **Add a parameter (新增參數)** 來建立第三個參數 **instanceType**，然後輸入下列資訊。

   1. 對於 **Parameter name (參數名稱)**，輸入 **instanceType**。

   1. 針對 **Type (類型)**，選擇 **String**。

   1. 對於 **Required (必要)**，選擇 `No`。

   1. 對於 **Default value (預設值)**，輸入 **t2.micro**。

   1. 對於 **Parameter Description (參數描述)**，輸入以下內容。

      ```
      (Optional) The instance type to use for the instance. The default value is t2.micro.
      ```

1. 展開 **Target type (目標類型)**，並選擇 **"/"**。

1. (選用) 展開 **Document tags** (文件標籤)，將資源標籤套用至您的 Runbook。對於 **Tag key (標籤鍵)**，輸入 **Purpose**，以及對於 **Tag value (標籤值)**，輸入 **LaunchInstanceAndCheckState**。

1. 在 **Step 1 (步驟 1)** 區段中，完成下列步驟。

   1. 對於 **Step name** (步驟名稱)，輸入自動化第一個步驟的此描述性步驟名稱：**LaunchEc2Instance**。

   1. 對於 **Action type (動作類型)**，選擇 **Run a script (執行指令碼)** (**aws:executeScript**)。

   1. 對於 **Description (描述)**，輸入自動化步驟的描述，如下所示。

      ```
      **About This Step**
          
          This step first launches an EC2 instance using the ```aws:executeScript``` action and the provided script.
      ```

   1. 展開 **Inputs (輸入)**。

   1. 對於 **Runtime (執行時間)**，選擇用於執行所提供指令碼的執行時間語言。

   1. 對於 **Handler (處理常式)**，輸入 **launch\$1instance**。這是在以下指令碼中宣告的函數名稱。
**注意**  
PowerShell 不需要用到。

   1. 對於 **Script (指令碼)**，請以下列項目取代預設內容。請務必將指令碼與對應的執行時間值相符。

------
#### [ 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. 展開 **Outputs (輸出)**，並執行下列動作：
   + 對於**名稱**，輸入 **payload**。
   + 對於 **Selector (選取器)**，輸入 **\$1.Payload**。
   + 針對 **Type (類型)**，選擇 `StringMap`。

1. 選擇 **Add step** (新增步驟)，將第二個步驟新增至 Runbook。第二個步驟會查詢在步驟 1 中啟動的執行個體狀態，並等候傳回的狀態為 `ok` 為止。

1. 在 **Step 2 (步驟 2)** 區段中，執行下列動作。

   1. 對於 **Step name** (步驟名稱)，輸入自動化第二個步驟的此描述性名稱：**WaitForInstanceStatusOk**。

   1. 對於 **Action type (動作類型)**，選擇 **Run a script (執行指令碼)** (**aws:executeScript**)。

   1. 對於 **Description (描述)**，輸入自動化步驟的描述，如下所示。

      ```
      **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. 對於 **Runtime (執行時間)**，選擇用於執行所提供指令碼的執行時間語言。

   1. 對於 **Handler (處理常式)**，輸入 **poll\$1instance**。這是在以下指令碼中宣告的函數名稱。
**注意**  
PowerShell 不需要用到。

   1. 對於 **Script (指令碼)**，請以下列項目取代預設內容。請務必將指令碼與對應的執行時間值相符。

------
#### [ 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** (建立自動化) 以儲存 Runbook。

# 在執行手冊中使用指令碼
<a name="automation-document-script-considerations"></a>

自動化 Runbook 支援在自動化時執行指令碼。Automation 是 AWS Systems Manager中的工具。透過使用 Runbook，您可以直接在 AWS 中執行指令碼，而無需建立個別的運算環境來執行指令碼。因為 Runbooks 可以與其他自動化步驟類型 (例如核准) 一起執行指令碼步驟，所以您可在嚴重或不明確的情況下手動介入。您可以從 Runbook 中的 `aws:executeScript` 動作傳送輸出到 Amazon CloudWatch Logs。如需詳細資訊，請參閱[使用 CloudWatch Logs 記錄自動化動作輸出](automation-action-logging.md)。

## 使用 Runbook 的許可
<a name="script-permissions"></a>

若要使用 Runbook，Systems Manager 必須使用 AWS Identity and Access Management (IAM) 角色的許可。自動化用來判斷要使用角色的許可的方法取決於幾個因素，以及步驟是否使用 `aws:executeScript` 動作。

對於不使用 `aws:executeScript` 的 Runbook，Automation 會使用兩個許可來源的其中一個：
+ Runbook 中指定或作為參數傳入的 IAM 服務角色或擔任角色的許可。
+ 如果未指定 IAM 服務角色，則為啟動自動化執行之使用者的許可。

不過，當 Runbook 中的步驟包含 `aws:executeScript`動作時，如果為動作指定的 Python 或 PowerShell 指令碼正在呼叫任何 AWS API 操作，則一律需要 IAM 服務角色 （擔任角色）。自動化會以下列順序檢查此角色：
+ Runbook 中指定或作為參數傳入的 IAM 服務角色或擔任角色的許可。
+ 如果找不到任何角色，自動化會嘗試執行為 `aws:executeScript` 指定的 Python 或 PowerShell 指令碼，而不使用任何許可。如果指令碼呼叫 AWS API 操作 （例如 Amazon EC2 `CreateImage`操作），或嘗試對 AWS 資源 （例如 EC2 執行個體） 採取行動，則包含指令碼的步驟會失敗，Systems Manager 會傳回報告失敗的錯誤訊息。

## 將指令碼新增至 Runbook
<a name="adding-scripts"></a>

您可以在 Runbook 中將指令碼內嵌做為步驟的一部分，將指令碼新增至 Runbook。您也可以從本機機器上傳指令碼或指定指令碼所在的 Amazon Simple Storage Service (Amazon S3) 儲存貯體，將指令碼連接至 Runbook。執行指令碼的步驟完成後，指令碼的輸出會以 JSON 物件的形式提供，然後您可以將該輸出做為 Runbook 中後續步驟的輸入。如需有關 `aws:executeScript` 動作及如何使用指令碼附件的詳細資訊，請參閱 [`aws:executeScript` – 執行指令碼](automation-action-executeScript.md)。

## Runbook 的指令碼限制
<a name="script-constraints"></a>

Runbook 會強制執行五個檔案附件的限制。指令碼可以使用 Python 指令碼 (.py) 的形式、PowerShell Core 指令碼 (.ps1)，或附加為 .zip 檔案中的內容。

# 在執行手冊中使用條件陳述式
<a name="automation-branch-condition"></a>

根據預設，您在 Runbook 之 `mainSteps` 區段中定義的步驟會循序執行。一個動作完成後，`mainSteps` 區段中指定的下一個動作就會開始。此外，如果動作無法執行，整個自動化就會失敗 (根據預設)。您可以使用本節說明的 `aws:branch` 自動化動作和 Runbook 選項建立執行*條件式分支*的自動化。這表示您可以建立自動化以在評估不同選擇後跳至不同的步驟，或是在步驟完成時動態回應變更。以下是您可以用來建立動態自動化的選項清單：
+ **`aws:branch`**：動作可讓您建立動態自動化，以評估單一步驟中的多個選擇，接著根據該評估的結果跳至 Runbook 中的不同步驟。
+ **`nextStep`**：此選項會指定在成功完成步驟後要接著處理自動化中的哪個步驟。
+ **`isEnd`**：此選項會在特定步驟結束時停止自動化執行。此選項的預設值為 false。
+ **`isCritical`**：此選項會指定某個步驟是成功完成自動化的關鍵。如果此指定步驟失敗，則自動化會將自動化的最終狀態回報為 `Failed`。此選項的預設值為 `true`。
+ **`onFailure`**：此選項指示自動化在失敗時應中止、繼續或前往不同的步驟。此選項的預設值為 abort。

以下部分說明 `aws:branch` 自動化動作。如需 `nextStep`、`isEnd`、`isCritical` 和 `onFailure` 選項的詳細資訊，請參閱 [範例 `aws:branch` Runbook](#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`。自動化可以根據您在 Runbook `Parameters` 區段中指定的參數值評估 `Choices`。自動化也可以根據前一個步驟的輸出評估 `Choices`。

自動化會使用布林值表達式評估每個選擇。如果評估判斷第一個選擇為 `true`，則自動化會跳至為該選擇指定的步驟。如果第一個選擇的評估判斷是 `false`，則自動化會評估下一個選擇。如果您的步驟包括三個或更多 `Choices`，則工作流程會循序評估每個選擇，直到評估某個選擇是 `true` 為止。接著自動化會跳至選擇為 `true` 的指定步驟。

如果 `Choices` 均不為 `true`，則自動化會檢查步驟是否包含 `Default` 值。如果沒有選擇為 `true`，則 `Default` 值會定義自動化應跳至的步驟。如果未針對步驟指定 `Default` 值，則自動化會處理 Runbook 中的下一個步驟。

以下是 YAML 中的 `aws:branch` 步驟，名稱為 **chooseOSfromParameter**。步驟包含兩個 `Choices`：(`NextStep: runWindowsCommand`) 和 (`NextStep: runLinuxCommand`)。自動化會評估這些 `Choices`，決定要針對適當的作業系統執行什麼命令。每個選擇的 `Variable` 會使用 `{{OSName}}`，此為 Runbook 撰寫者在 Runbook `Parameters` 區段中定義的參數。

```
mainSteps:
- name: chooseOSfromParameter
  action: aws:branch
  inputs:
    Choices:
    - NextStep: runWindowsCommand
      Variable: "{{OSName}}"
      StringEquals: Windows
    - NextStep: runLinuxCommand
      Variable: "{{OSName}}"
      StringEquals: Linux
```

以下是 YAML 中的 `aws:branch` 步驟，名稱為 **chooseOSfromOutput**。步驟包含兩個 `Choices`：(`NextStep: runPowerShellCommand`) 和 (`NextStep: runShellCommand`)。自動化會評估這些 `Choices`，決定要針對適當的作業系統執行什麼命令。每個選擇的 `Variable` 會使用 `{{GetInstance.platform}}`，也就是 Runbook 中先前步驟的輸出。此範例也包含一個名稱為 `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
```

### 在 Runbook 中建立 `aws:branch` 步驟
<a name="create-branch-action"></a>

當您在 Runbook 中建立 `aws:branch` 步驟，您要定義應由自動化評估的 `Choices`，以決定自動化接下來應跳至哪個步驟。如前所述，`Choices` 是使用布林值運算式評估。每個選擇都必須定義以下選項：
+ **NextStep**：如果指定選擇為 `true`，在 Runbook 中要處理的下一個步驟。
+ **變數**：指定執行手冊 `Parameters` 區段中定義的參數名稱、`Variables` 區段中定義的變數，或指定上一步的輸出物件。

  使用以下格式指定變數值。

  `Variable: "{{variable name}}"`

  使用以下格式指定參數值。

  `Variable: "{{parameter name}}"`

  使用以下格式指定輸出物件變數。

  `Variable: "{{previousStepName.outputName}}"`
**注意**  
有關建立輸出變數的詳細資訊，請參閱下一節 [關於建立輸出變數](#branch-action-output)。
+ **Operation**：用於評估選擇的條件，例如 `StringEquals: Linux`。`aws:branch` 動作支援以下運算：

**字串運算**
  + StringEquals
  + EqualsIgnoreCase
  + StartsWith
  + EndsWith
  + Contains

**數值運算**
  + NumericEquals
  + NumericGreater
  + NumericLesser
  + NumericGreaterOrEquals
  + NumericLesser
  + NumericLesserOrEquals

**布林運算**
  + BooleanEquals
**重要**  
當您建立 Runbook 時，系統會驗證 Runbook 中的每個操作。如果不支援操作，系統會在您嘗試建立 Runbook 時傳回錯誤。
+ **Default**：指定 `Choices` 均不為 `true` 時，自動化應跳至的遞補步驟。
**注意**  
如果不想指定 `Default` 值，您可以指定 `isEnd` 選項。如果 `Choices` 均不為 `true`，而 `Default` 值也未指定，則自動化會在步驟結束時停止。

使用以下範本協助您在 Runbook 中建構 `aws:branch` 步驟：將每個*範例資源預留位置*取代為您自己的資訊。

------
#### [ 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`) 中，撰寫者想要參考 platform 欄位的輸出做為變數。若要建立變數，只需結合步驟名稱 (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` Runbook
<a name="branch-runbook-examples"></a>

以下是一些使用 `aws:branch` 的範例 Runbook。

**範例 1：使用 `aws:branch` 搭配輸出變數以根據作業系統類型執行命令**

在此範例 (`GetInstance`) 的第一個步驟，Runbook 撰寫人使用 `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` 搭配參數變數以根據作業系統類型執行命令**

Runbook 撰寫者在 Runbook 開頭的 `parameters` 區段定義了數個參數選項。其中一個參數名稱為 `OperatingSystemName`。在第一個步驟中 (`ChooseOS`)，撰寫者使用 `aws:branch` 動作搭配兩個 `Choices` (`NextStep: runWindowsCommand`) 和 (`NextStep: runLinuxCommand`)。這些 `Choices` 的變數會參考在參數區段中指定的參數選項 (`Variable: "{{OperatingSystemName}}"`)。使用者執行此 Runbook 時，針對 `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>

本節包括不同的範例，示範如何在 Runbook 中使用動態選項。本節中每個範例都會延伸以下的 Runbook。此 Runbook 有兩個動作。第一種動作名稱為 `InstallMsiPackage`。它會使用 `aws:runCommand` 動作在 Windows Server 執行個體上安裝應用程式。第二個動作名稱為 `TestInstall`。這會使用 `aws:invokeLambdaFunction` 動作對安裝的應用程式執行測試，確認應用程式是否安裝成功。步驟一指定 `onFailure: Abort`。這表示如果應用程式未安裝成功，自動化就在步驟二前停止。

**範例 1：具有兩個線性動作的 Runbook**

```
---
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
...
```

**注意**  
在處理 Runbook 之前，系統會驗證 Runbook 是否不會建立無限迴圈。如果偵測到無限迴圈，自動化會傳回錯誤和圓形追蹤，顯示建立迴圈的步驟。

**建立定義關鍵步驟的動態自動化**

您可以將一個步驟指定為自動化整體成功的關鍵。如果關鍵步驟失敗，即使有一個或多個步驟已執行成功，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}}` 格式執行手冊中的後續步驟。您還可以在執行手冊中定義自動化動作的自訂輸出。這可讓您執行指令碼，或叫用其他 的 API 操作 AWS 服務 一次，以便在稍後的動作中重複使用這些值作為輸入。執行手冊中的參數類型是靜態的。這意味著參數類型在定義後便無法變更。若要定義步驟輸出，請提供下列欄位：
+ 名稱：(必填) 用於在後面的步驟中引用輸出值的輸出名稱。
+ 選取器：(必填) 用於決定輸出值的 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` 動作呼叫 Amazon EC2 DescribeImages API 操作，以獲得特定 Windows Server 2016 AMI 的名稱。這會將映像 ID 輸出為 `ImageId`。
+ 使用 `aws:executeAwsApi` 動作呼叫 Amazon EC2 RunInstances API 操作，以啟動使用先前步驟之 `ImageId` 的執行個體。這會將執行個體 ID 輸出為 `InstanceId`。
+ 使用 ` aws:waitForAwsResourceProperty` 動作輪詢 Amazon EC2 DescribeInstanceStatus API 操作，以等待執行個體達到 `running` 狀態。動作在 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 操作定義。您可以檢視 API 操作 (也稱為方法)，方式是在以下[服務參考](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/index.html)頁面的左側導覽中選擇一項服務。在您想要呼叫之服務的 **Client (用戶端)** 部分選擇一個方法。例如，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 自動化支援的 JSONPath 運算子相關資訊：
+ **以點標記的子代 (.)**：與 JSON 物件搭配使用。此運算子會選取特定索引鍵的值。
+ **Deep-scan (..)**：與 JSON 元素搭配使用。此運算子會在各層級掃描 JSON 元素並選取具有特定索引鍵之值的清單。此運算子的傳回類型一律為 JSON 陣列。在自動化動作輸出類型的內容中，運算子可以是 StringList 或 MapList。
+ **Array-Index ([ ])**：與 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 Example 4：深度掃描 JSON 回應，接著取得做為 StringList 的 VolumeId 所有值** 

```
JSONPath:
$.Reservations..BlockDeviceMappings..VolumeId
        
Returns:
[
   "vol-000000000000",
   "vol-111111111111"
]

Type: StringList
```

**JSONPath 範例 5：取得做為 StringMap 的特定 BlockDeviceMappings 物件**

```
JSONPath:
$.Reservations[0].Instances[0].BlockDeviceMappings[0]
        
Returns:
{
   "Ebs" : {
      "DeleteOnTermination" : true,
      "Status" : "attached",
      "VolumeId" : "vol-000000000000"
   },
   "DeviceName" : "/dev/xvda"
}

Type: StringMap
```

**JSONPath Example 6：深度掃描 JSON 回應，接著取得做為 MapList 的所有 State 物件**

```
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 建立 Webhook 整合
<a name="creating-webhook-integrations"></a>

若要在自動化過程中使用 Webhook 傳送訊息，請建立整合。在自動化過程中，您可以使用 Runbook 中的 `aws:invokeWebhook` 動作來叫用整合。若尚未建立 Webhook，請參閱 [為整合建立 Webhook](#creating-webhooks)。若要進一步了解 `aws:invokeWebhook` 動作，請參閱 [`aws:invokeWebhook`：叫用 Automation Webhook 整合](invoke-webhook.md)。

如以下程序所示，您可以使用 Systems Manager Automation 主控台或偏好的命令列工具來建立整合。

## 建立整合 (主控台)
<a name="creating-integrations-console"></a>

**建立 Automation 整合 (主控台)**

1. 在 https：//[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 使用 Parameter Store (Systems Manager 中的工具) 中的保留命名空間來存放與整合相關的資訊。如果您使用 建立整合 AWS 管理主控台，自動化會為您處理此程序。在命名空間之後，您必須指定要建立的整合類型，然後指定整合的名稱。Automation 目前支援 `webhook` 類型整合。

`webhook` 類型整合的支援欄位如下所示：
+ Description
+ 標頭
+ 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` 參數。將每個*範例資源預留位置*取代為您自己的資訊。`/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"}'
  ```

------

## 為整合建立 Webhook
<a name="creating-webhooks"></a>

借助提供商建立 Webhook 時，請注意下列事項：
+ 通訊協定必須是 HTTPS。
+ 支援自訂請求標頭。
+ 可以指定預設請求主體。
+ 使用 `aws:invokeWebhook` 動作叫用整合時，可以覆寫預設請求主體。

# 處理 Runbook 中的逾時
<a name="automation-handling-timeouts"></a>

`timeoutSeconds` 屬性由所有自動化動作共用。您可以使用此屬性來指定動作的執行逾時值。此外，您還可以變更動作逾時影響自動化和整體執行狀態的方式。您也可以定義動作的 `onFailure` 和 `isCritical` 共用屬性來這樣做。

例如，視您的使用案例而定，您可能希望自動化繼續執行不同的動作，而且在動作逾時時不影響自動化的整體狀態。在此範例中，您可以使用 `timeoutSeconds` 屬性指定動作逾時之前要等待的時間長度。接著指定如果逾時，自動化應該採取的動作或步驟。使用 `step:step name` 格式指定 `onFailure` 屬性的值，來取代 `Abort` 的預設值。預設情況下，如果動作逾時，自動化的執行狀態將是 `Timed Out`。若要避免逾時影響自動化執行狀態，請為 `isCritical` 屬性指定 `false`。

下列範例顯示如何定義此案例中所述動作的共用屬性。

------
#### [ 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 Runbook Reference
<a name="automation-documents-reference"></a>

為了協助您快速入門， AWS Systems Manager 提供預先定義的 Runbook。這些 Runbook 由 Amazon Web Services AWS 支援和 維護 AWS Config。Runbook 參考說明 Systems Manager 提供的每個預先定義的 Runbook 支援，以及 AWS Config。如需詳細資訊，請參閱 [Systems Manager Automation Runbook Reference](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)
  + [更新 LinuxAMI (AWS CLI)](automation-tutorial-update-ami.md#update-patch-linux-ami-cli)
  + [更新 Windows Server (AMI)](automation-tutorial-update-patch-windows-ami.md)
  + [AMI 使用自動化更新黃金 AWS Lambda，以及 Parameter Store](automation-tutorial-update-patch-golden-ami.md)
    + [任務 1：建立 Systems Manager Parameter Store 參數](automation-tutorial-update-patch-golden-ami.md#create-parameter-ami)
    + [任務 2：建立 的 IAM 角色 AWS Lambda](automation-tutorial-update-patch-golden-ami.md#create-lambda-role)
    + [任務 3：建立 AWS Lambda 函數](automation-tutorial-update-patch-golden-ami.md#create-lambda-function)
    + [任務 4：建立 Runbook 並修補 AMI](automation-tutorial-update-patch-golden-ami.md#create-custom-ami-update-runbook)
  + [使用 Automation 和 Jenkins 更新 AMIs](automation-tutorial-update-patch-ami-jenkins-integration.md)
  + [更新 Auto Scaling 群組的 AMIs](automation-tutorial-update-patch-windows-ami-autoscaling.md)
    + [建立 **PatchAMIAndUpdateASG** Runbook](automation-tutorial-update-patch-windows-ami-autoscaling.md#create-autoscaling-update-runbook)
+ [使用 AWS 支援 自助式 Runbook](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)
+ [更新 LinuxAMI (AWS CLI)](#update-patch-linux-ami-cli)
+ [更新 Windows Server (AMI)](automation-tutorial-update-patch-windows-ami.md)
+ [AMI 使用自動化更新黃金 AWS Lambda，以及 Parameter Store](automation-tutorial-update-patch-golden-ami.md)
+ [使用 Automation 和 Jenkins 更新 AMIs](automation-tutorial-update-patch-ami-jenkins-integration.md)
+ [更新 Auto Scaling 群組的 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` Runbook 也會自動化安裝其他的網站特定套件和組態。您可以使用此演練更新各種 Linux 發行版本，包括 Ubuntu Server、Red Hat Enterprise Linux (RHEL) 或 Amazon Linux AMIs。如需支援的 Linux 版本完整清單，請參閱 [Patch Manager 先決條件](patch-manager-prerequisites.md)。

`AWS-UpdateLinuxAmi` 執行手冊可讓您自動化映像維護任務，而無需撰寫 JSON 或 YAML 格式的執行手冊。您可以使用 `AWS-UpdateLinuxAmi` Runbook 執行以下類型的任務。
+ 在 Amazon Linux、Red Hat Enterprise Linux 或 Ubuntu Server Amazon Machine Image (AMI) 上，升級所有發行版本套件和 Amazon 軟體。這是 Runbook 預設行為。
+ 在 AWS Systems Manager SSM Agent現有映像上安裝 以啟用 Systems Manager 工具，例如使用 AWS Systems Manager Run Command 執行遠端命令或使用庫存執行軟體庫存收集。
+ 安裝其他軟體套件。

**開始之前**  
在您開始使用 Runbook 之前，請設定 Automation 的角色和 EventBridge (選用)。如需詳細資訊，請參閱[設定自動化](automation-setup.md)。此演練也需要您指定 AWS Identity and Access Management (IAM) 執行個體描述檔的名稱。如需有關建立 IAM 執行個體設定檔的詳細資訊，請參閱[設定 Systems Manager 所需的執行個體許可](setup-instance-permissions.md)。

`AWS-UpdateLinuxAmi` Runbook 接受以下的輸入參數。


****  

| 參數 | 類型 | 說明 | 
| --- | --- | --- | 
|  SourceAmiId  |  String  |  (必要) 來源 AMI ID。  | 
|  IamInstanceProfileName  |  String  |  (必要) 您在[設定 Systems Manager 所需的執行個體許可](setup-instance-permissions.md)中所建立之 IAM 執行個體設定檔角色的名稱。執行個體設定檔角色可讓自動化許可在您的執行個體上執行動作，例如執行命令或啟動和停用服務。Runbook 僅使用執行個體設定檔角色的名稱。如果您指定 Amazon Resource Name (ARN)，自動化會失敗。  | 
|  AutomationAssumeRole  |  String  |  (必要) 您在 [設定自動化](automation-setup.md) 中建立之 IAM 服務角色的名稱。服務角色 (也稱為擔任角色) 會提供自動化許可來擔任您的 IAM 角色並代表您執行動作。例如，在 Runbook 中執行 `aws:createImage` 動作時，服務角色會允許自動化建立新的 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` Runbook 包含下列自動化動作。

**步驟 1：launchInstance (`aws:runInstances` 動作) **  
此步驟使用 Amazon Elastic Compute Cloud (Amazon EC2) 使用者資料和 IAM 執行個體設定檔角色啟動執行個體。Userdata 會根據作業系統安裝合適的 SSM Agent 代理程式。安裝 SSM Agent 後，您可以利用 Systems Manager 的各種工具，例如 Run Command、State 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。例如：「AMI Generated by EC2 Automation on \$1\$1global:DATE\$1TIME\$1\$1 from \$1\$1SourceAmiId\$1\$1」，其中 DATE\$1TIME 和 SourceID 代表自動化變數。

**步驟 5：terminateInstance (`aws:changeInstanceState` 動作) **  
此步驟會藉由終止執行中的執行個體來清除自動化。

**Output**  
自動化會傳回新的 AMI ID 作為輸出。

**注意**  
根據預設，Automation 執行 `AWS-UpdateLinuxAmi` Runbook 時，系統在預設 VPC (172.30.0.0/16) 中建立暫時執行個體。如果刪除預設 VPC，您會收到以下錯誤：  
`VPC not defined 400`  
若要解決此問題，您必須複製 `AWS-UpdateLinuxAmi` Runbook 並指定子網路 ID。如需詳細資訊，請參閱[VPC 未定義 400](automation-troubleshooting.md#automation-trbl-common-vpc)。

**使用 Automation (AWS Systems Manager) 建立已修補的 AMI**

1. 在 https：//[https://console.aws.amazon.com/systems-manager/](https://console.aws.amazon.com/systems-manager/) 開啟 AWS Systems Manager 主控台。

1. 在導覽窗格中，選擇 **Automation** (自動化)。

1. 選擇 **Execute automation (執行自動化)**。

1. 在 **Automation document** (自動化文件) 清單中，選擇 `AWS-UpdateLinuxAmi`。

1. 在 **Document details (文件詳細資訊)** 部分，確認 **Document version (文件版本)** 設為 **Default version at runtime (執行時間的預設版本)**。

1. 選擇**下一步**。

1. 在 **Execution Mode (執行模式)** 部分，選擇 **Simple execution (簡易執行)**。

1. 在 **Input parameters** (輸入參數) 部分，輸入您在 **Before You Begin** (開始之前) 部分收集的資訊。

1. 選擇 **Execute (執行)**。主控台會顯示自動化執行的狀態。

自動化結束後，從已更新的 AMI 啟動測試執行個體以確認變更。

**注意**  
如果自動化中有任何步驟失敗，關於失敗的資訊會列於 **Automation Executions** (自動化執行清單) 頁面。自動化設計為在成功完成所有任務後終止暫時執行個體。如果有步驟失敗，系統可能不會終止執行個體。所以如果有步驟失敗，請手動終止暫時執行個體。

## 更新 LinuxAMI (AWS CLI)
<a name="update-patch-linux-ami-cli"></a>

此 AWS Systems Manager 自動化演練說明如何使用 AWS Command Line Interface (AWS CLI) 和 Systems Manager `AWS-UpdateLinuxAmi` 執行手冊，以您指定的最新版本套件自動修補 Linux Amazon Machine Image(AMI)。Automation 是 AWS Systems Manager中的工具。`AWS-UpdateLinuxAmi` Runbook 也會自動化安裝其他的網站特定套件和組態。您可以使用此演練更新各種 Linux 發行版本，包括 Ubuntu Server、Red Hat Enterprise Linux (RHEL) 或 Amazon Linux AMIs。如需支援的 Linux 版本完整清單，請參閱 [Patch Manager 先決條件](patch-manager-prerequisites.md)。

`AWS-UpdateLinuxAmi` Runbook 可讓您自動化映像維護任務，不必使用 JSON 或 YAML 撰寫 Runbook。您可以使用 `AWS-UpdateLinuxAmi` Runbook 執行以下類型的任務。
+ 在 Amazon Linux、RHEL 或 Ubuntu Server Amazon Machine Image (AMI) 上，升級所有發行版本套件和 Amazon 軟體。這是 Runbook 預設行為。
+ 在 AWS Systems Manager SSM Agent現有映像上安裝 以啟用 Systems Manager 功能，例如使用 AWS Systems Manager Run Command 執行遠端命令或使用庫存執行軟體庫存收集。
+ 安裝其他軟體套件。

**開始之前**  
在您開始使用 Runbook 之前，請設定 Automation 的角色和 EventBridge (選用)。如需詳細資訊，請參閱[設定自動化](automation-setup.md)。此演練也需要您指定 AWS Identity and Access Management (IAM) 執行個體描述檔的名稱。如需有關建立 IAM 執行個體設定檔的詳細資訊，請參閱[設定 Systems Manager 所需的執行個體許可](setup-instance-permissions.md)。

`AWS-UpdateLinuxAmi` Runbook 接受以下的輸入參數。


****  

| 參數 | 類型 | 說明 | 
| --- | --- | --- | 
|  SourceAmiId  |  String  |  (必要) 來源 AMI ID。您可以使用*公*有 AWS Systems Manager Parameter Store參數自動參考 Amazon EC2 AMI for Linux 的最新 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 執行個體設定檔角色的名稱。執行個體設定檔角色可讓自動化許可在您的執行個體上執行動作，例如執行命令或啟動和停用服務。Runbook 僅使用執行個體設定檔角色的名稱。  | 
|  AutomationAssumeRole  |  String  |  (必要) 您在 [設定自動化](automation-setup.md) 中建立之 IAM 服務角色的名稱。服務角色 (也稱為擔任角色) 會提供自動化許可來擔任您的 IAM 角色並代表您執行動作。例如，在 Runbook 中執行 `aws:createImage` 動作時，服務角色會允許自動化建立新的 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` Runbook 包含下列步驟。

**步驟 1：launchInstance (`aws:runInstances` 動作) **  
此步驟使用 Amazon Elastic Compute Cloud (Amazon EC2) 使用者資料和 IAM 執行個體設定檔角色啟動執行個體。使用者資料會根據作業系統安裝合適的 SSM Agent。安裝 SSM Agent 後，您可以利用 Systems Manager 的各種工具，例如 Run Command、State 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。例如：「AMI Generated by EC2 Automation on \$1\$1global:DATE\$1TIME\$1\$1 from \$1\$1SourceAmiId\$1\$1」，其中 DATE\$1TIME 和 SourceID 代表自動化變數。

**步驟 5：terminateInstance (`aws:changeInstanceState` 動作) **  
此步驟會藉由終止執行中的執行個體來清除自動化。

**輸出**  
自動化會傳回新的 AMI ID 作為輸出。

**注意**  
根據預設，Automation 執行 `AWS-UpdateLinuxAmi` Runbook 時，系統在預設 VPC (172.30.0.0/16) 中建立暫時執行個體。如果刪除預設 VPC，您會收到以下錯誤：  
`VPC not defined 400`  
若要解決此問題，您必須複製 `AWS-UpdateLinuxAmi` Runbook 並指定子網路 ID。如需詳細資訊，請參閱[VPC 未定義 400](automation-troubleshooting.md#automation-trbl-common-vpc)。

**使用 自動化 建立已修補的 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` Runbook。將每個*範例資源預留位置*取代為您自己的資訊。

   ```
   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 Executions** (自動化執行清單) 頁面。自動化設計為在成功完成所有任務後終止暫時執行個體。如果有步驟失敗，系統可能不會終止執行個體。所以如果有步驟失敗，請手動終止暫時執行個體。

# 更新 Windows Server (AMI)
<a name="automation-tutorial-update-patch-windows-ami"></a>

`AWS-UpdateWindowsAmi` Runbook 可讓您自動化 Amazon Windows Amazon Machine Image (AMI) 的映像維護任務，不必使用 JSON 或 YAML 撰寫 Runbook。此 Runbook 支援 Windows Server 2008 R2 或更新版本。您可以使用 `AWS-UpdateWindowsAmi` Runbook 執行以下類型的任務。
+ 安裝所有 Windows 更新和升級 Amazon 軟體 (預設行為)。
+ 安裝特定 Windows 更新和升級 Amazon 軟體。
+ 使用您的指令碼自訂 AMI。

**開始之前**  
在您開始使用 Runbook 之前，[設定 Automation 的角色](automation-setup-iam.md)以新增 `iam:PassRole` 政策，此政策會參考您想要授予存取之執行個體設定檔的 ARN。(選用) 為 Automation ( AWS Systems Manager中的工具) 設定 Amazon EventBridge。如需詳細資訊，請參閱[設定自動化](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` Runbook 接受以下的輸入參數。


****  

| 參數 | 類型 | 說明 | 
| --- | --- | --- | 
|  SourceAmiId  |  String  |  (必要) 來源 AMI ID。您可以使用 Systems Manager Parameter Store *公有*參數自動參考最新的 Windows Server AMI ID。如需詳細資訊，請參閱[使用 AWS Systems Manager查詢最新的 Windows AMI ID Parameter Store](https://aws.amazon.com/blogs/mt/query-for-the-latest-windows-ami-using-systems-manager-parameter-store/)。  | 
|  SubnetId  |  String  |  (選用) 您要啟動暫時執行個體的子網路。如果您已刪除預設 VPC，則必須為此參數指定一個值。  | 
|  IamInstanceProfileName  |  String  |  (必要) 您在[設定 Systems Manager 所需的執行個體許可](setup-instance-permissions.md)中所建立之 IAM 執行個體設定檔角色的名稱。執行個體設定檔角色可讓自動化許可在您的執行個體上執行動作，例如執行命令或啟動和停用服務。Runbook 僅使用執行個體設定檔角色的名稱。  | 
|  AutomationAssumeRole  |  String  |  (必要) 您在 [設定自動化](automation-setup.md) 中建立之 IAM 服務角色的名稱。服務角色 (也稱為擔任角色) 會提供自動化許可來擔任您的 IAM 角色並代表您執行動作。例如，在 Runbook 中執行 `aws:createImage` 動作時，服務角色會允許自動化建立新的 AMI。針對此參數，必須指定的完整 ARN。  | 
|  TargetAmiName  |  String  |  (選用) 建立後的新 AMI 之名稱。預設名稱為系統產生的字串，包括來源 AMI ID，以及建立時間和日期。  | 
|  InstanceType  |  String  |  (選用) 作為工作空間主機啟動的執行個體類型。執行個體類型因區域而異。預設類型為 t2.medium。  | 
|  PreUpdateScript  |  String  |  (選用) 更新 AMI 之前執行的指令碼。在 Runbook 中或在執行時間輸入指令碼作為參數。  | 
|  PostUpdateScript  |  String  |  (選用) 更新 AMI 之後執行的指令碼。在 Runbook 中或在執行時間輸入指令碼作為參數。  | 
|  IncludeKbs  |  String  |  (選用) 指定一個或多個要包含的 Microsoft 知識庫 (KB) 文章 ID。您可以使用逗號分隔值安裝多個 ID。有效格式：KB9876543 或 9876543。  | 
|  ExcludeKbs  |  String  |  (選用) 指定一個或多個要排除的 Microsoft 知識庫 (KB) 文章 ID。您可以使用逗號分隔值排除多個 ID。有效格式：KB9876543 或 9876543。  | 
|  類別  |  String  |  (選用) 指定一個或多個更新類別。您可以使用逗號分隔值篩選類別。選項：Critical Update (重大更新)，Security Update (安全性更新)，Definition Update (定義更新)，Update Rollup (更新彙總套件)，Service Pack，Tool (工具)，Update (更新)，或 Driver (驅動程式)。有效格式包含單一項目，例如：Critical Update (重大更新)。或者您可以指定逗號分隔清單：Critical Update,Security Update,Definition Update。  | 
|  SeverityLevels  |  String  |  (選用) 指定一個或多個與更新關聯的 MSRC 嚴重性等級。您可以使用逗號分隔值篩選嚴重性等級。選項：Critical，Important，Low，Moderate 或 Unspecified。有效格式包括單一項目，例如：Critical。或者，您可以指定逗號分隔清單：Critical，Important，Low。  | 

**自動化步驟**  
依預設，`AWS-UpdateWindowsAmi` Runbook 包含下列步驟。

**步驟 1：launchInstance (`aws:runInstances` 動作)**  
此步驟藉由指定之 `SourceAmiID` 的 IAM 執行個體設定檔角色來啟動執行個體。

**步驟 2：runPreUpdateScript (`aws:runCommand` 動作)**  
此步驟可讓您指定指令碼做為字串，在更新安裝之前執行。

**步驟 3：updateEC2Config (`aws:runCommand` 動作)**  
此步驟使用 `AWS-InstallPowerShellModule` Runbook 下載 AWS 公有 PowerShell 模組。Systems Manager 會使用 SHA-256 雜湊來驗證模組的完整性。接著，Systems Manager 會檢查作業系統，以判斷是否要更新 EC2Config 或 EC2Launch。EC2Config 透過 Windows Server 2012 R2 在 Windows Server 2008 R2 上執行。EC2Launch 在 Windows Server 2016 上執行。

**步驟 4：updateSSMAgent (`aws:runCommand` 動作)**  
此步驟會藉由使用 `AWS-UpdateSSMAgent` Runbook 更新 SSM Agent。

**步驟 5：updateAWSPVDriver (`aws:runCommand` 動作)**  
此步驟會使用 `AWS-ConfigureAWSPackage` Runbook 更新 AWS PV 驅動程式。

**步驟 6：updateAwsEnaNetworkDriver (`aws:runCommand` 動作)**  
此步驟會使用 `AWS-ConfigureAWSPackage` Runbook 更新 AWS ENA Network 驅動程式。

**步驟 7：installWindowsUpdates (`aws:runCommand` 動作) **  
此步驟會藉由使用 `AWS-InstallWindowsUpdates` Runbook 安裝 Windows 更新。根據預設，Systems Manager 會搜尋和安裝所有缺少的更新。您可以藉由指定以下參數變更預設行為：`IncludeKbs`、`ExcludeKbs`、`Categories` 或 `SeverityLevels`。

**步驟 8：runPostUpdateScript (`aws:runCommand` 動作)**  
此步驟可讓您指定指令碼做為字串，在更新安裝之後執行。

**步驟 9：runSysprepGeneralize (`aws:runCommand` 動作) **  
此步驟使用 `AWS-InstallPowerShellModule` Runbook 下載 AWS 公有 PowerShell 模組。Systems Manager 會使用 SHA-256 雜湊來驗證模組的完整性。Systems Manager 接著會使用 AWS支援的 EC2Launch (Windows Server 2016) 或 EC2Config (Windows Server 2008 R2 到 2012 R2) 方法執行 sysprep。

**步驟 10：stopInstance 停止 (`aws:changeInstanceState` 動作) **  
此步驟會停止更新的執行個體。

**步驟 11：createImage (`aws:createImage` 動作) **  
此步驟會以連結至來源 ID 和建立時間的描述性名稱建立新的 AMI。例如：「AMI Generated by EC2 Automation on \$1\$1global:DATE\$1TIME\$1\$1 from \$1\$1SourceAmiId\$1\$1」，其中 DATE\$1TIME 和 SourceID 代表自動化變數。

**步驟 12：TerminateInstance (`aws:changeInstanceState` 動作) **  
此步驟會藉由終止執行中的執行個體來清除自動化。

**Output**  
本節可讓您將各種步驟的輸出或任何參數的值指定為自動化輸出。根據預設，輸出是由自動化建立的已更新 Windows AMI 之 ID。

**注意**  
根據預設，自動化執行 `AWS-UpdateWindowsAmi` Runbook 和建立暫時執行個體時，系統會使用預設 VPC (172.30.0.0/16)。如果刪除預設 VPC，您會收到以下錯誤：  
VPC 未定義 400  
若要解決此問題，您必須複製 `AWS-UpdateWindowsAmi` Runbook 並指定子網路 ID。如需詳細資訊，請參閱[VPC 未定義 400](automation-troubleshooting.md#automation-trbl-common-vpc)。

**使用自動化建立已修補的 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` Runbook。將每個*範例資源預留位置*取代為您自己的資訊。以下的範例命令使用最新的 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 分鐘或以上的時間完成，取決於修補程式的數量。

# AMI 使用自動化更新黃金 AWS Lambda，以及 Parameter Store
<a name="automation-tutorial-update-patch-golden-ami"></a>

在以下範例使用的模型中，組織會維護並定期修補其自有的專屬 AMIs，而非從 Amazon Elastic Compute Cloud (Amazon EC2) AMIs 建立。

以下程序示範如何自動將作業系統 (OS) 修補程式套用至已視為是最近期或*最新* AMI 的 AMI。在此範例中， 參數的預設值是由名為 的 AWS Systems Manager Parameter Store參數`SourceAmiId`定義`latestAmi`。值`latestAmi`會由自動化結束時叫用的 AWS Lambda 函數更新。此 Automation 程序可將耗費在修補 AMIs 的時間與心力降至最低，原因在於修補一律會套用至最新的 AMI。Parameter Store 和 Automation 是 AWS Systems Manager的工具。

**開始之前**  
設定 Automation 角色和 (選用) Automation 的 Amazon EventBridge。如需詳細資訊，請參閱[設定自動化](automation-setup.md)。

**Topics**
+ [任務 1：建立 Systems Manager Parameter Store 參數](#create-parameter-ami)
+ [任務 2：建立 的 IAM 角色 AWS Lambda](#create-lambda-role)
+ [任務 3：建立 AWS Lambda 函數](#create-lambda-function)
+ [任務 4：建立 Runbook 並修補 AMI](#create-custom-ami-update-runbook)

## 任務 1：建立 Systems Manager Parameter Store 參數
<a name="create-parameter-ami"></a>

在 Parameter Store 中建立字串參數，使用以下資訊：
+ **Name (名稱)**：`latestAmi`。
+ **值**：AMI ID。例如：` ami-188d6e0e`。

如需建立 Parameter Store 字串參數的詳細資訊，請參閱 [在 Systems Manager 中建立 Parameter Store 參數](sysman-paramstore-su-create.md)。

## 任務 2：建立 的 IAM 角色 AWS Lambda
<a name="create-lambda-role"></a>

使用下列程序來建立 的 IAM 服務角色 AWS Lambda。這些政策會提供 Lambda 許可，以使用 Lambda 函數和 Systems Manager 來更新 `latestAmi` 參數的值。

**建立適用於 Lambda 的 IAM 服務角色**

1. 登入 AWS 管理主控台 ，並在 https：//[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. 在**檢閱政策**頁面上**名稱**中，輸入該內嵌政策的名稱，例如 **amiLambda**。

1. 選擇**建立政策**。

1. 重複步驟 2 和 3。

1. 貼上下列政策。將每個*範例資源預留位置*取代為您自己的資訊。

------
#### [ 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. 在**檢閱政策**頁面上**名稱**中，輸入該內嵌政策的名稱，例如 **amiParameter**。

1. 選擇**建立政策**。

1. 在導覽窗格中，選擇**角色**，然後選擇**建立角色**。

1. 在**使用案例**下，隨即選擇 **Lambda**，然後選擇**下一步**。

1. 在**新增許可**頁面上，使用**搜尋**欄位找出您之前建立的兩個政策。

1. 選取政策旁的核取方塊，然後選擇**下一步**。

1. 對於 **Role name (角色名稱)**，輸入新角色的名稱，例如 **lambda-ssm-role** 或另一個您喜好的名稱。
**注意**  
因為有各種實體可能會參照角色，所以您無法在建立角色之後變更角色名稱。

1. (選用) 新增一或多個標籤鍵值組來整理、追蹤或控制此角色的存取權，然後選擇**建立角色**。

## 任務 3：建立 AWS Lambda 函數
<a name="create-lambda-function"></a>

使用以下程序建立可自動更新 `latestAmi` 參數值的 Lambda 函數。

**建立 Lambda 函數**

1. 登入 AWS 管理主控台 並開啟位於 https：//[https://console.aws.amazon.com/lambda/](https://console.aws.amazon.com/lambda/) 的 AWS Lambda 主控台。

1. 選擇**建立函數**。

1. 在 **Create function (建立函數)** 頁面上，選擇 **Author from scratch (從頭開始撰寫)**。

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. 針對 **Event name (事件名稱)**，輸入測試事件的名稱，例如 **MyTestEvent**。

1. 將現有文字取代為以下的 JSON。把 *AMI ID* 取代為您自己的資訊以設定 `latestAmi` 參數值。

   ```
   {
      "parameterName":"latestAmi",
      "parameterValue":"AMI ID"
   }
   ```

1. 選擇**儲存**。

1. 選擇 **Test (測試)** 以測試函數。在**執行結果**索引標籤上，狀態應報告為**成功**，同時包含與更新有關的其他詳細資訊。

## 任務 4：建立 Runbook 並修補 AMI
<a name="create-custom-ami-update-runbook"></a>

使用以下程序建立和執行 Runbook，以修補您針對 **latestAmi** 參數指定的 AMI。自動化工作流程完成後，**latestAmi** 的值會以新修補的 AMI 之 ID 更新。後續的自動化會使用由先前執行建立的 AMI。

**建立和執行 Runbook**

1. 在 https：//[https://console.aws.amazon.com/systems-manager/](https://console.aws.amazon.com/systems-manager/) 開啟 AWS Systems Manager 主控台。

1. 在導覽窗格中，選擇 **Documents (文件)**。

1. 在**建立文件**中，選擇**自動化**。

1. 對於**名稱**，輸入 **UpdateMyLatestWindowsAmi**。

1. 選擇 **Editor (編輯器)** 標籤，然後選擇 **Edit (編輯)**。

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** Runbook，然後選擇 **UpdateMyLatestWindowsAmi** 卡中的按鈕。

1. 選擇**下一步**。

1. 選擇 **Simple execution (簡單執行)**。

1. 請為輸入參數指定值。

1. 選擇 **Execute (執行)**。

1. 自動化完成後，在導覽窗格中選擇 **Parameter Store** 並確認 `latestAmi` 的新值符合自動化傳回的值。您也可以在 Amazon EC2 主控台的 **AMIs** 部分確認新的 AMI ID 符合自動化輸出。

# 使用 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 之前，請完成以下任務：
+ 完成 [AMI 使用自動化更新黃金 AWS Lambda，以及 Parameter Store](automation-tutorial-update-patch-golden-ami.md) 範例。以下範例使用在該範例中建立的 **UpdateMyLatestWindowsAmi** Runbook。
+ 為 Automation 設定 IAM 角色。Systems Manager 需要執行個體設定檔角色和服務角色 ARN 以處理自動化。如需詳細資訊，請參閱[設定自動化](automation-setup.md)。

**為 Jenkins 伺服器建立 IAM 政策**

1. 登入 AWS 管理主控台 ，並在 https：//[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": "ssm:StartAutomationExecution",
               "Resource": [
                   "arn:aws:ssm:us-east-1:111122223333:document/UpdateMyLatestWindowsAmi",
                   "arn:aws:ssm:us-east-1:111122223333:automation-execution/*"
               ]
           }
       ]
   }
   ```

------

1. 選擇**檢閱政策**。

1. 在**檢閱政策**頁面上**名稱**中，輸入該內嵌政策的名稱，例如 **JenkinsPolicy**。

1. 選擇**建立政策**。

1. 在導覽窗格中，選擇**角色**。

1. 選擇連接至 Jenkins 伺服器的執行個體設定檔。

1. 在**許可**索引標籤上，依序選擇**新增許可**、**連接政策**。

1. 在**其他許可政策**區段中，輸入您在之前的步驟中建立的政策名稱。例如，**JenkinsPolicy**。

1. 勾選政策旁邊的方塊，然後選擇**連接政策**。

使用下列程序在您的 AWS CLI 伺服器上設定 Jenkins。

**為 Automation 設定 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 執行個體設定檔取得憑證**選項。

按照下列程序設定 Jenkins 專案以調用 Automation。

**設定 Jenkins 伺服器以調用 Automation**

1. 在 Web 瀏覽器中開啟 Jenkins 主控台。

1. 選擇您想要以自動化設定的專案，接著選擇 **Configure (設定)**。

1. 在 **Build (建置)** 索引標籤，選擇 **Add Build Step (新增建置步驟)**。

1. 選擇 **Execute shell (執行 shell)** 或 **Execute Windows batch command (執行 Windows 批次命令)** (取決於您的作業系統)。

1. 在**命令**欄位中，執行如下所示的 AWS CLI 命令。將每個*範例資源預留位置*取代為您自己的資訊。

   ```
   aws ssm start-automation-execution \
           --document-name runbook name \
           --region AWS 區域 of your source AMI \
           --parameters runbook parameters
   ```

   下列範例命令使用 **UpdateMyLatestWindowsAmi** Runbook 和 [AMI 使用自動化更新黃金 AWS Lambda，以及 Parameter Store](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/zh_tw/systems-manager/latest/userguide/images/sysman-ami-jenkins2.png)

1. 在 Jenkins 專案中，選擇**立即建置**。Jenkins 會傳回類似於下列範例的輸出。  
![\[Jenkins 軟體中的範例命令輸出。\]](http://docs.aws.amazon.com/zh_tw/systems-manager/latest/userguide/images/sysman-ami-jenkins.png)

# 更新 Auto Scaling 群組的 AMIs
<a name="automation-tutorial-update-patch-windows-ami-autoscaling"></a>

下列範例使用新修補的 AMI 更新 Auto Scaling 群組。此方法可確保新的映像會自動提供給使用 Auto Scaling 群組的不同運算環境。

此範例中自動化的最後步驟使用 Python 函數來建立使用新修補 AMI 的啟動範本。然後，更新 Auto Scaling 群組以使用新的啟動範本。在此類型的 Auto Scaling 情況下，使用者可以在 Auto Scaling 群組中終止現有的執行個體，以強制新的執行個體啟動並使用新映像。或者，使用者可以等待並允許縮減或擴展事件自然啟動較新的執行個體。

**開始之前**  
開始此範例之前，請先完成以下任務。
+ 設定 Automation 的 IAM 角色，這是其中的工具 AWS Systems Manager。Systems Manager 需要執行個體設定檔角色和服務角色 ARN 以處理自動化。如需詳細資訊，請參閱[設定自動化](automation-setup.md)。

## 建立 **PatchAMIAndUpdateASG** Runbook
<a name="create-autoscaling-update-runbook"></a>

請使用下列程序建立 **PatchAMIAndUpdateASG** Runbook，其會修補為 **SourceAMI** 參數指定的 AMI。此 Runbook 也會更新 Auto Scaling 群組以使用最新且經修補的 AMI。

**建立和執行 Runbook**

1. 在 https：//[https://console.aws.amazon.com/systems-manager/](https://console.aws.amazon.com/systems-manager/) 開啟 AWS Systems Manager 主控台。

1. 在導覽窗格中，選擇 **Documents (文件)**。

1. 在 **Create document** (建立文件) 下拉式清單中，選擇 **Automation** (自動化)。

1. 在 **Name (名稱)** 欄位中，輸入 **PatchAMIAndUpdateASG**。

1. 選擇 **Editor** (編輯器) 索引標籤，然後選擇 **Edit** (編輯)。

1. 出現提示時選擇 **OK** (確定)，然後在 **Document editor** (文件編輯器) 欄位中刪除內容。

1. 在 **Document editor** (文件編輯器) 欄位中，貼上下列 YAML 範例 Runbook 內容。

   ```
   ---
   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** Runbook，然後選擇 **PatchAMIAndUpdateASG** 卡中的按鈕。

1. 選擇**下一步**。

1. 選擇 **Simple execution (簡單執行)**。

1. 為輸入參數指定值。確定您指定的 `SubnetId` 和 `SecurityGroupIds` 允許存取公用 Systems Manager 端點，或是 Systems Manager 的介面端點。

1. 選擇 **Execute (執行)**。

1. 自動化完成後，在 Amazon EC2 主控台選擇 **Auto Scaling**，接著選擇 **Launch Templates** (啟動範本)。確認您已看到新的啟動範本，且其使用新的 AMI。

1. 選擇 **Auto Scaling** (Auto Scaling)，然後選擇 **Auto Scaling Groups** (Auto Scaling 群組)。確認 Auto Scaling 群組使用新的啟動範本。

1. 在您的 Auto Scaling 群組中終止一個或多個執行個體。取代執行個體會以新的 AMI 啟動。

# 使用 AWS 支援 自助式 Runbook
<a name="automation-tutorial-support-runbooks"></a>

本節說明如何使用 AWS 支援 團隊建立的一些自助式自動化。這些自動化可協助您管理 AWS 資源。

**支援 Automation 工作流程**  
支援自動化工作流程 (SAW) 是由 AWS 支援 團隊撰寫和維護的自動化 Runbook。這些 Runbook 可協助您疑難排解 AWS 資源的常見問題、主動監控和識別網路問題、收集和分析日誌等。

SAW Runbook 使用 **`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 支援計劃的客戶也可以存取使用 **`AWSPremiumSupport`**字首的 Runbook。例如 [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 支援，請參閱 [入門 AWS 支援](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) 執行個體的問題進行故障診斷。您可以手動執行工具，請參閱 [Using EC2Rescue for Linux Server (使用適用於 Linux 伺服器的 EC2Rescue)](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Linux-Server-EC2Rescue.html) 和 [Using EC2Rescue for Windows Server (使用適用於 Windows Server 的 EC2Rescue)](https://docs.aws.amazon.com/AWSEC2/latest/WindowsGuide/Windows-Server-EC2Rescue.html)。或者，您可以使用 Systems Manager Automation 和 **`AWSSupport-ExecuteEC2Rescue`** Runbook 自動執行工具。Automation 是 AWS Systems Manager中的工具。**`AWSSupport-ExecuteEC2Rescue`** Runbook 旨在執行一組 Systems Manager 動作、 CloudFormation 動作和 Lambda 函數，以將通常必須使用 EC2Rescue 的步驟自動化。

您可以使用 **`AWSSupport-ExecuteEC2Rescue`** Runbook 針對不同類型的作業系統 (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`** Runbook 對執行個體進行故障診斷的運作方式如下：
+ 您要指定無法連線的執行個體 ID 並執行 Runbook。
+ 系統會建立暫時 VPC，接著執行一系列 Lambda 函數以設定 VPC。
+ 系統會在與原始執行個體相同的可用區域中為您的暫時 VPC 識別出子網路。
+ 系統會啟動暫時且啟用 SSM 的協助程式執行個體。
+ 系統會停止您的原始執行個體，並建立備份。接著系統會將原始根磁碟區連接至協助程式執行個體。
+ 系統會使用 Run Command 在協助程式執行個體上執行 EC2Rescue。EC2Rescue 會在已連接的原始根磁碟區上識別並嘗試修正問題。完成後，EC2Rescue 會重新將根磁碟區連接回原始執行個體。
+ 系統會重新啟動您的原始執行個體，並終止暫時執行個體。系統也會終止在自動化開始時建立的暫時 VPC 和 Lambda 函數。

## 開始之前
<a name="automation-ec2rescue-begin"></a>

執行以下自動化之前，請先執行以下項目：
+ 複製無法連線之執行個體的執行個體 ID。您會在程序中指定此 ID。
+ 或者，收集與無法連線之執行個體位於相同可用區域中的子網路 ID。EC2Rescue 執行個體會在此子網路中建立。如果您未指定子網路，則自動化會在您的 中建立新的暫時 VPC AWS 帳戶。確認您的 至少 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)。
+ 或者，您可以建立並指定自動化的 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 受管政策，您也必須為其連接 **AmazonSSMAutomationRole** 受管政策，以使您的執行個體能夠與 Systems Manager API 通訊。

**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 自動化建立所需的 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 值。

   例如，對於中國區域，將 `arn:aws` 的所有案例變更為 `arn:aws-cn`。

1. 登入 AWS 管理主控台 ，並在 https：//[https://console.aws.amazon.com/cloudformation](https://console.aws.amazon.com/cloudformation/) 開啟 CloudFormation 主控台。

1. 選擇 **Create stack (建立堆疊)**、**With new resources (standard) (使用新資源 (標準))**。

1. 在 **Create stack (建立堆疊)** 頁面上，對於 **Prerequisite - Prepare template (先決條件 - 準備範本)**，選擇 **Template is ready (範本已準備就緒)**。

1. 對於 **Specify template (指定範本)**，選擇 **Upload a template file (上傳範本檔案)**。

1. 選擇 **Choose file (選擇檔案)**，然後瀏覽並從您解壓縮檔案的目錄中選取 `AWSSupport-EC2RescueRole.json` 檔案。

1. 選擇**下一步**。

1. 在 **Specify stack details (指定堆疊詳細資訊)** 頁面上，對於 **Stack name (堆疊名稱)** 欄位，輸入識別此堆疊的名稱，然後選擇 **Next (下一步)**。

1. (選用) 在 **Tags (標籤)** 區域中將一個或多個標籤索引鍵名稱/值對套用至堆疊。

   標籤是您指派給資源的選用性中繼資料。標籤可讓您以不同的方式 (例如用途、擁有者或環境) 將資源分類。例如，您可能想要標記堆疊來識別其執行的任務類型、相關的目標類型或其他資源，以及其執行所在的環境。

1. 選擇 **Next** (下一步)

1. 在**檢閱**頁面上，檢閱堆疊詳細資訊，然後向下捲動並選擇**我確認 CloudFormation 可能建立 IAM 資源**的選項。

1. 選擇**建立堆疊**。

   CloudFormation 會顯示 **CREATE\$1IN\$1PROGRESS** 狀態幾分鐘。堆疊建立之後，狀態會變更為 **CREATE\$1COMPLETE (CREATE\$1COMPLETE)**。您也可以選擇重新整理圖示來檢查建立程序的狀態。

1. 在 **Stacks** (堆疊) 清單中，選擇您剛建立堆疊的選項按鈕，然後選擇 **Outputs** (輸出) 索引標籤。

1. 請記下 **Value (值)**。此為 AssumeRole 的 ARN。當您在下一個程序[執行自動化](#automation-ec2rescue-executing)中執行自動化時，請指定此 ARN。

## 執行自動化
<a name="automation-ec2rescue-executing"></a>

**重要**  
以下自動化工作流程會停止無法連線的執行個體。停止執行個體可能會導致已連接執行個體存放磁碟區上的資料遺失 (若有)。停止執行個體也可能會導致公有 IP 變更 (若無關聯的彈性 IP)。

**執行 `AWSSupport-ExecuteEC2Rescue` 自動化。**

1. 在 https：//[https://console.aws.amazon.com/systems-manager/](https://console.aws.amazon.com/systems-manager/) 開啟 AWS Systems Manager 主控台。

1. 在導覽窗格中，選擇 **Automation** (自動化)。

1. 選擇 **Execute automation (執行自動化)**。

1. 在 **Automation document (自動化文件)** 部分，從清單選擇 **Owned by Amazon (由 Amazon 所有)**。

1. 在 Runbook 清單中，選擇 `AWSSupport-ExecuteEC2Rescue` 卡片中的按鈕，然後選擇 **Next** (下一步)。

1. 在 **Execute automation document (執行自動化文件)** 頁面上，選擇 **Simple execution (簡易執行)**。

1. 在 **Document details (文件詳細資訊)** 部分，確認 **Document version (文件版本)** 設為最高的預設版本。例如，**\$1DEFAULT** 或 **3 (default) (3 (預設))**。

1. 在 **Input parameters (輸入參數)** 區段中，指定以下參數：

   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 的選項，請確認您使用的是 Runbook 最新的 **Default** (預設) 版本。

1. (選用) 在 **Tags** (標籤) 區域中，套用一個或多個標籤索引鍵名稱/值對以協助識別自動化，例如 `Key=Purpose,Value=EC2Rescue`。

1. 選擇 **Execute (執行)**。

作為自動化的一部分，Runbook 會建立備份 AMI。其他所有由自動化建立的資源都會自動刪除，但此 AMI 會保留於您的帳戶。AMI 使用以下慣例命名：

備份 AMI：AWSSupport-EC2Rescue:*UnreachableInstanceId*

您可以搜尋自動化執行 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` Runbook 旨在執行 AWS Systems Manager 動作、 AWS CloudFormation 動作和 AWS Lambda 函數的組合，以自動化重設本機管理員密碼通常所需的步驟。

您可以使用 中的自動化工具 AWS Systems Manager搭配 `AWSSupport-ResetAccess` Runbook 來解決下列問題：

**Windows**

*遺失 EC2 金鑰對*：若要解決此問題，您可以使用 **AWSSupport-ResetAccess** Runbook 從您目前的執行個體建立啟用密碼的 AMI，從 AMI 啟動新的執行個體，接著選取您自己的金鑰對。

*遺失本機管理員密碼*：若要解決此問題，您可以使用 `AWSSupport-ResetAccess` Runbook 產生可藉由目前的 EC2 金鑰對解密的新密碼。

**Linux**

*遺失 EC2 金鑰對，或遺失設定執行個體之 SSH 存取的金鑰*：若要解決此問題，您可以使用 `AWSSupport-ResetAccess` Runbook 為目前的執行個體建立新的 SSH 金鑰，這可讓您再次連線至執行個體。

**注意**  
如果您的適用於 Windows Server 的 EC2 執行個體是針對 Systems Manager 設定，您也可以使用 EC2Rescue 和 AWS Systems Manager Run Command 重設本機管理員密碼。如需詳細資訊，請參閱《Amazon EC2 使用者指南》**中的[將 EC2Rescue for Windows Server 與 Systems Manager Run Command 搭配使用](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` Runbook 對執行個體進行故障診斷的運作方式如下：
+ 您要指定執行個體 ID 並執行 Runbook。
+ 系統會建立暫時 VPC，接著執行一系列 Lambda 函數以設定 VPC。
+ 系統會在與原始執行個體相同的可用區域中為您的暫時 VPC 識別出子網路。
+ 系統會啟動暫時且啟用 SSM 的協助程式執行個體。
+ 系統會停止您的原始執行個體，並建立備份。接著系統會將原始根磁碟區連接至協助程式執行個體。
+ 系統會使用 Run Command 在協助程式執行個體上執行 EC2Rescue。在 Windows 上，EC2Rescue 會於已連接的原始根磁碟區使用 EC2Config 或 EC2Launch，藉此啟用本機管理員的密碼產生。在 Linux 上，EC2Rescue 會產生和插入新的 SSH 金鑰，並將私密金鑰加密儲存於 Parameter Store。完成後，EC2Rescue 會重新將根磁碟區連接回原始執行個體。
+ 密碼產生啟用後，系統會在您的執行個體建立新的 Amazon Machine Image (AMI)。您可以使用此 AMI 建立新的 EC2 執行個體，並視需要與新的金鑰對建立關聯。
+ 系統會重新啟動您的原始執行個體，並終止暫時執行個體。系統也會終止在自動化開始時建立的暫時 VPC 和 Lambda 函數。
+ **Windows**：您的執行個體會產生新密碼，而您可以使用目前指派給執行個體的金鑰對從 Amazon EC2 主控台解碼。

  **Linux**：SSH 金鑰以 **/ec2rl/openssh/*instance ID*/key** 存放在 Systems Manager 參數存放區，您可用此金鑰 SSH 至執行個體。

## 開始之前
<a name="automation-ec2reset-begin"></a>

執行以下自動化之前，請先執行以下項目：
+ 複製您想要重設管理員密碼的執行個體之執行個體 ID。您會在程序中指定此 ID。
+ 或者，收集與無法連線之執行個體位於相同可用區域中的子網路 ID。EC2Rescue 執行個體會在此子網路中建立。如果您未指定子網路，則自動化會在您的 中建立新的暫時 VPC AWS 帳戶。確認您的 至少 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)。
+ 或者，您可以建立和指定自動化的 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 受管政策，您也必須為其連接 **AmazonSSMAutomationRole** 受管政策，以使您的執行個體能夠與 Systems Manager API 通訊。

**`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 自動化建立所需的 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 值。

   例如，對於中國區域，將 `arn:aws` 的所有案例變更為 `arn:aws-cn`。

1. 登入 AWS 管理主控台 ，並在 https：//[https://console.aws.amazon.com/cloudformation](https://console.aws.amazon.com/cloudformation/) 開啟 CloudFormation 主控台。

1. 選擇 **Create stack (建立堆疊)**、**With new resources (standard) (使用新資源 (標準))**。

1. 在 **Create stack (建立堆疊)** 頁面上，對於 **Prerequisite - Prepare template (先決條件 - 準備範本)**，選擇 **Template is ready (範本已準備就緒)**。

1. 對於 **Specify template (指定範本)**，選擇 **Upload a template file (上傳範本檔案)**。

1. 選擇 **Choose file (選擇檔案)**，然後瀏覽並從您解壓縮檔案的目錄中選取 `AWSSupport-EC2RescueRole.json` 檔案。

1. 選擇**下一步**。

1. 在 **Specify stack details (指定堆疊詳細資訊)** 頁面上，對於 **Stack name (堆疊名稱)** 欄位，輸入識別此堆疊的名稱，然後選擇 **Next (下一步)**。

1. (選用) 在 **Tags (標籤)** 區域中將一個或多個標籤索引鍵名稱/值對套用至堆疊。

   標籤是您指派給資源的選用性中繼資料。標籤可讓您以不同的方式 (例如用途、擁有者或環境) 將資源分類。例如，您可能想要標記堆疊來識別其執行的任務類型、相關的目標類型或其他資源，以及其執行所在的環境。

1. 選擇 **Next** (下一步)

1. 在**檢閱**頁面上，檢閱堆疊詳細資訊，然後向下捲動並選擇**我確認 CloudFormation 可能建立 IAM 資源**的選項。

1. CloudFormation 會顯示 **CREATE\$1IN\$1PROGRESS** 狀態幾分鐘。堆疊建立之後，狀態會變更為 **CREATE\$1COMPLETE (CREATE\$1COMPLETE)**。您也可以選擇重新整理圖示來檢查建立程序的狀態。

1. 在堆疊清單中，選擇您剛建立堆疊旁的選項，然後選擇 **Outputs (輸出)** 標籤。

1. 複製 **Value (值)**。此為 AssumeRole 的 ARN。您會在執行自動化時指定此 ARN。

## 執行自動化
<a name="automation-ec2reset-executing"></a>

下列程序說明如何使用 AWS Systems Manager 主控台來執行 `AWSSupport-ResetAccess` Runbook。

**重要**  
以下自動化會停止執行個體。停止執行個體可能會導致已連接執行個體存放磁碟區上的資料遺失 (若有)。停止執行個體也可能會導致公有 IP 變更 (若無關聯的彈性 IP)。為了避免這些組態變更，請使用 Run Command 重設存取。如需詳細資訊，請參閱《Amazon EC2 使用者指南》**中的[將 EC2Rescue for Windows Server 與 Systems Manager Run Command 搭配使用](https://docs.aws.amazon.com/AWSEC2/latest/WindowsGuide/ec2rw-ssm.html)。

**執行 AWSSupport-ResetAccess 自動化**

1. 在 https：//[https://console.aws.amazon.com/systems-manager/](https://console.aws.amazon.com/systems-manager/) 開啟 AWS Systems Manager 主控台。

1. 在導覽窗格中，選擇 **Automation** (自動化)。

1. 選擇 **Execute automation (執行自動化)**。

1. 在 **Automation document (自動化文件)** 部分，從清單選擇 **Owned by Amazon (由 Amazon 所有)**。

1. 在 Runbook 清單中，選擇 **AWSSupport-ResetAccess** 卡片中的按鈕，然後選擇 **Next** (下一步)。

1. 在 **Execute automation document (執行自動化文件)** 頁面上，選擇 **Simple execution (簡易執行)**。

1. 在 **Document details (文件詳細資訊)** 部分，確認 **Document version (文件版本)** 設為最高的預設版本。例如，**\$1DEFAULT** 或 **3 (default) (3 (預設))**。

1. 在 **Input parameters (輸入參數)** 區段中，指定以下參數：

   1. 針對 **InstanceID**，指定無法連線之執行個體的 ID。

   1. 針對 **SubnetId**，在與您指定之執行個體位於相同可用區域的現有 VPC 中指定子網路。根據預設，Systems Manager 會建立新的 VPC，但您也可以在現有 VPC 中指定子網路。
**注意**  
如果您沒見到指定子網路 ID 的選項，請確認您使用的是 Runbook 最新的 **Default** (預設) 版本。

   1. 針對 **EC2RescueInstanceType**，指定 EC2Rescue 執行個體的執行個體類型。預設執行個體類型為 `t2.medium`。

   1. 針對 **AssumeRole**，如果您使用本主題先前所述的 CloudFormation 程序為此自動化建立角色，請指定您在 CloudFormation 主控台中記下的 AssumeRole ARN。

1. (選用) 在 **Tags** (標籤) 區域中，套用一個或多個標籤索引鍵名稱/值對以協助識別自動化，例如 `Key=Purpose,Value=ResetAccess`。

1. 選擇 **Execute (執行)**。

1. 若要監控自動化進度，請選擇執行中的自動化，接著選擇 **Steps** (步驟) 標籤。自動化結束時，選擇 **Descriptions** (描述) 標籤，接著選擇 **View output** (檢視輸出) 以檢視結果。若要檢視個別步驟的輸出，請選擇 **Steps (步驟)** 標籤，然後選擇步驟旁的 **View Outputs (檢視輸出)**。

作為自動化的一部分，Runbook 會建立備份 AMI 和已啟用密碼的 AMI。其他所有由自動化建立的資源都會自動刪除，但此 AMIs 會保留於您的帳戶。這些 AMIs 使用以下慣例命名：
+ 備份 AMI：`AWSSupport-EC2Rescue:InstanceID`
+ 密碼啟動的 AMI：AWSSupport-EC2Rescue：從*執行個體 ID* 以密碼啟動的 AMI

您可以搜尋自動化執行 ID 以找到這些 AMIs。

針對 Linux，執行個體的新 SSH 私密金鑰會加密儲存於 Parameter Store。參數名稱為 **/ec2rl/openssh/*instance ID*/key**。

# 使用輸入轉換器將資料傳遞至 Automation
<a name="automation-tutorial-eventbridge-input-transformers"></a>

本 AWS Systems Manager 自動化教學課程說明如何使用 Amazon EventBridge 的輸入轉換器功能，從執行個體狀態變更事件中擷取 Amazon Elastic Compute Cloud (Amazon EC2) 執行個體`instance-id`的 。Automation 是 AWS Systems Manager中的工具。我們使用輸入轉換器將該資料傳遞給 `AWS-CreateImage` Runbook 目標，作為 `InstanceId` 輸入參數。當執行個體變更為 `stopped` 狀態時，將觸發規則。

如需使用輸入轉換器的詳細資訊，請參閱《Amazon EventBridge 使用者指南**》中的[教學課程：使用輸入轉換器以自訂傳送至事件目標的內容](https://docs.aws.amazon.com/eventbridge/latest/userguide/eventbridge-input-transformer-tutorial.html)。

**開始之前**  
確認您已將必要的 EventBridge 許可和信任政策新增至您的 Systems Manager Automation 服務角色。如需詳細資訊，請參閱《Amazon EventBridge 使用者指南**》中的[管理您的 EventBridge 資源之存取許可的概觀](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 帳戶，請選取**預設值**。當您帳戶中 AWS 服務 的 發出事件時，一律會前往您帳戶的預設事件匯流排。

1. 針對**規則類型**，選擇**具有事件模式的規則**。

1. 選擇**下一步**。

1. 在**事件來源**欄位中，選擇 **AWS 事件或 EventBridge 合作夥伴事件**。

1. 在**事件模式**區段中，選擇**使用模式表單**。

1. 在 **Event source** (事件來源) 欄位中，選擇 **AWS services** (服務)。

1. 在 **AWS 服務**中，選擇 **EC2**。

1. 在 **Event Type (事件類型)** 中，選擇 **EC2 Instance State-change Notification (EC2 執行個體狀態變更通知)**。

1. 針對**事件類型規格 1**，選取**特定狀態**，然後選擇**已停止**。

1. 針對**事件類型規格 2**，選取**任何執行個體**，或選取**特定執行個體 ID**，然後輸入要監控的執行個體 ID。

1. 選擇**下一步**。

1. 在**目標類型**欄位中，選擇 **AWS 服務**。

1. 針對 **Select a target** (選取目標)，請選擇 **Systems Manager Automation**。

1. 在 **Document (文件)** 中，選擇 **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** (使用現有角色)，然後選擇您的自動化服務角色。

1. 選擇**下一步**。

1. (選用) 為規則輸入一或多個標籤。如需詳細資訊，請參閱《Amazon EventBridge 使用者指南**》中的[標記您的 Amazon EventBridge 資源](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 是 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 以回應動作或自動化狀態變更。

如需有關在自動化中處理逾時的詳細資訊，請參閱 [處理 Runbook 中的逾時](automation-handling-timeouts.md)。

## 關於自動化狀態
<a name="automation-statuses-about"></a>

除了整體自動化之外，自動化還會報告個別自動化動作的狀態詳細資訊。

整體自動化狀態可能會與個別動作或步驟所回報的狀態不同，如以下資料表所示。


**動作的詳細狀態**  

| 狀態 | 詳細資訊 | 
| --- | --- | 
| 待定 | 步驟尚未開始執行。如果您的自動化使用條件式動作，則在不符合條件的情形下執行步驟時，自動化完成後，步驟仍會維持在此狀態。如果在步驟執行之前取消自動化，則步驟也會保持在此狀態。 | 
| InProgress | 步驟正在執行中。 | 
| 等待 | 步驟正在等待輸入。 | 
| 成功 | 步驟已成功完成。這是一個終端狀態。 | 
| TimedOut | 步驟或核准未在指定的逾時期間之前完成。這是一個終端狀態。 | 
| 取消 | 申請者取消後，步驟正在停用過程中。 | 
| 已取消 | 在完成之前，申請者停止了步驟。這是一個終端狀態。 | 
| 失敗 |  步驟未成功完成。這是一個終端狀態。  | 
| Exited |  僅由 `aws:loop` 動作傳回。迴圈未完全完成。迴圈內的步驟使用 `nextStep`、`onCancel` 或 `onFailure` 屬性移至外部步驟。  | 


**自動化的詳細狀態**  

| 狀態 | 詳細資訊 | 
| --- | --- | 
| 待定 | 自動化尚未開始執行。 | 
| InProgress | 自動化正在執行中。 | 
| 等待 | 自動化正在等待輸入。 | 
| 成功 | 自動化已成功完成。這是一個終端狀態。 | 
| TimedOut | 步驟或核准未在指定的逾時期間之前完成。這是一個終端狀態。 | 
| 取消 | 申請者取消後，自動化正在停用過程中。 | 
| 已取消 | 在完成之前，申請者停止了自動化。這是一個終端狀態。 | 
| 失敗 |  自動化未成功完成。這是一個終端狀態。  | 

# 故障診斷 Systems Manager Automation
<a name="automation-troubleshooting"></a>

使用以下資訊，協助您對 AWS Systems Manager Automation ( AWS Systems Manager中的工具) 的問題進行疑難排解。此主題包含根據自動化錯誤訊息解決問題的特定任務。

**Topics**
+ [常見的自動化錯誤](#automation-trbl-common)
+ [自動化執行無法啟動](#automation-trbl-access)
+ [執行已開始，但狀態為失敗](#automation-trbl-exstrt)
+ [執行已開始，但發生逾時](#automation-trbl-to)

## 常見的自動化錯誤
<a name="automation-trbl-common"></a>

本節包含常見自動化錯誤的資訊。

### VPC 未定義 400
<a name="automation-trbl-common-vpc"></a>

根據預設，自動化執行 `AWS-UpdateLinuxAmi` Runbook 或 `AWS-UpdateWindowsAmi` Runbook 時，系統會在預設 VPC (172.30.0.0/16) 中建立暫時執行個體。如果刪除預設 VPC，您會收到以下錯誤：

`VPC not defined 400`

如要解決此問題，您必須指定 `SubnetId` 輸入參數的值。

## 自動化執行無法啟動
<a name="automation-trbl-access"></a>

如果您尚未正確設定 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：將 iam:PassRole 政策連接至自動化角色](automation-setup-iam.md#attach-passrole-policy)。

### 無效的擔任角色
<a name="automation-trbl-ar"></a>

在您執行 Automation 時，擔任角色會由 Runbook 提供或做為 Runbook 的參數值傳遞。如果未指定或正確設定擔任角色，可能會發生不同類型的錯誤。

**格式錯誤的擔任角色**  
**錯誤訊息**：`The format of the supplied assume role ARN isn't valid.` 擔任角色格式不正確。若要解決此問題，請確認您的 Runbook 中指定了有效的擔任角色，或在執行自動化時將其做為執行時間參數。

**擔任角色無法擔任**  
**錯誤訊息**：`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-setup.md)。以下主題說明建立此角色的特定詳細資訊：[任務 1：建立自動化的服務角色](automation-setup-iam.md#create-service-role)。
+ 可能原因 2：擔任角色與 Systems Manager 服務沒有信任關係。若要解決此問題，請建立信任關係。如需詳細資訊，請參閱《IAM 使用者指南**》中的[我無法擔任角色](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>

Runbook 包含步驟和依序執行的步驟。每個步驟會呼叫一個或多個 AWS 服務 API。API 會決定輸入、行為和步驟的輸出。有許多地方可能會發生錯誤導致步驟失敗。失敗訊息會指出錯誤發生的時間和位置。

若要在 Amazon Elastic Compute Cloud (Amazon EC2) 主控台查看失敗訊息，請選擇失敗步驟的 **View Outputs (檢視輸出)** 連結。若要查看來自 的失敗訊息 AWS CLI，請呼叫 `get-automation-execution`並在失敗的 中尋找 `FailureMessage` 屬性`StepExecution`。

在以下範例中，與 `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 更新 Runbook 或參數值。

**擔任角色政策缺少足夠的許可**  
**錯誤訊息**：`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。若要解決此問題，請將 IAM 政策連接至擁有呼叫 `RunInstances` API 之許可的擔任角色。如需更多資訊，請參閱[使用主控台建立用於自動化的服務角色](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` 動作指定的使用者資料指令碼有問題或語法不正確。確認使用者資料指令碼的語法。此外，確認使用者資料指令碼並未關閉執行個體或呼叫其他指令碼以關閉執行個體。

**動作特定的故障參考**  
步驟失敗時，失敗訊息可能會指出發生失敗時正在呼叫什麼服務。下表列出各動作呼叫的服務。表格也提供了各服務的相關資訊連結。


****  

| Action | 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 執行命令](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 Machine Image](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)  | 

### 自動化服務內部錯誤
<a name="automation-trbl-err"></a>

**錯誤訊息**：`Internal Server Error. Please refer to Automation Service Troubleshooting Guide for more diagnosis details.`

Automation 服務的一項問題使指定的 Runbook 無法正確執行。若要解決此問題，請聯絡 AWS 支援。請提供執行 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` 參數指定較長的值。如果這樣未解決問題，請調查步驟執行時間比預期更久的原因