

• 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-actions-and-change"></a>

AWS Systems Manager 提供下列工具來變更您的 AWS 資源。

**Topics**
+ [AWS Systems Manager 自動化](systems-manager-automation.md)
+ [AWS Systems Manager Change Calendar](systems-manager-change-calendar.md)
+ [AWS Systems Manager Change Manager](change-manager.md)
+ [AWS Systems Manager Documents](documents.md)
+ [AWS Systems Manager Maintenance Windows](maintenance-windows.md)
+ [AWS Systems Manager Quick Setup](systems-manager-quick-setup.md)

# 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` 參數指定較長的值。如果這樣未解決問題，請調查步驟執行時間比預期更久的原因

# AWS Systems Manager Change Calendar
<a name="systems-manager-change-calendar"></a>

Change Calendar當您指定的動作 （例如，在 [Systems Manager Automation](systems-manager-automation.md) Runbook 中） 可能會在您的 中執行或不執行時， 中的工具 AWS Systems Manager可讓您設定日期和時間範圍 AWS 帳戶。在 Change Calendar 中，這些範圍稱為「事件」**。當您建立了 Change Calendar 項目，也會建立類型 `ChangeCalendar` 的 [Systems Manager](documents.md) 文件。在 Change Calendar 中，這些文件會以純文字格式儲存 [iCalendar 2.0](https://icalendar.org/) 資料。您新增到 Change Calendar 項目的事件將成為文件的一部份。若要開始使用 Change Calendar，請開啟 [Systems Manager 主控台](https://console.aws.amazon.com//systems-manager/change-calendar)。在導覽窗格中，選擇 **Change Calendar**。

您可以在 Systems Manager 主控台中建立行事曆及其事件。您還可以匯入從支援的第三方行事曆供應商匯出的 iCalendar (`.ics`) 檔案，以將其事件新增到您的行事曆中。支援的供應商包括 Google 行事曆、Microsoft Outlook 和 iCloud 行事曆。

Change Calendar 項目可能為以下兩種類型之一：

**`DEFAULT_OPEN`**，或預設開啟  
預設情況下 (但行事曆事件期間除外)，所有動作都可以執行。事件進行期間，`DEFAULT_OPEN` 行事曆的狀態為 `CLOSED`，且事件無法執行。

**`DEFAULT_CLOSED`**，或預設關閉。  
預設情況下 (但行事曆事件期間除外)，所有動作都無法執行。事件進行期間，`DEFAULT_CLOSED` 行事曆的狀態為 `OPEN`，且動作能夠執行。

您可以選擇將所有已排程的 Automation 工作流程、維護時段和 State Manager 關聯自動新增至行事曆。您也可以從行事曆顯示中移除這些個別類型的任何項。

## 誰應該使用Change Calendar？
<a name="systems-manager-change-calendar-who"></a>

**Change Manager 可用性變更**  
AWS Systems ManagerChange Manager 自 2025 年 11 月 7 日起，不再向新客戶開放。如果您想要使用 Change Manager，請在該日期之前註冊。現有客戶可以繼續正常使用該服務。如需詳細資訊，請參閱[AWS Systems ManagerChange Manager可用性變更](https://docs.aws.amazon.com/systems-manager/latest/userguide/change-manager-availability-change.html)。
+ AWS 執行下列動作類型的客戶：
  + 建立或執行 Automation 執行手冊。
  + 在 Change Manager 中建立變更請求。
  + 執行維護時段。
  + 在 State Manager 中建立關聯。

  自動化、Maintenance Windows、 和 Change ManagerState Manager都是工具 AWS Systems Manager。將這些工具與 Change Calendar 整合，您可以根據每個動作關聯的變更行事曆的目前狀態，允許或封鎖這些動作類型。
+ 負責確保 Systems Manager 受管節點組態一致性、穩定性和運作的管理員。

## Change Calendar 的優點
<a name="systems-manager-change-calendar-benefits"></a>

以下是 Change Calendar 的部分優點。
+ **在套用變更前事先檢閱**

  Change Calendar 項目可協助確保事先檢閱可能破壞環境的變更，再加以套用。
+ **僅在適當時機套用變更**

  Change Calendar 項目可協助確保環境在事件進行期間的穩定性。舉例來說，您可以建立 Change Calendar 項目，以便在您預期有高資源需求 (例如會議或公開行銷期間) 的時候禁止變更。當您預期有管理員支援有限 (例如假期或假日) 時，行事曆項目也可以禁止變更。您可以使用行事曆項目來允許變更，並將管理員支援有限，而不足以針對失敗工作或部署進行故障診斷的特定時段排除。
+ **取得目前或即將變更的行事曆狀態**

  您可以執行 Systems Manager `GetCalendarState` API 操作來獲得行事曆目前的狀態、指定時間的狀態，或是行事曆已排程變更的下一個狀態。
**注意**  
`GetCalendarState` API 的配額為每秒 10 個請求。如需有關 Systems Manager 配額的詳細資訊，請參閱 *Amazon Web Services 一般參考* 中的 [Systems Manager service quotas](https://docs.aws.amazon.com/general/latest/gr/ssm.html#limits_ssm)。
+ 

**支援 EventBridge**  
此 Systems Manager 工具作為 Amazon EventBridge 規則中的*事件*類型受到支援。如需詳細資訊，請參閱 [使用 Amazon EventBridge 監控 Systems Manager](monitoring-eventbridge-events.md) 及 [參考：Systems Manager 的 Amazon EventBridge 事件模式和類型](reference-eventbridge-events.md)。

**Topics**
+ [誰應該使用Change Calendar？](#systems-manager-change-calendar-who)
+ [Change Calendar 的優點](#systems-manager-change-calendar-benefits)
+ [設定 Change Calendar](systems-manager-change-calendar-prereqs.md)
+ [使用 Change Calendar](systems-manager-change-calendar-working.md)
+ [正在新增 Change Calendar 依賴性到自動化 Runbook](systems-manager-change-calendar-automations.md)
+ [Change Calendar 疑難排解](change-calendar-troubleshooting.md)

# 設定 Change Calendar
<a name="systems-manager-change-calendar-prereqs"></a>

在 中使用 工具之前Change Calendar，請先完成下列操作 AWS Systems Manager。

## 安裝最新的命令列工具
<a name="change-calendar-prereqs-tools"></a>

安裝最新的命令列工具，以取得與行事曆相關的狀態資訊。


| 需求 | Description | 
| --- | --- | 
|  AWS CLI  |  （選用） 若要使用 AWS Command Line Interface (AWS CLI) 取得行事曆的狀態資訊，請在本機 AWS CLI 電腦上安裝最新版本的 。 如需如何安裝或升級 CLI 的詳細資訊，請參閱《[AWS CLI使用者指南](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-install.html)》中的*安裝、更新和解除安裝AWS Command Line Interface *。  | 
|  AWS Tools for PowerShell  |  (選用) 若要使用 Tools for PowerShell 取得與行事曆相關的狀態資訊，請在本機電腦上安裝最新版本的 Tools for PowerShell。 如需如何安裝或升級 Tools for PowerShell 的詳細資訊，請參閱《*AWS Tools for PowerShell 使用者指南*》中的[安裝 AWS Tools for PowerShell](https://docs.aws.amazon.com/powershell/latest/userguide/pstools-getting-set-up.html)。  | 

## 設定許可
<a name="change-calendar-prereqs-permissions"></a>

如果使用者、群組或角色受獲指派管理員許可，則您可以完整存取 Change Calendar。如果您沒有管理員許可，則管理員必須指派 `AmazonSSMFullAccess` 受管政策或指派提供所需許可的政策給使用者、群組或角色，藉此給予您許可。

使用 Change Calendar 需要以下許可。

**Change Calendar 項目**  
若要建立、更新或刪除 Change Calendar 項目 (包含從項目新增或移除事件)，則連接至您的使用者、群組或角色的政策必須允許以下動作。  
+ `ssm:CreateDocument`
+ `ssm:DeleteDocument`
+ `ssm:DescribeDocument`
+ `ssm:DescribeDocumentPermission`
+ `ssm:GetCalendar`
+ `ssm:ListDocuments`
+ `ssm:ModifyDocumentPermission`
+ `ssm:PutCalendar`
+ `ssm:UpdateDocument`
+ `ssm:UpdateDocumentDefaultVersion`

**行事曆狀態**  
若要取得目前或即將變更的行事曆狀態，則連接至您的使用者、群組或角色的政策必須允許以下動作。  
+ `ssm:GetCalendarState`

**操作事件**  
若要檢視操作事件 (例如維護時段、關聯及計劃的自動化)，連接至您的使用者、群組或角色的政策必須允許以下動作：  
+ `ssm:DescribeMaintenanceWindows`
+ `ssm:DescribeMaintenanceWindowExecution`
+ `ssm:DescribeAutomationExecutions`
+ `ssm:ListAssociations`

**注意**  
他人擁有 (也就是他人建立) 的 Change Calendar 項目僅供唯讀，即便與您的帳戶分享也是如此。維護時段、State Manager 關聯和自動化不會共用。

# 使用 Change Calendar
<a name="systems-manager-change-calendar-working"></a>

您可以使用 AWS Systems Manager 主控台來新增、管理或刪除 Change Calendar (AWS Systems Manager 中的工具) 中的項目。您也可以匯入支援的第三方行事曆供應商的事件，方法是匯入您從來源行事曆匯出的 iCalendar (`.ics`) 檔案。另外，您可以使用 `GetCalendarState` API 操作或 `get-calendar-state` AWS Command Line Interface (AWS CLI) 命令，從而獲取在特定時間的 Change Calendar 相關資訊。

**Topics**
+ [建立變更行事曆](change-calendar-create.md)
+ [在 Change Calendar 中建立和管理事件](change-calendar-events.md)
+ [從第三方行事曆中匯入及管理事件](third-party-events.md)
+ [更新變更行事曆](change-calendar-update.md)
+ [共用變更行事曆](change-calendar-share.md)
+ [刪除變更行事曆](change-calendar-delete.md)
+ [取得變更行事曆的狀態](change-calendar-getstate.md)

# 建立變更行事曆
<a name="change-calendar-create"></a>

您在 Change Calendar (AWS Systems Manager 中的工具) 中建立項目時，就是在建立使用 `text` 格式的 Systems Manager 文件 (SSM 文件)。

**若要建立變更行事曆**

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. 在導覽窗格中，選擇 **Change Calendar**。

1. 選擇 **Create calendar (建立行事曆)**。

   -或-

   如果先開啟 **Change Calendar** 首頁，則選擇 **Create change calendar** (建立變更行事曆)。

1. 在 **Create instance (建立行事曆)** 頁面上的 **Calendar details (行事曆詳細資料)** 中，輸入行事曆項目的名稱。行事曆名稱可包含字母、數字、句點、破折號和底線。請使用足夠特別的名稱，以便迅速辨識行事曆項目的用途。例如，**support-off-hours**。建立行事曆項目後就無法更新此名稱。

1. (選用) 在 **Description** (描述) 中，輸入行事曆項目的描述。

1. (選用) 在 **Import calendar** (匯入行事曆) 區域中，選擇 **Choose file** (選擇檔案)，以選取您從第三方行事曆供應商匯出的 iCalendar (`.ics`) 檔案。匯入檔案會將其事件新增至您的行事曆。

   支援的供應商包括 Google 行事曆、Microsoft Outlook 和 iCloud 行事曆。

   如需更多詳細資訊，請參閱 [從第三方行事曆供應商匯入事件](change-calendar-import.md)。

1. 在 **Calendar type (行事曆類型)** 中，選擇以下其中一項。
   + **Open by default** (預設開啟) - 行事曆會開啟 (事件開始後可執行自動化動作)，接著在相關活動進行期間關閉。
   + **Closed by default** (預設關閉) - 行事曆會關閉 (事件開始後可執行自動化動作)，但會在相關活動進行期間開啟。

1. (選用) 在**變更管理事件**中，選取**將變更管理事件新增至行事曆**。此選項會在每月行事曆顯示畫面中顯示所有已排程的維護時段、State Manager 關聯、Automation 工作流程及 Change Manager 變更請求。
**提示**  
如果您稍後想要從行事曆顯示中永久移除這些事件類型，請編輯行事曆，取消選取此核取方塊，然後選擇**儲存**。

1. 選擇 **Create calendar (建立行事曆)**。

   建立行事曆項目後，Systems Manager 會在 **Change Calendar** 清單中顯示行事曆項目。欄位會顯示行事曆版本和行事曆擁有者的 AWS 帳戶 帳戶編號。除非您至少建立或匯入一個事件，否則行事曆將無法禁止或允許任何動作。如需建立事件的資訊，請參閱 [建立 Change Calendar 事件](change-calendar-create-event.md)。如需匯入事件的相關資訊，請參閱 [從第三方行事曆供應商匯入事件](change-calendar-import.md)。

# 在 Change Calendar 中建立和管理事件
<a name="change-calendar-events"></a>

在 中建立行事曆後 AWS Systems Manager Change Calendar，您可以建立、更新和刪除已開啟或已關閉行事曆中包含的事件。 Change Calendar 是 中的工具 AWS Systems Manager。

**提示**  
作為直接在 Systems Manager 主控台中建立事件的替代方案，您可以從支援的第三方行事曆應用程式匯入 iCalendar (`.ics`) 檔案。如需相關資訊，請參閱[從第三方行事曆中匯入及管理事件](third-party-events.md)。

**Topics**
+ [建立 Change Calendar 事件](change-calendar-create-event.md)
+ [更新 Change Calendar 事件](change-calendar-update-event.md)
+ [刪除Change Calendar事件](change-calendar-delete-event.md)

# 建立 Change Calendar 事件
<a name="change-calendar-create-event"></a>

當您將事件新增至 Change Calendar (AWS Systems Manager 中的工具) 中的項目時，就會指定行事曆項目預設動作暫停的時段。舉例來說，如果行事曆項目類型預設為關閉，則行事曆會在事件進行期間開放變更。(您也可以建立建議事件，其僅在行事曆上發揮提供資訊的作用。)

目前您只能使用主控台來建立 Change Calendar 事件。事件會新增到您在建立 Change Calendar 項目時所建立的 Change Calendar 文件。

**若要建立 Change Calendar 事件**

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. 在導覽窗格中，選擇 **Change Calendar**。

1. 在行事曆清單中，請為您要新增事件的行事曆項目選擇名稱。

1. 在行事曆項目的詳細資料頁面上選擇 **Create event (建立事件)**。

1. 在 **Create scheduled event (建立排程事件)** 頁面的 **Event details (事件詳細資料)** 中，輸入事件的顯示名稱。事件名稱可包含字母、數字、句點、破折號和底線。請使用足夠特別的名稱，以便辨識事件的用途。例如，**nighttime-hours**。

1. 在 **Description** (描述) 中，輸入事件的描述。例如 **The support team isn't available during these hours**。

1. (選用) 如果希望此事件僅用作視覺通知或提醒，可選取 **Advisory** (建議) 核取方塊。建議事件不會在行事曆上發揮任何作用，僅為檢視行事曆的使用者提供資訊。

1. 在 **Event start date** (事件開始日期) 中，以 `MM/DD/YYYY` 格式輸入或選擇事件的開始日期，再以 `hh:mm:ss` (時分秒) 格式輸入指定日期的時間作為事件的開始時間。

1. 在 **Event end date** (事件結束日期) 中，以 `MM/DD/YYYY` 格式輸入或選擇事件的結束日期，再以 `hh:mm:ss` (時分秒) 格式輸入指定日期的時間作為事件的結束時間。

1. 在 **Schedule time zone** (排程時區) 中，選擇事件開始和結束時間適用的時區。您可以輸入城市的部分名稱，或是格林威治標準時間 (GMT) 以外的時區，以便更快找到時區。預設值是國際標準時間 (UTC)。

1. (選用) 如果要建立每天、每週或每月循環發生的事件，請開啟 **Recurrence** (循環)，然後指定循環的頻率和選用的結束日期。

1. 選擇 **Create scheduled event (建立排程事件)**。新的事件會新增到您的行事曆項目，且會顯示在行事曆項目詳細資料頁面的 **Events (事件)** 標籤上。

# 更新 Change Calendar 事件
<a name="change-calendar-update-event"></a>

使用下列程序更新 AWS Systems Manager 主控台中的 Change Calendar 事件。Change Calendar 是 AWS Systems Manager 中的工具。

**若要更新 Change Calendar 事件**

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. 在導覽窗格中，選擇 **Change Calendar**。

1. 在行事曆清單中，請為您要編輯事件的行事曆項目選擇名稱。

1. 在行事曆項目的詳細資料頁面上選擇 **Events (事件)**。

1. 在行事曆頁面中選擇您要編輯的事件。
**提示**  
使用左上角的按鈕來往後或往前一年，或是往後或往前一個月。如果有需要，可以從右上角的清單選擇正確的時區來變更時區。

1. 在 **Event details** (事件詳細資訊) 中選擇 **Edit** (編輯)。

   若要變更事件名稱和描述，請新增或替換目前文字值。

1. 若要變更 **Event start date** (事件開始日期) 值，請選擇目前開始日期，然後從行事曆中選擇一個新日期。若要變更開始時間，請選擇目前開始時間，然後從清單中選擇一個新時間。

1. 若要變更 **Event end date** (事件結束日期) 值，請選擇目前日期，然後從行事曆中選擇一個新的結束日期。若要變更結束時間，請選擇目前結束時間，然後從清單中選擇一個新時間。

1. 若要變更 **Schedule time zone** (排程時區) 值，請選擇事件開始和結束時間適用的時區。您可以輸入城市的部分名稱，或是格林威治標準時間 (GMT) 以外的時區，以便更快找到時區。預設值是國際標準時間 (UTC)。

1. (選用) 如果希望此事件僅用作視覺通知或提醒，可選取 **Advisory** (建議) 核取方塊。建議事件不會在行事曆上發揮任何作用，僅為檢視行事曆的使用者提供資訊。

1. 選擇**儲存**。您的變更會顯示在行事曆項目詳細資料頁面的 **Events (事件)** 標籤上。選擇您更新的事件來檢視變更。

# 刪除Change Calendar事件
<a name="change-calendar-delete-event"></a>

您可以使用 AWS 管理主控台在 Change Calendar (AWS Systems Manager 中的工具) 中逐一刪除事件。

**提示**  
如果您在建立行事曆時選取了**將變更管理事件新增至行事曆**，您可以執行下列動作：  
若要*暫時*隱藏行事曆顯示中的某個變更管理事件類型，請在每月預覽最上方針對該類型選擇 **X**。
若要從行事曆顯示中*永久*移除這些類型，請編輯行事曆，取消選取**將變更管理事件新增至行事曆**核取方塊，然後選擇**儲存**。從行事曆顯示中移除類型並不會將其從您的帳戶中刪除。

**若要刪除 Change Calendar 事件**

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. 在導覽窗格中，選擇 **Change Calendar**。

1. 在行事曆清單中，請選擇您要從中刪除事件的行事曆項目名稱。

1. 在行事曆項目的詳細資料頁面上選擇 **Events (事件)**。

1. 在行事曆頁面中選擇您要刪除的事件。
**提示**  
使用左上角的按鈕來將行事曆往後或往前一年，或是往後或往前一個月。如果有需要，可以從右上角的清單選擇正確的時區來變更時區。

1. 在 **Event details (事件詳細資料)** 頁面上，選擇 **Delete (刪除)**。當系統提示您確認是否要刪除事件時，請選擇 **Confirm** (確認)。

# 從第三方行事曆中匯入及管理事件
<a name="third-party-events"></a>

除了直接在 AWS Systems Manager 主控台中建立事件外，您也可以從支援的第三方行事曆應用程式匯入 iCalendar (`.ics`) 檔案。您的行事曆可以同時包含匯入的事件和您在 Change Calendar ( AWS Systems Manager中的工具) 中建立的事件。

**開始之前**  
在您嘗試匯入行事曆檔案之前，請先檢閱以下要求與限制：

行事曆檔案格式  
僅支援有效的 iCalendar 檔案 (`.ics`)。

支援的行事曆供應商  
僅支援從下列第三方行事曆供應商匯出的`.ics`檔案：  
+ Google 行事曆 ([匯出指示](https://support.google.com/calendar/answer/37111))
+ Microsoft Outlook ([匯出指示](https://support.microsoft.com/en-us/office/export-an-outlook-calendar-to-google-calendar-662fa3bb-0794-4b18-add8-9968b665f4e6))
+ iCloud 行事曆 ([匯出指示](https://support.apple.com/guide/calendar/import-or-export-calendars-icl1023/mac))

檔案大小  
您可以匯入任意數量的有效 `.ics` 檔案。不過，每個行事曆的所有匯入檔案大小總計不得超過 64KB。  
若要將 `.ics` 檔案的大小減至最小，請確定您只匯出行事曆項目的基本詳細資訊。必要時，請縮短要匯出的時間長度。

時區  
除了行事曆名稱、行事曆供應商和至少一個事件之外，您匯出的 `.ics` 檔案也應指出行事曆的時區。如果沒有，或是識別時區時發生問題，系統會在匯入檔案後提示您指定時區。

重複事件限制  
匯出的 `.ics` 檔案可以包含重複事件。不過，如果在來源行事曆中刪除重複事件的一個或多個事件，匯入就會失敗。

**Topics**
+ [從第三方行事曆供應商匯入事件](change-calendar-import.md)
+ [從第三方行事曆供應商更新所有事件](change-calendar-import-add-remove.md)
+ [刪除從第三方行事曆匯入的所有事件](change-calendar-delete-ics.md)

# 從第三方行事曆供應商匯入事件
<a name="change-calendar-import"></a>

使用以下程序可從支援的第三方行事曆應用程式匯入 iCalendar (`.ics`) 檔案。檔案中包含的事件會納入開啟或關閉行事曆的規則中。您可以將檔案匯入到您正在使用 Change Calendar ( AWS Systems Manager中的工具) 建立的新行事曆或現有的行事曆。

匯入 `.ics` 檔案之後，您可以使用 Change Calendar 介面從其中移除個別事件。如需相關資訊，請參閱[刪除Change Calendar事件](change-calendar-delete-event.md)。您也可以透過刪除 `.ics` 檔案，來刪除來源行事曆中的所有事件。如需相關資訊，請參閱[刪除從第三方行事曆匯入的所有事件](change-calendar-delete-ics.md)。

**若要從第三方行事曆供應商匯入事件**

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

1. 在導覽窗格中，選擇 **Change Calendar**。

1. 若要從新的行事曆開始，請選擇 **Create calendar** (建立行事曆)。在 **Import calendar** (匯入行事曆) 區域中，選擇 **Choose file** (選擇檔案)。如需有關建立新行事曆的其他步驟的資訊，請參閱 [建立變更行事曆](change-calendar-create.md)。

   -或-

   若要將第三方事件匯入現有的行事曆，請選擇現有行事曆的名稱加以開啟。

1. 選擇 **Actions, Edit** (動作：編輯)，然後在 **Import calendar** (匯入行事曆) 區域中選擇 **Choose file** (選擇檔案)。

1. 導覽並選取本機電腦上匯出的 `.ics` 檔案。

1. 如果出現提示，對於 **Select a time zone** (選取時區)，選取要套用至行事曆的時區。

1. 選擇**儲存**。

# 從第三方行事曆供應商更新所有事件
<a name="change-calendar-import-add-remove"></a>

如果在您匯入其 iCalendar `.ics` 檔案之後，將多個事件新增至來源行事曆或從來源行事曆中移除事件，則您可以在 Change Calendar 中反映這些變更。首先，重新匯出來源行事曆，然後將新檔案匯入到 Change Calendar ( AWS Systems Manager中的工具)。變更行事曆中的事件將會更新，以反映較新檔案的內容。

**若要從第三方行事曆供應商更新所有事件**

1. 在您的第三方行事曆中，新增或移除您想要反映在 Change Calendar 中的事件，然後再將行事曆重新匯出至新的 `.ics` 檔案。

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

1. 在導覽窗格中，選擇 **Change Calendar**。

1. 從行事曆清單中，從清單中選擇行事曆名稱。

1. 選擇**選擇檔案**，然後導覽並選取替代 `.ics` 檔案。

1. 若要回應有關覆寫現有檔案的通知，請選擇 **Confirm** (確認)。

# 刪除從第三方行事曆匯入的所有事件
<a name="change-calendar-delete-ics"></a>

如果您不再希望從第三方供應商匯入的任何事件包含在行事曆中，您可以刪除已匯入的 iCalendar `.ics` 檔案。

**若要刪除從第三方行事曆匯入的所有事件**

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

1. 在導覽窗格中，選擇 **Change Calendar**。

1. 從行事曆清單中，從清單中選擇行事曆名稱。

1. 在 **Import calendar** (匯入行事曆) 區域中的 **My imported calendars** (我匯入的行事曆)，找出匯入行事曆的名稱，然後選擇卡上的 **X**。

1. 選擇**儲存**。

# 更新變更行事曆
<a name="change-calendar-update"></a>

您可以更新變更行事曆的描述，但無法更新其名稱。您雖然可以變更行事曆的預設狀態，但是請注意，這會使行事曆相關事件進行期間的變更動作行為發生反轉。舉例來說，如果您將行事曆的狀態從 **Open by default** (預設開啟) 變更為 **Closed by default** (預設關閉)，那麼如果有建立相關事件的使用者不知道變更，就可能做出不必要的變更。

您更新變更行事曆時，就是在編輯您在建立項目時所建立的 Change Calendar 文件。Change Calendar 是 AWS Systems Manager 中的工具。

**若要更新變更行事曆**

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. 在導覽窗格中，選擇 **Change Calendar**。

1. 在行事曆清單中，請選擇您要更新的行事曆名稱。

1. 在行事曆的詳細資訊頁面上，選擇 **Actions, Edit** (動作：編輯)。

1. 您可以在 **Description (描述)** 中變更描述文字。您無法編輯變更行事曆的名稱。

1. 如果要變更行事曆狀態，請在 **Calendar type (行事曆類型)** 中選擇其他值。請注意，這會使行事曆相關事件進行期間的變更動作行為發生反轉。變更行事曆類型之前，您應該和其他 Change Calendar 使用者確認變更行事曆類型並不會在他們所建立的活動進行時出現不必要的變更。
   + **Open by default** (預設開啟) - 行事曆會開啟 (事件開始後可執行自動化動作)，接著在相關活動進行期間關閉。
   + **Closed by default** (預設關閉) - 行事曆會關閉 (事件開始後可執行自動化動作)，但會在相關活動進行期間開啟。

1. 選擇**儲存**。

   除非您至少新增一個事件，否則行事曆將無法禁止或允許任何動作。如需有關如何新增事件的資訊，請參閱[建立 Change Calendar 事件](change-calendar-create-event.md)。

# 共用變更行事曆
<a name="change-calendar-share"></a>

透過使用 AWS Systems Manager 主控台，您可以在 Change Calendar (AWS Systems Manager 中的工具) 中與其他 AWS 帳戶共用行事曆。共用行事曆時，行事曆僅供共用帳戶內的使用者唯讀。維護時段、State Manager 關聯和自動化不會共用。

**若要共用變更行事曆**

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. 在導覽窗格中，選擇 **Change Calendar**。

1. 在行事曆清單中，請選擇您要共用的行事曆名稱。

1. 在行事曆的詳細資訊頁面上，選擇 **Share** (共用) 索引標籤。

1. 選擇 **Actions, Share** (動作：共用)。

1. 在 **Share calendar** (共用行事曆) 中，針對 **Account ID** (帳戶 ID)，輸入有效 AWS 帳戶 的 ID 編號，然後選擇 **Share** (共用)。

   共用帳戶的使用者可以讀取變更行事曆，但無法進行變更。

# 刪除變更行事曆
<a name="change-calendar-delete"></a>

您可以透過使用 Systems Manager 主控台或 AWS Command Line Interface (AWS CLI)，刪除 Change Calendar (AWS Systems Manager 中的工具) 中的行事曆。刪除變更行事曆也會刪除所有相關事件。

**若要刪除變更行事曆**

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. 在導覽窗格中，選擇 **Change Calendar**。

1. 在行事曆清單中，請選擇您要刪除的行事曆名稱。

1. 在行事曆的詳細資訊頁面上，選擇 **Actions, Delete** (動作：刪除)。當系統提示您確認是否要刪除行事曆時，請選擇 **Delete** (刪除)。

# 取得變更行事曆的狀態
<a name="change-calendar-getstate"></a>

您可以在 Change Calendar ( AWS Systems Manager中的工具) 中，取得行事曆的整體狀態，或特定時間的行事曆狀態。您也可以取得下次行事曆狀態從 `OPEN` 變更為 `CLOSED` 的時間，反之亦然。

**注意**  
如需有關 Change Calendar 與 Amazon EventBridge 整合以自動監控行事曆狀態變更的資訊，請參閱 [Change Calendar 與 Amazon EventBridge 整合](monitoring-systems-manager-event-examples.md#change-calendar-eventbridge-integration)。EventBridge 整合會在行事曆狀態轉換時提供事件驅動通知，補充 `GetCalendarState` API 動作的輪詢型方法。

您可以使用 `GetCalendarState` API 操作來執行這項任務。本節中的程序使用 AWS Command Line Interface (AWS CLI)。

**若要取得變更行事曆的狀態**
+ 請執行以下命令，來取得一或多個行事曆在特定時間的狀態。`--calendar-names` 參數是必要項目，`--at-time` 則為選用參數。將每個*範例資源預留位置*取代為您自己的資訊。

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

  ```
  aws ssm get-calendar-state \
      --calendar-names "Calendar_name_or_document_ARN_1" "Calendar_name_or_document_ARN_2" \
      --at-time "ISO_8601_time_format"
  ```

  下列是 範例。

  ```
  aws ssm get-calendar-state \
      --calendar-names "arn:aws:ssm:us-east-2:123456789012:document/MyChangeCalendarDocument" "arn:aws:ssm:us-east-2:123456789012:document/SupportOffHours" \
      --at-time "2020-07-30T11:05:14-0700"
  ```

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

  ```
  aws ssm get-calendar-state ^
      --calendar-names "Calendar_name_or_document_ARN_1" "Calendar_name_or_document_ARN_2" ^
      --at-time "ISO_8601_time_format"
  ```

  下列是 範例。

  ```
  aws ssm get-calendar-state ^
      --calendar-names "arn:aws:ssm:us-east-2:123456789012:document/MyChangeCalendarDocument" "arn:aws:ssm:us-east-2:123456789012:document/SupportOffHours" ^
      --at-time "2020-07-30T11:05:14-0700"
  ```

------

  該命令會傳回相關資訊，如以下所示。

  ```
  {
      "State": "OPEN",
      "AtTime": "2020-07-30T16:18:18Z",
      "NextTransitionTime": "2020-07-31T00:00:00Z"
  }
  ```

  結果會顯示您帳戶擁有 (或與您帳戶共用) 的行事曆狀態 (行事曆類型為 `DEFAULT_OPEN` 或 `DEFAULT_CLOSED`，並且以 `--at-time` 的值指定時間)，以及下一次轉換的時間。如果您不新增 `--at-time` 參數，就會使用目前的時間。
**注意**  
如果您在請求中指定多個行事曆，此命令僅會在請求中的所有行事曆均開啟的情況下傳回 `OPEN` 的狀態。如果請求中的一或多個行事曆已關閉，則傳回的狀態為 `CLOSED`。

# 正在新增 Change Calendar 依賴性到自動化 Runbook
<a name="systems-manager-change-calendar-automations"></a>

若要讓自動化動作遵循 Change Calendar中的工具 AWS Systems Manager，請在使用 [`aws:assertAwsResourceProperty`](automation-action-assertAwsResourceProperty.md)動作的 Automation Runbook 中新增步驟。設定要執行 `GetCalendarState` 的動作，來驗證指定的行事曆項目是否處於您希望的狀態 (`OPEN` 或 `CLOSED`)。只有在行事曆狀態為 `OPEN` 時，自動化 Runbook 才可以繼續進行下一個步驟。下列內容是 YAML 的範例摘錄，其中的自動化 Runbook 無法繼續進行下一個步驟 (`LaunchInstance`)，除非行事曆狀態符合 `DesiredValues` 中指定的 `OPEN` 行事曆狀態才可以。

下列是 範例。

```
mainSteps:
  - name: MyCheckCalendarStateStep
    action: 'aws:assertAwsResourceProperty'
    inputs:
      Service: ssm
      Api: GetCalendarState
      CalendarNames: ["arn:aws:ssm:us-east-2:123456789012:document/SaleDays"]
      PropertySelector: '$.State'
      DesiredValues:
      - OPEN
    description: "Use GetCalendarState to determine whether a calendar is open or closed."
    nextStep: LaunchInstance
  - name: LaunchInstance
    action: 'aws:executeScript'
    inputs:
      Runtime: python3.11 
...
```

# Change Calendar 疑難排解
<a name="change-calendar-troubleshooting"></a>

使用下列資訊以協助您對 Change Calendar ( AWS Systems Manager中的工具) 的問題進行疑難排解。

**Topics**
+ ['Calendar import failed' ('行事曆匯入失敗') 錯誤](#change-manager-troubleshooting-1)

## 'Calendar import failed' ('行事曆匯入失敗') 錯誤
<a name="change-manager-troubleshooting-1"></a>

**問題**：當匯入 iCalendar (`.ics`) 檔案時，系統會報告行事曆匯入失敗。
+ **解決方案 1** – 確定您正在匯入從支援的第三方行事曆供應商匯出的檔案，其中包括下列各項：
  + Google 行事曆 ([匯出指示](https://support.google.com/calendar/answer/37111))
  + Microsoft Outlook ([匯出指示](https://support.microsoft.com/en-us/office/export-an-outlook-calendar-to-google-calendar-662fa3bb-0794-4b18-add8-9968b665f4e6))
  + iCloud 行事曆 ([匯出指示](https://support.apple.com/guide/calendar/import-or-export-calendars-icl1023/mac))
+ **解決方案 2** – 如果您的來源行事曆包含任何重複事件，請確定未取消或刪除任何個別事件。目前，Change Calendar 不支援匯入具有個別取消的重複事件。若要解決這個問題，請從來源行事曆中移除重複事件、重新匯出行事曆並將它重新匯入 Change Calendar，然後使用 Change Calendar 介面新增重複事件。如需相關資訊，請參閱[建立 Change Calendar 事件](change-calendar-create-event.md)。
+ **解決方案 3** – 確定您的來源行事曆包含至少一個事件。上傳不包含事件的 `.ics` 檔案不會成功。
+ **解決方案 4** – 如果系統報告，因為 `.ics` 太大而匯入失敗，則請確定您只匯出行事曆項目的基本詳細資訊。必要時，請縮短您匯出的時間段長度。
+ **解決方案 5** – 如果當您嘗試從 **Events** (事件) 標籤匯入時，Change Calendar 無法判斷匯出的行事曆的時區，您可能會收到此訊息："Calendar import failed. Change Calendar couldn't locate a valid time zone。You can import the calendar from the Edit menu." (行事曆匯入失敗。Change Calendar 無法找到有效時區。您可以從編輯選單中匯入行事曆。) 在此情況下，請依次選擇 **Actions, Edit** (動作、編輯)，然後嘗試從 **Edit calendar** (編輯行事曆) 頁面匯入檔案。
+ **解決方案 6** – 請勿在匯入之前編輯 `.ics` 檔案。嘗試修改檔案內容可能會損毀行事曆資料。如果您在嘗試匯入之前已修改檔案，請再次從來源行事曆匯出行事曆，然後重新嘗試上傳。

# AWS Systems Manager Change Manager
<a name="change-manager"></a>

**Change Manager 可用性變更**  
AWS Systems Manager Change Manager 自 2025 年 11 月 7 日起，不再向新客戶開放。如果您想要使用 Change Manager，請在該日期之前註冊。現有客戶可以繼續正常使用該服務。如需詳細資訊，請參閱[AWS Systems Manager Change Manager可用性變更](https://docs.aws.amazon.com/systems-manager/latest/userguide/change-manager-availability-change.html)。

Change Manager是 中的工具 AWS Systems Manager，是一種企業變更管理架構，用於請求、核准、實作和報告應用程式組態和基礎設施的操作變更。從單一*委派管理員帳戶*，如果您使用 AWS Organizations，您可以管理跨多個 AWS 帳戶 和多個 的變更 AWS 區域。或使用*本機帳戶*，您可以管理單一 AWS 帳戶的變更。使用 Change Manager 管理 AWS 資源和內部部署資源的變更。若要開始使用 Change Manager，請開啟 [Systems Manager 主控台](https://console.aws.amazon.com//systems-manager/change-manager)。在導覽窗格中，選擇 **Change Manager**。

透過 Change Manager，您可以使用預先核准的*變更範本*，協助自動化資源的變更程序，並協助避免在進行操作變更時的意外結果。每個變更範本可指定下列項目：
+ 建立變更請求時，可供使用者選擇的一個或多個 Automation Runbook。對資源所做的變更會在 Automation Runbook 中進行定義。您可以在您建立的變更範本中包含自訂 Runbook 或 [AWS 受管 Runbook](automation-documents-reference.md)。當使用者建立變更請求時，他們可以選擇要在請求中包含哪一個可用 Runbook。此外，您可以建立變更範本，讓提出請求的使用者指定變更請求中的任何 Runbook。
+ 帳戶中使用者，必須檢閱使用該變更範本提出的變更請求。
+ Amazon Simple Notification Service (Amazon SNS) 主題，用於通知指派的核准者變更請求已準備好進行審核。
+ Amazon CloudWatch 警示，用於監控 Runbook 工作流程。
+ Amazon SNS 主題，用於針對使用變更範本建立的變更請求傳送狀態變更通知。
+ 要套用至變更範本的標籤，以便用於分類和篩選變更範本。
+ 是否可以在沒有核准步驟的情況下執行從變更範本建立的變更請求 (自動核准的請求)。

透過與 Systems Manager 中的另一個工具 整合Change Calendar， Change Manager也可協助您安全地實作變更，同時避免與重要業務事件的排程衝突。 與 Change Manager整合， AWS Organizations AWS IAM Identity Center 並協助您使用現有的身分管理系統，從單一帳戶管理整個組織的變更。您可以從 Change Manager 監控變更進度和稽核整個組織的操作變更，提供更好的可見性和責任。

Change Manager 補充了您的[持續整合](https://aws.amazon.com/devops/continuous-integration) (CI) 實務和[持續交付](https://aws.amazon.com/devops/continuous-delivery) (CD) 方法論的安全控制。Change Manager 不適用於作為自動發行程序 (例如 CI/CD 管道) 的所做的變更，除非有例外狀況或需要核准。

## Change Manager 的運作方式
<a name="how-change-manager-works"></a>

識別出標準或緊急操作變更的需求時，組織中的某個人會根據為您的組織或帳戶中建立的其中一個變更範本來建立變更請求。

如果請求的變更需要手動核准，Change Manager 會透過 Amazon SNS 通知來通知指定的核准者變更請求已準備好進行審核。您可以在變更範本中為變更請求指定核准者，或讓使用者指定變更請求本身的核准者。您可以為不同的範本指派不同的檢閱者。例如，指派一個使用者、使用者群組或 AWS Identity and Access Management (IAM) 角色，其必須核准受管節點的變更請求，以及針對資料庫變更核准其他使用者、群組或 IAM 角色。如果變更範本允許自動核准，且請求者的使用者政策未禁止此操作，則使用者也可以選擇針對其請求執行 Automation 執行手冊，而不需要檢閱步驟 (除變更凍結事件外)。

對於每個變更範本，您最多可以新增五個核准者層級。例如，您可能需要技術檢閱者先核准從變更範本中建立的變更請求，然後再請求一位或多位經理的第二層核准。

Change Manager 已與 [AWS Systems Manager Change Calendar](systems-manager-change-calendar.md) 整合。核准請求的變更後，系統會先決定請求是否與其他排定的企業活動衝突。如果偵測到衝突，Change Manager 可以封鎖變更，或在啟動 Runbook 工作流程之前需要其他核准。例如，您可能只允許在上班時間進行變更，以確保團隊可以管理任何未預期的問題。對於請求在這些時間以外執行的任何變更，您可以*變更凍結核准者*的形式要求更高層級的管理核准。如需緊急變更，Change Manager 可以跳過檢查 Change Calendar 的步驟，以獲得核准變更請求之後的衝突或封鎖事件。

當需要實作核准的變更時，Change Manager 會執行關聯的變更請求中指定的自動化 Runbook。執行 Runbook 工作流程時，只允許在核准的變更請求中定義的操作。這種方法有助於避免實作變更時的意外的結果。

除了限制執行 Runbook 工作流程時可以進行的變更之外，Change Manager 也可以幫助您控制並發和錯誤閾值。您可以選擇 Runbook 工作流程一次可以執行多少資源、一次可以在多少個帳戶中執行變更戶，以及在停止程序之前允許失敗和復原 (如果 Runbook 包含回復指令碼) 多少次。您也可以使用 CloudWatch 警示監控變更的進度。

Runbook 工作流程完成後，您可以檢閱所做變更的詳細資訊。這些詳細資訊包括變更請求的原因、使用的變更範本、請求和核准變更的人員，以及如何實作變更。

**詳細資訊**  
在 *AWS 新聞部落格*上[介紹 AWS Systems ManagerChange Manager](https://aws.amazon.com/blogs/aws/introducing-systems-manager-change-manager/)

## Change Manager 對我的營運有何好處？
<a name="change-manager-benefits"></a>

Change Manager 的優點包括：
+ **降低服務中斷和停機的風險**

  Change Manager 可以確保在執行 Runbook 工作流程時，只會實作核准的變更，進而更安全地進行操作變更。您可以封鎖未計劃和未檢閱的變更。Change Manager 可協助您避免因人為錯誤造成的意外結果類型，而這些結果需要花費昂貴的時間進行研究和回溯。
+ **取得變更記錄的詳細稽核與報告**

  Change Manager 提供責任制，以一致的方式報告和稽核整個組織所做的變更、變更的意圖，以及核准和實作變更的人員的詳細資訊。
+ **避免排程衝突或違規**

  Change Manager 可以根據您組織的作用中變更行事曆，偵測排程衝突，例如假日事件或新產品啟動。您可以允許 Runbook 工作流程僅在上班時間執行，或只允許其他核准。
+ **根據不斷變化的業務調整變更需求**

  在不同的業務期間，您可以實作不同的變更管理需求。例如，在月底報告、稅季或其他重要業務期間，您可以封鎖變更，或需要主管層級的核准才能進行可能造成不必要的營運風險的變更。
+ **集中管理不同帳戶的變更**

  透過與 Organizations 整合，Change Manager 可讓您從單一委派系統管理員帳戶管理所有組織單位 (OU) 的變更。您可以開啟 Change Manager 用於整個組織，或僅搭配部分 OU 使用。

## 誰應該使用Change Manager？
<a name="change-manager-who"></a>

Change Manager 適用於下列 AWS 客戶和組織：
+ 任何想要改善對其雲端或內部部署環境進行操作變更的安全性和管控 AWS 的客戶。
+ 想要提高團隊之間的協作和可見性的 Organizations，可藉由避免停機來改善應用程式可用性，以及降低手動和重複工作的相關風險。
+ Organizations 必須遵守變更管理的最佳實務。
+ 需要對其應用程式組態和基礎設施所做變更的完整可稽核歷程記錄的客戶。

## Change Manager有哪些主要功能？
<a name="change-manager-features"></a>

Change Manager 的主要功能如下所示：
+ **變更管理最佳實務的整合式支援**

  利用 Change Manager，您可以將選取變更管理最佳實務套用至您的營運中。您可以選擇開啟以下選項：
  + 檢查 Change Calendar 以查看事件目前是否受到限制，因此只會在開啟的行事曆期間進行變更。
  + 允許在受限事件期間進行變更，並獲得變更凍結核准者的額外的核准。
  + 需要為所有變更範本指定 CloudWatch 警示。
  + 需要在您帳戶中建立的所有變更範本都經過審核和核准，才能用來建立變更請求。
+ **已關閉行事曆期間和緊急變更請求的不同核准路徑**

  您可以允許選項檢查 Change Calendar 以獲悉受限制的事件，並封鎖核准的變更請求，直到事件完成為止。但是，您還可以指定第二組核准者，即變更凍結核准者，即使行事曆已關閉，他們也可以允許執行變更。您也可以建立緊急變更範本。從緊急變更範本建立的變更請求仍需要定期核准，但不受行事曆限制，也不需要變更凍結核准。
+ **控制啟動 Runbook 工作流程的方式和時間**

  Runbook 工作流程可以根據排程啟動，或在核准完成後立即啟動 (受行事曆限制規則的約束)。
+ **內建通知支援**

  指定組織中應檢閱和核准變更範本和變更請求的人員。將 Amazon SNS 主題指派給變更範本，以將使用該變更範本建立的變更請求狀態變更通知傳送給該主題的訂閱者。
+ **與 整合 AWS Systems Manager Change Calendar**

  Change Manager 允許管理員限制在指定時間段內的排程變更。例如，您可以建立政策，只允許在營業時間進行變更，以確保團隊能夠處理任何問題。您也可以在重要的業務事件期間限制變更。例如，零售業務可能會限制大型銷售活動期間的變更。您也可以要求在限制期間進行額外的核准。
+ **與 AWS IAM Identity Center 和 Active Directory 整合支援**

  藉助 IAM Identity Center 整合，您組織的成員可以存取 AWS 帳戶 ，並根據一般使用者身分使用 Systems Manager 來管理其資源。使用 IAM Identity Center，您可以將使用者存取指派給 AWS的帳戶。

  與 Active Directory 的整合可讓您將 Active Directory 帳戶中的使用者指派為核准者，以變更為您的 Change Manager 營運建立的範本。
+ **與 Amazon CloudWatch 警示的整合**

  Change Manager 已與 CloudWatch 警示整合。Change Manager 會在 Runbook 工作流程期間接聽 CloudWatch 警示，並採取針對警示定義的任何動作 (包括傳送通知)。
+ **與 AWS CloudTrail Lake 整合**

  透過在 AWS CloudTrail Lake 中建立事件資料存放區，您可以檢視在您的帳戶或組織中執行的變更請求所做變更的可稽核資訊。儲存的事件資訊包括下列詳細資訊：
  + 執行的 API 動作
  + 針對這些動作包含的請求參數
  + 執行動作的使用者
  + 在此過程中更新的資源
+ **與 整合 AWS Organizations**

  使用 Organizations 提供的跨帳戶功能，您可以使用委派管理員帳戶來管理您組織的 OU 中的 Change Manager 營運。在您的 Organizations 管理帳戶中，您可以指定哪個帳戶要作為委派系統管理員帳戶。您也可以控制在您的哪些 OU 中可以使用 Change Manager。

## 使用 Change Manager 需要付費嗎？
<a name="change-manager-cost"></a>

是。Change Manager 均按依使用量付費的方式定價。您僅需按實際用量付費。如需詳細資訊，請參閱[AWS Systems Manager 定價](https://aws.amazon.com/systems-manager/pricing/)。

## 什麼是 Change Manager 的主要元件？
<a name="change-manager-primary-components"></a>

您用來管理組織或帳戶中變更流程的 Change Manager 元件包括下列各項：

### 委派管理員帳戶
<a name="change-manager-what-is-delegated-account"></a>

如果您在整個組織中使用 Change Manager，則會使用委派管理員帳戶。這是指定為管理跨 Systems Manager 操作活動的帳戶的 AWS 帳戶 ，包括 Change Manager。委派管理員帳戶會管理整個組織的變更活動。當您設定組織以配合 Change Manager 使用時，可以指定哪些帳號擔任此角色。委派管理員帳戶必須是指派給組織單位 (OU) 的唯一成員。如果您 AWS 帳戶 只Change Manager搭配單一 使用 ，則不需要委派的管理員帳戶。

**重要**  
如果您在整個組織中使用 Change Manager，我們建議始終從委派管理員帳戶進行變更。雖然您可以從組織中的其他帳戶進行變更，但這些變更將不會在受委派管理員帳戶中報告，也不可在其中檢視。

### 變更範本
<a name="change-manager-what-is-change-template"></a>

變更範本是 Change Manager 中的組態設定的集合，可定義必要核准、可用 Runbook 以及變更請求的通知選項等項目。

您可以要求組織或帳戶中的使用者建立的變更範本必須經過核准程序，才能使用。

Change Manager 支援兩種變更範本類型。對於根據*緊急變更範本*的已核准變更請求，即使在 Change Calendar 中有封鎖事件，也可以進行請求的變更。對於根據*標準變更範本*的已核准變更請求，如果 Change Calendar 中有封鎖事件，則無法進行請求的變更，除非獲得委派的*變更凍結事件*核准者的額外核准。

### 變更請求
<a name="change-manager-what-is-change-request"></a>

變更請求是在 中執行 Automation Runbook Change Manager的請求，以更新 AWS 或內部部署環境中的一或多個資源。變更請求是使用變更範本建立的。

當您建立變更請求時，組織或帳戶中的一個或多個核准者必須檢閱並核准該請求。如果沒有所需的核准，則不允許執行會套用您請求的變更的 Runbook 工作流程。

在系統中，變更請求是 OpsItem 中的一種類型 AWS Systems Manager OpsCenter。然而，類型 `/aws/changerequest` 的 OpsItems 不會在 OpsCenter 中顯示。作為 OpsItems，變更要求會受到與其他類型的 OpsItems 相同的強制性配額。

此外，若要以程式設計方式建立變更要求，您不要呼叫 `CreateOpsItem` API 操作。相反，您可以使用 `[https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_StartChangeRequestExecution.html](https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_StartChangeRequestExecution.html)` API 操作。不過，但相較於立即執行，變更請求必須獲得核准並且在 Change Calendar 中必須沒有任何會阻止工作流程執行的封鎖事件。當獲得核准且未封鎖行事曆 (或已授與略過封鎖行事曆事件的許可) 時，即能完成 `StartChangeRequestExecution` 動作。

### Runbook 工作流程
<a name="change-manager-what-is-runbook-workflow"></a>

Runbook 工作流程是指對雲端或內部部署環境中目標資源進行請求變更的程序。每個變更請求會指定單一的自動化 Runbook 來進行請求的變更。在授予所有必要的核准之後且 Change Calendar 中沒有封鎖事件，就會發生 Runbook 工作流程。如果變更已排定在特定的日期和時間，則 Runbook 工作流程會在排定之前開始，即使已收到所有核准且未封鎖行事曆。

**Topics**
+ [Change Manager 的運作方式](#how-change-manager-works)
+ [Change Manager 對我的營運有何好處？](#change-manager-benefits)
+ [誰應該使用Change Manager？](#change-manager-who)
+ [Change Manager有哪些主要功能？](#change-manager-features)
+ [使用 Change Manager 需要付費嗎？](#change-manager-cost)
+ [什麼是 Change Manager 的主要元件？](#change-manager-primary-components)
+ [設定 Change Manager](change-manager-setting-up.md)
+ [使用 Change Manager](working-with-change-manager.md)
+ [稽核和記錄 Change Manager 活動](change-manager-auditing.md)
+ [Change Manager 疑難排解](change-manager-troubleshooting.md)

# 設定 Change Manager
<a name="change-manager-setting-up"></a>

**Change Manager 可用性變更**  
AWS Systems ManagerChange Manager 自 2025 年 11 月 7 日起，不再向新客戶開放。如果您想要使用 Change Manager，請在該日期之前註冊。現有客戶可以繼續正常使用服務。如需詳細資訊，請參閱[AWS Systems ManagerChange Manager可用性變更](https://docs.aws.amazon.com/systems-manager/latest/userguide/change-manager-availability-change.html)。

您可以使用 中的Change Manager工具 AWS Systems Manager來管理整個組織、 中所設定 AWS Organizations或單一組織的變更 AWS 帳戶。

如果您搭配組織使用 Change Manager，則可以主題 [設定適用於組織的 Change Manager (管理帳戶)](change-manager-organization-setup.md) 開始，然後繼續前往 [設定 Change Manager 選項和最佳實務](change-manager-account-setup.md)。

如果您搭配單一帳戶使用 Change Manager，請直接前往 [設定 Change Manager 選項和最佳實務](change-manager-account-setup.md)。

**注意**  
如果您開始時是搭配單一帳戶使用 Change Manager，但該帳戶稍後會新增至 Change Manager 允許的組織單位中，則會忽略您的單一帳戶設定。

**Topics**
+ [設定適用於組織的 Change Manager (管理帳戶)](change-manager-organization-setup.md)
+ [設定 Change Manager 選項和最佳實務](change-manager-account-setup.md)
+ [設定 Change Manager 的角色和許可](change-manager-permissions.md)
+ [控制對自動核准 Runbook 工作流程的存取](change-manager-auto-approval-access.md)

# 設定適用於組織的 Change Manager (管理帳戶)
<a name="change-manager-organization-setup"></a>

**Change Manager 可用性變更**  
AWS Systems Manager Change Manager 自 2025 年 11 月 7 日起，不再向新客戶開放。如果您想要使用 Change Manager，請在該日期之前註冊。現有客戶可以繼續正常使用該服務。如需詳細資訊，請參閱[AWS Systems Manager Change Manager可用性變更](https://docs.aws.amazon.com/systems-manager/latest/userguide/change-manager-availability-change.html)。

如果您使用 中的Change Manager工具 搭配 中設定的組織 AWS Systems Manager，則此主題中的任務適用 AWS Organizations。如果您Change Manager只想將 與單一 搭配使用 AWS 帳戶，請跳至主題 [設定 Change Manager 選項和最佳實務](change-manager-account-setup.md)。

在做為 Organizations *管理帳戶的* 中 AWS 帳戶 ，執行本節中的任務。如需管理帳戶和其他 Organizations 概念的相關資訊，請參閱 [AWS Organizations 術語與概念](https://docs.aws.amazon.com/organizations/latest/userguide/orgs_getting-started_concepts.html)。

如果您需要開啟 Organizations 並將帳戶指定為管理帳戶，然後再繼續進行，請參閱*《AWS Organizations 使用者指南》*中的[建立和管理組織](https://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_org.html)。

**注意**  
無法在下列情況下執行此設定程序 AWS 區域：  
歐洲 (米蘭) (eu-south-1)
中東 (巴林) (me-south-1)
非洲 (開普敦) (af-south-1)
亞太區域 (香港) (ap-east-1)
確保您在管理帳戶中的不同區域工作，以執行此程序。

在安裝程序期間，您需要在 Quick Setup ( AWS Systems Manager中的工具) 中執行下列主要任務。
+ **任務 1：註冊貴組織的委派管理員帳戶**

  使用 Change Manager 執行的變更相關任務可以您其中一個成員帳戶中進行管理，而您可將該帳戶指定為*委派管理員帳戶*。您註冊的 Change Manager 的委派管理員帳戶會成為您所有 Systems Manager 操作的委派管理員帳戶。（您可能已委派其他管理員帳戶） AWS 服務。您的 Change Manager 委派管理員帳戶 (與管理帳戶不同) 可管理整個組織的變更活動，包括變更範本、變更請求和每個核准。在委派管理員帳戶中，您也可以為 Change Manager 營運指定其他組態選項。
**重要**  
委派管理員帳戶必須是在 Organizations 中指派給組織單位 (OU) 的唯一成員。
+ **任務 2：定義並指定變更申請者角色或自訂任務函數的 Runbook 存取政策，且您要將其用於您的 Change Manager 操作**

  若要在 中建立變更請求Change Manager，必須授予成員帳戶中的使用者 AWS Identity and Access Management (IAM) 許可，讓他們只能存取您選擇提供給他們的 Automation Runbook 和變更範本。
**注意**  
當使用者建立變更請求時，他們會先選取變更範本。此變更範本可能會提供多個 Runbook，但使用者只能為每個變更要求選取一個 Runbook。變更範本也可以設定為允許使用者在其請求中包含任何可用的 Runbook。

  若要授予所需的許可，Change Manager 會使用亦為 IAM 所用的*任務職能*的概念。然而，與 IAM 中的[任務職能的AWS 受管政策](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_job-functions.html)不同，您可以指定您的 Change Manager 任務職能的名稱以及這些任務職能的 IAM 許可。

  當您設定任務職能時，建議您建立自訂政策，並僅提供執行變更管理任務所需的權限。例如，您可能根據您定義的*任務職能*指定許可，以將使用者限制至特定的執行手冊組。

  例如，您可以建立名為 `DBAdmin` 的任務職能。對於此任務職能，您僅可授予與 Amazon DynamoDB 資料庫相關的 Runbook 所需的許可，例如 `AWS-CreateDynamoDbBackup` 和 `AWSConfigRemediation-DeleteDynamoDbTable`。

  作為另一個範例，您可能只想授予某些使用者使用與 Amazon Simple Storage Service (Amazon S3) 儲存貯體相關的 Runbook 所需的許可，例如 `AWS-ConfigureS3BucketLogging` 和 `AWSConfigRemediation-ConfigureS3BucketPublicAccessBlock`。

  Change Manager 的 Quick Setup 中的組態程序也會提供一組完整的 Systems Manager 系統管理許可，以供您套用至您建立的管理角色。

  您部署的每個 Change Manager Quick Setup 組態會在您的委派管理員帳戶中建立具有許可的任務職能，以在您選取的組織單位中執行 Change Manager 範本和 Automation Runbook。您最多可以為 Change Manager 建立 15 個 Quick Setup 組態。
+ **任務 3：選擇組織中要搭配 Change Manager 使用的成員帳戶**

  您可以在 Organizations 設定的所有組織單位中以及其營運的所有 AWS 區域 中，搭配所有成員帳戶使用 Change Manager。如果您願意的話，您可以僅搭配部分組織單位使用 Change Manager。

**重要**  
我們強烈建議您在開始此程序之前，先通讀其步驟，以了解您的組態選擇以及授予的許可。特別是規劃您要建立的自訂任務職能，以及您指派給每個任務職能的許可。這可確保當您稍後將您建立的任務職能政策連接到個別使用者、使用者群組或 IAM 角色時，只會授予您想要讓他們擁有的許可。  
最佳實務是使用管理員的登入來設定委派 AWS 帳戶 管理員帳戶。然後在建立變更範本並識別每個範本使用的 Runbook 之後，設定任務職能及其許可。

若要設定與組織搭配使用的 Change Manager，請在 Systems Manager 主控台的 Quick Setup 區域中執行以下任務。

您可以針對您要為組織建立的每個任務職能重複此任務。您建立的每個任務職能擁有針對不同組織單位的許可。

**若要在 Organizations 管理帳戶中設定 Change Manager 的組織**

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

1. 在導覽窗格中，選擇 **Quick Setup**。

1. 在 **Change Manager** 卡上，選擇 **Create** (建立)。

1. 對於 **Delegated administrator account** (委派管理員帳戶)，輸入您要用來管理變更範本、變更請求和 Change Manager 中的 Runbook 工作流程的 AWS 帳戶 的 ID。

   如果您先前已為 Systems Manager 指定委派管理員帳戶，其 ID 已在此欄位中報告。
**重要**  
委派管理員帳戶必須是在 Organizations 中指派給組織單位 (OU) 的唯一成員。  
如果您註冊的委派管理員帳戶稍後會從該角色取消註冊，系統會同時移除其管理 Systems Manager 操作的許可。請注意，您需要返回 Quick Setup、指定不同的委派管理員帳戶，然後再次指定所有任務職能和許可。  
如果您在整個組織中使用 Change Manager，我們建議始終從委派管理員帳戶進行變更。雖然您可以從組織中的其他帳戶進行變更，但這些變更將不會在受委派管理員帳戶中報告，也不可在其中檢視。

1. 在 **Permissions to request and make changes** (請求和進行變更的許可) 區段中，執行下列動作。
**注意**  
您建立的每個部署組態只會針對一個任務職能提供許可政策。您可以稍後返回 Quick Setup，以便在您建立要用於操作的變更範本時，建立更多任務職能。

   **若要建立管理員角色** – 對於對所有 AWS 動作具有 IAM 許可的管理員任務職能 動作，請執行下列動作。
**重要**  
授予使用者完整的管理許可務必謹慎進行，且只有當他們的角色需要完整的 Systems Manager 存取權限時進行。如需 Systems Manager 存取之安全考量的重要資訊，請參閱 [適用於 AWS Systems Manager 的 Identity and Access Management](security-iam.md) 和 [Systems Manager 的安全最佳實務](security-best-practices.md)。

   1. 對於 **Job function** (任務職能)，輸入名稱以識別此角色及其許可，例如 **My AWS Admin**。

   1. 對於 **Role and permissions option** (角色和許可選項)，選擇 **Administrator permissions** (管理員許可)。

   **若要建立其他任務職能** – 若要建立非管理角色，請執行下列動作：

   1. 對於 **Job function** (任務職能)，輸入名稱以識別此角色及建議其許可。您選擇的名稱應代表您將提供許可的 Runbook 範圍，例如 `DBAdmin` 或 `S3Admin`。

   1. 對於 **Role and permissions option** (角色和許可選項)，選擇 **Custom permissions** (自訂許可)。

   1. 在 **Permissions policy editor** (許可政策編輯器) 中，以 JSON 格式輸入 IAM 許可，進而授與此任務職能。
**提示**  
我們建議您使用 IAM 政策編輯器來建構政策，然後將政策 JSON 貼到 **Permissions policy** (許可政策) 欄位。

**範例政策：DynamoDB 資料庫管理**  
例如，您可以從政策內容開始，提供使用任務職能需要存取的 Systems Manager 文件 (SSM 文件) 的許可。以下是在美國東部 （俄亥俄） 區域 () 中，授予與 DynamoDB 資料庫相關的所有 AWS 受管 Automation Runbook 的存取權 AWS 帳戶 `123456789012`，以及在範例中建立的兩個變更範本的範例政策內容`us-east-2`。

   該政策也包含 [https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_StartChangeRequestExecution.html](https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_StartChangeRequestExecution.html) 操作的許可，這是在 Change Calendar 中建立變更請求所必需的。
**注意**  
此範例並不全面。使用資料庫和節點等其他 AWS 資源時，可能需要其他許可。

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

****  

   ```
   {
       "Version":"2012-10-17",		 	 	 
       "Statement": [
           {
               "Effect": "Allow",
               "Action": [
                   "ssm:CreateDocument",
                   "ssm:DescribeDocument",
                   "ssm:DescribeDocumentParameters",
                   "ssm:DescribeDocumentPermission",
                   "ssm:GetDocument",
                   "ssm:ListDocumentVersions",
                   "ssm:ModifyDocumentPermission",
                   "ssm:UpdateDocument",
                   "ssm:UpdateDocumentDefaultVersion"
               ],
               "Resource": [
                   "arn:aws:ssm:us-east-1:*:document/AWS-CreateDynamoDbBackup",
                   "arn:aws:ssm:us-east-1:*:document/AWS-AWS-DeleteDynamoDbBackup",
                   "arn:aws:ssm:us-east-1:*:document/AWS-DeleteDynamoDbTableBackups",
                   "arn:aws:ssm:us-east-1:*:document/AWSConfigRemediation-DeleteDynamoDbTable",
                   "arn:aws:ssm:us-east-1:*:document/AWSConfigRemediation-EnableEncryptionOnDynamoDbTable",
                   "arn:aws:ssm:us-east-1:*:document/AWSConfigRemediation-EnablePITRForDynamoDbTable",
                   "arn:aws:ssm:us-east-1:111122223333:document/MyFirstDBChangeTemplate",
                   "arn:aws:ssm:us-east-1:111122223333:document/MySecondDBChangeTemplate"
               ]
           },
           {
               "Effect": "Allow",
               "Action": "ssm:ListDocuments",
               "Resource": "*"
           },
           {
               "Effect": "Allow",
               "Action": "ssm:StartChangeRequestExecution",
               "Resource": [
                   "arn:aws:ssm:us-east-1:111122223333:document/*",
                   "arn:aws:ssm:us-east-1:111122223333:automation-execution/*"
               ]
           }
       ]
   }
   ```

------

   如需 IAM 政策的詳細資訊，請參閱《IAM 使用者指南》**中的 [AWS 資源的存取管理](https://docs.aws.amazon.com/IAM/latest/UserGuide/access.html)和[建立 IAM 政策](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_create.html)。

1. 在 **Targets** (目標) 區段中，選擇要將您建立之任務職能的許可授予整個組織，還是只授予部分組織單位。

   如果您選擇 **Entire organization** (整個組織)，請繼續步驟 9。

   如果選擇 **Custom** (自訂)，請繼續步驟 8。

1. 在 **Target OUs** (目標 OU) 區段中，選取要搭配 Change Manager 使用之組織單位的核取方塊。

1. 選擇**建立**。

系統完成為您組織設定 Change Manager 後，它會顯示部署的摘要。此摘要資訊包含為您設定之任務職能建立的角色名稱。例如 `AWS-QuickSetup-SSMChangeMgr-DBAdminInvocationRole`。

**注意**  
Quick Setup 使用 AWS CloudFormation StackSets 部署您的組態。您還可以在 CloudFormation 主控台中檢視有關已完成的部署組態的資訊。如需 StackSets 的相關資訊，請參閱*AWS CloudFormation 《 使用者指南*》中的[使用 AWS CloudFormation StackSets](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/what-is-cfnstacksets.html)。

您的下一個步驟是設定其他 Change Manager 選項。您可以使用委派管理員帳戶或組織單位中允許搭配 Change Manager 使用的任何帳戶來完成此任務。您可以設定選項，例如選擇使用者身分識別管理選項、指定哪些使用者可以檢閱和核准或拒絕變更範本和變更請求，以及選擇允許您組織的最佳實務選項。如需相關資訊，請參閱[設定 Change Manager 選項和最佳實務](change-manager-account-setup.md)。

# 設定 Change Manager 選項和最佳實務
<a name="change-manager-account-setup"></a>

**Change Manager 可用性變更**  
AWS Systems Manager Change Manager 自 2025 年 11 月 7 日起，不再向新客戶開放。如果您想要使用 Change Manager，請在該日期之前註冊。現有客戶可以繼續正常使用該服務。如需詳細資訊，請參閱[AWS Systems Manager Change Manager可用性變更](https://docs.aws.amazon.com/systems-manager/latest/userguide/change-manager-availability-change.html)。

無論您使用 Change Manager、 中的工具 AWS Systems Manager、跨組織或單一 ，都必須執行本節中的任務 AWS 帳戶。

如果您使用的適用於組織的 Change Manager，您可以在委派管理員帳戶中或組織單位中允許搭配 Change Manager 使用的任何帳戶中執行下列任務。

**Topics**
+ [任務 1：設定 Change Manager 使用者身分識別管理和範本檢閱者](#cm-configure-account-task-1)
+ [任務 2：設定 Change Manager 變更凍結事件核准者和最佳實務](#cm-configure-account-task-2)
+ [為 Change Manager 通知設定 Amazon SNS 主題](change-manager-sns-setup.md)

## 任務 1：設定 Change Manager 使用者身分識別管理和範本檢閱者
<a name="cm-configure-account-task-1"></a>

在您第一次存取 Change Manager 時在此程序中執行任務。您可以稍後返回 Change Manager 並選擇 **Settings** (設定) 標籤上的 **Edit** (編輯)，進而更新這些組態設定。

**若要設定 Change Manager 使用者身分識別管理和範本檢閱者**

1. 登入 AWS 管理主控台。

   如果您使用的是適用於組織的 Change Manager，請使用您的委派管理員帳戶的憑證登入。使用者必須擁有必要的 AWS Identity and Access Management (IAM) 許可，以便更新 Change Manager 設定。

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

1. 在導覽窗格中，選擇 **Change Manager**。

1. 在服務首頁上，根據可用的選項執行下列其中一項操作：
   + 如果您使用 Change Manager搭配 AWS Organizations ，請選擇**設定委派帳戶**。
   + 如果您使用 Change Manager搭配單一 AWS 帳戶，請選擇**設定 Change Manager**。

     -或-

     選擇 **Create sample change request** (建立範例變更請求)、**Skip** (略過)，然後選擇 **Settings** (設定) 標籤。

1. 對於 **User identity management** (使用者身分識別管理)，選擇下列其中一項。
   + **AWS Identity and Access Management (IAM)** – Change Manager識別提出和核准請求的使用者，並使用您現有的使用者、群組和角色在 中執行其他動作。
   + **AWS IAM Identity Center (IAM Identity Center)** – 允許 [IAM Identity Center](https://docs.aws.amazon.com/singlesignon/latest/userguide/) 建立和管理身分，或連線到現有的身分來源，以識別在 中執行動作的使用者Change Manager。

1. 在 **Template reviewer notification** (範本檢閱者通知) 區段中，指定 Amazon Simple Notification Service (Amazon SNS) 主題，以便通知範本檢閱者新的變更範本或變更範本版本已準備好接受檢閱。確保您選擇的 Amazon SNS 主題已設定為傳送通知給範本檢閱者。

   如需有關針對變更範本檢閱者通知而建立和設定 Amazon SNS 主題的資訊，請參閱 [為 Change Manager 通知設定 Amazon SNS 主題](change-manager-sns-setup.md)。

   1. 若要指定範本檢閱者通知的 Amazon SNS 主題，請選擇下列其中一項：
      + **Enter an SNS Amazon Resource Name (ARN)** (輸入 SNS Amazon 資源名稱 (ARN)) – 對於 **Topic ARN** (主題 ARN)，輸入現有 Amazon SNS 主題的 ARN。此主題可以位於您組織的任何帳戶中。
      + **選取現有的 SNS 主題** – 對於 **Target notification topic** (目標通知主題) 中，選取您目前 AWS 帳戶中的現有 Amazon SNS 主題的 ARN。（如果您尚未在目前的 AWS 帳戶 和 中建立任何 Amazon SNS 主題，則無法使用此選項 AWS 區域。)
**注意**  
您選取的 Amazon SNS 主題必須設定為指定其傳送的通知以及要傳送的訂閱者。其存取政策也必須將許可授予 Systems Manager，以便 Change Manager 可以傳送通知。如需相關資訊，請參閱[為 Change Manager 通知設定 Amazon SNS 主題](change-manager-sns-setup.md)。

   1. 選擇 **Add notification** (新增通知)。

1. 在 **Change template reviewers** (變更範本檢閱者) 區段中，選取組織或帳戶中的使用者，以檢閱新的變更範本或變更範本版本，然後再將其用於您的營運中。

   變更範本檢閱者負責驗證其他使用者已提交供 Change Manager Runbook 工作流程使用之範本的適用性和安全性。

   透過執行下列動作來選取變更範本檢閱者：

   1. 選擇**新增**。

   1. 選取您要指派為變更範本檢閱者之各個使用者、群組或 IAM 角色名稱旁的核取方塊。

   1. 選擇 **Add approvers** (新增核准者)。

1. 選擇**提交**。

 完成此初始安裝程序之後，請遵循 [任務 2：設定 Change Manager 變更凍結事件核准者和最佳實務](#cm-configure-account-task-2) 中的步驟設定其他 Change Manager 設定和最佳實務。

## 任務 2：設定 Change Manager 變更凍結事件核准者和最佳實務
<a name="cm-configure-account-task-2"></a>

在您完成 [任務 1：設定 Change Manager 使用者身分識別管理和範本檢閱者](#cm-configure-account-task-1) 中的步驟後，您可以指定*變更凍結事件*期間的變更請求的額外檢閱者，並指定您希望允許用於 Change Manager 營運的最佳實務。

變更凍結事件表示限制在目前的變更行事曆中 ( 中的 AWS Systems Manager Change Calendar行事曆狀態為 `CLOSED`)。在這些情況下，除了變更請求的一般核准者之外，或者如果使用允許自動核准的範本建立變更請求，則變更凍結核准者必須授予執行此變更請求的許可。如果沒有，則無法處理變更，直至行事曆狀態再次變為 `OPEN`。

**若要設定 Change Manager 變更凍結事件核准者和最佳實務**

1. 在導覽窗格中，選擇 **Change Manager**。

1. 選擇 **Settings** (設定) 標籤，然後選擇 **Edit** (編輯)。

1. 在 **Approvers for change freeze events** (變更凍結事件的核准者) 區段中，選取組織或帳戶中可核准變更的使用者，即使在 Change Calendar 中使用的行事曆目前已關閉。
**注意**  
若要允許變更凍結檢閱，您必須開啟 **Best practices** (最佳實務) 中的 **Check Change Calendar for restricted change events** (檢查變更行事曆是否有限制變更事件) 選項。

   執行下列動作，以選取變更凍結事件的核准者：

   1. 選擇**新增**。

   1. 選取您要指派為變更凍結事件的核准者之各個使用者、群組或 IAM 角色名稱旁的核取方塊。

   1. 選擇 **Add approvers** (新增核准者)。

1. 在頁面底部附近的 **Best practices** (最佳實務) 區段中，開啟您要針對下列每個選項強制執行的最佳實務。
   + 選項：**Check Change Calendar for restricted change events** (檢查變更行事曆是否有限制變更事件)

     若要指定 Change Manager 檢查 Change Calendar 中的行事曆，以確保變更不會被排程事件封鎖，請先選取 **Enabled** (已啟用) 核取方塊，然後從 **Change Calendar** (變更行事曆) 清單中選取行事曆以檢查是否有限制事件。

     如需有關 Change Calendar 的詳細資訊，請參閱「[AWS Systems Manager Change Calendar](systems-manager-change-calendar.md)」。
   + 選項：**SNS topic for approvers for closed events** (已關閉事件的核准者的 SNS 主題)

     1. 選擇下列其中一項，指定帳戶中的 Amazon Simple Notification Service (Amazon SNS) 主題，以便在變更凍結事件期間傳送通知給核准者。(請注意，您也必須在上述 **Best practices** (最佳實務) 的 **Approvers for change freeze events** (變更凍結事件的核准者) 中指定核准者。)
        + **Enter an SNS Amazon Resource Name (ARN)** (輸入 SNS Amazon 資源名稱 (ARN)) – 對於 **Topic ARN** (主題 ARN)，輸入現有 Amazon SNS 主題的 ARN。此主題可以位於您組織的任何帳戶中。
        + **選取現有的 SNS 主題** – 對於 **Target notification topic** (目標通知主題) 中，選取您目前 AWS 帳戶中的現有 Amazon SNS 主題的 ARN。（如果您尚未在目前的 AWS 帳戶 和 中建立任何 Amazon SNS 主題，則無法使用此選項 AWS 區域。)
**注意**  
您選取的 Amazon SNS 主題必須設定為指定其傳送的通知以及要傳送的訂閱者。其存取政策也必須將許可授予 Systems Manager，以便 Change Manager 可以傳送通知。如需相關資訊，請參閱[為 Change Manager 通知設定 Amazon SNS 主題](change-manager-sns-setup.md)。

     1. 選擇 **Add notification** (新增通知)。
   + 選項：**Require monitors for all templates** (需要監控所有範本)

     如果您想要確保組織或帳戶的所有範本都指定了 Amazon CloudWatch 警示來監控變更操作，則請選取 **Enabled** (已啟用) 核取方塊。
   + 選項：**Require template review and approval before use** (使用前需要範本檢閱和核准)

     若要確保不會建立任何變更要求，且不會執行 Runbook 工作流程，而不會以已檢閱和已核准的範本為基礎，請選取 **Enabled** (已啟用) 核取方塊。

1. 選擇**儲存**。

# 為 Change Manager 通知設定 Amazon SNS 主題
<a name="change-manager-sns-setup"></a>

**Change Manager 可用性變更**  
AWS Systems Manager Change Manager 自 2025 年 11 月 7 日起，不再向新客戶開放。如果您想要使用 Change Manager，請在該日期之前註冊。現有客戶可以繼續正常使用該服務。如需詳細資訊，請參閱[AWS Systems Manager Change Manager可用性變更](https://docs.aws.amazon.com/systems-manager/latest/userguide/change-manager-availability-change.html)。

您可以設定 中的Change Manager工具 AWS Systems Manager，針對與變更請求和變更範本相關的事件傳送通知至 Amazon Simple Notification Service (Amazon SNS) 主題。完成下列任務，以接收您新增主題的 Change Manager 事件的通知。

**Topics**
+ [任務 1：建立並訂閱 Amazon SNS 主題](#change-manager-sns-setup-create-topic)
+ [任務 2：更新 Amazon SNS 存取政策](#change-manager-sns-setup-encryption-policy)
+ [任務 3：（選用） 更新 AWS Key Management Service 存取政策](#change-manager-sns-setup-KMS-policy)

## 任務 1：建立並訂閱 Amazon SNS 主題
<a name="change-manager-sns-setup-create-topic"></a>

首先，您必須建立並訂閱 Amazon SNS 主題。如需詳細資訊，請參閱《*Amazon Simple Notification Service 開發人員指南*》中的[建立 Amazon SNS 主題](https://docs.aws.amazon.com/sns/latest/dg/sns-create-topic.html)和[訂閱 Amazon SNS 主題](https://docs.aws.amazon.com/sns/latest/dg/sns-tutorial-create-subscribe-endpoint-to-topic.html)。

**注意**  
若要接收通知，您必須指定與委派管理員帳戶位於相同 AWS 區域 和 中的 Amazon SNS 主題的 Amazon Resource Name AWS 帳戶 (ARN)。

## 任務 2：更新 Amazon SNS 存取政策
<a name="change-manager-sns-setup-encryption-policy"></a>

使用下列程序更新 Amazon SNS 存取政策，讓 Systems Manager 可以將 Change Manager 通知發佈至您在任務 1 中建立的 Amazon SNS 主題。如果不完成此任務，Change Manager 沒有為您新增主題的事件傳送通知的許可。

1. 登入 AWS 管理主控台 並開啟位於 https：//[https://console.aws.amazon.com/sns/v3/home](https://console.aws.amazon.com/sns/v3/home) 的 Amazon SNS 主控台。

1. 在導覽窗格中，選擇**主題**。

1. 選擇您在任務 1 中建立的主題，然後選擇 **Edit** (編輯)。

1. 展開 **Access policy (存取政策)**。

1. 新增並更新下列 `Sid` 區塊至現有政策，並使用自己的資訊取代每個*使用者輸入預留位置*。

   ```
   {
       "Sid": "Allow Change Manager to publish to this topic",
       "Effect": "Allow",
       "Principal": {
           "Service": "ssm.amazonaws.com"
       },
       "Action": "sns:Publish",
       "Resource": "arn:aws:sns:region:account-id:topic-name",
       "Condition": {
           "StringEquals": {
               "aws:SourceAccount": [
                   "account-id"
               ]
           }
       }
   }
   ```

   在現有 `Sid` 區塊後輸入此區塊，並將 *region*、*account-id* 和 *topic\$1name* 取代為您建立之主題的適當值。

1. 選擇**儲存變更**。

現在，當您新增至主題的事件類型發生時，系統會傳送通知給 Amazon SNS 主題。

**重要**  
如果您使用 AWS Key Management Service (AWS KMS) 伺服器端加密金鑰設定 Amazon SNS 主題，則必須完成任務 3。

## 任務 3：（選用） 更新 AWS Key Management Service 存取政策
<a name="change-manager-sns-setup-KMS-policy"></a>

如果您開啟 Amazon SNS 主題的 AWS Key Management Service (AWS KMS) 伺服器端加密，則還必須更新 AWS KMS key 您在設定主題時所選 的存取政策。使用下列處理程序更新存取政策，讓 Systems Manager 可以將 Change Manager 核准通知發佈至您在任務 1 中建立的 Amazon SNS 主題。

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

1. 在導覽窗格中，選擇 **Customer managed keys** (客戶受管金鑰)。

1. 選擇您在建立主題時所選擇的客戶受管金鑰的 ID。

1. 在 **Key policy (金鑰政策)** 區段中，選擇 **Switch to policy view (切換至政策檢視)**。

1. 選擇**編輯**。

1. 在現有政策中的某個現有 `Sid` 區塊後輸入以下 `Sid` 區塊。將每個*使用者輸入預留位置*替換為自己的資訊。

   ```
   {
       "Sid": "Allow Change Manager to decrypt the key",
       "Effect": "Allow",
       "Principal": {
           "Service": "ssm.amazonaws.com"
       },
       "Action": [
           "kms:Decrypt",
           "kms:GenerateDataKey*"
       ],
       "Resource": "arn:aws:kms:region:account-id:key/key-id",
       "Condition": {
           "StringEquals": {
               "aws:SourceAccount": [
                   "account-id"
               ]
           }
       }
   }
   ```

1. 現在在資源政策中的某個現有 `Sid` 區塊之後輸入以下 `Sid` 區塊以協助防止[跨服務混淆代理人問題](https://docs.aws.amazon.com/IAM/latest/UserGuide/confused-deputy.html)。

   此區塊使用 [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) 全域條件內容索引鍵，可限制 Systems Manager 為資源提供其他服務的許可。

   將每個*使用者輸入預留位置*取代為自己的資訊。

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

****  

   ```
   {
       "Version":"2012-10-17",		 	 	 
       "Statement": [
           {
               "Sid": "Configure confused deputy protection for AWS KMS keys used in Amazon SNS topic when called from Systems Manager",
               "Effect": "Allow",
               "Principal": {
                   "Service": "ssm.amazonaws.com"
               },
               "Action": [
                   "sns:Publish"
               ],
               "Resource": "arn:aws:sns:us-east-1:111122223333:topic-name",
               "Condition": {
                   "ArnLike": {
                       "aws:SourceArn": "arn:aws:ssm:us-east-1:111122223333:*"
                   },
                   "StringEquals": {
                       "aws:SourceAccount": "111122223333"
                   }
               }
           }
       ]
   }
   ```

------

1. 選擇**儲存變更**。

# 設定 Change Manager 的角色和許可
<a name="change-manager-permissions"></a>

**Change Manager 可用性變更**  
AWS Systems Manager Change Manager 自 2025 年 11 月 7 日起，不再向新客戶開放。如果您想要使用 Change Manager，請在該日期之前註冊。現有客戶可以繼續正常使用該服務。如需詳細資訊，請參閱[AWS Systems Manager Change Manager可用性變更](https://docs.aws.amazon.com/systems-manager/latest/userguide/change-manager-availability-change.html)。

在預設情況下，Change Manager 沒有在您的資源上執行動作的許可。您必須使用 AWS Identity and Access Management (IAM) 服務角色或*擔任角色*來授予存取權。此角色可讓 Change Manager 代表您安全地執行在已核准變更請求中指定的 Runbook 工作流程。角色將 grant AWS Security Token Service (AWS STS) [AssumeRole](https://docs.aws.amazon.com/STS/latest/APIReference/API_AssumeRole.html) 信任授予 Change Manager。

藉由向角色提供這些權限以代表組織中的使用者執行操作，使用者本身無需被授予該許可陣列。許可允許的動作僅限於已核准的操作。

當您的帳户或組織中的使用者建立變更請求時，他們可以選取此擔任角色來執行變更操作。

您可以為 Change Manager 建立新的擔任角色，或更新具備所需許可的現有角色。

如果您需要為 Change Manager 建立服務角色，請完成以下任務。

**Topics**
+ [任務 1：建立 Change Manager 的擔任角色策略](#change-manager-role-policy)
+ [任務 2：建立 Change Manager 的擔任角色](#change-manager-role)
+ [任務 3：將 `iam:PassRole` 策略連接至其他角色](#change-manager-passpolicy)
+ [任務 4：將內嵌政策新增至 擔任角色以叫用其他 AWS 服務](#change-manager-role-add-inline-policy)
+ [任務 5：設定使用者存取至 Change Manager](#change-manager-passrole)

## 任務 1：建立 Change Manager 的擔任角色策略
<a name="change-manager-role-policy"></a>

使用以下程序建立您將連接至 Change Manager 擔任角色的政策。

**若要建立 Change Manager 的擔任角色策略**

1. 在 [https://console.aws.amazon.com/iam/](https://console.aws.amazon.com/iam/) 中開啟 IAM 主控台。

1. 在導覽窗格中，選擇 **Policies (政策)**，然後選擇 **Create Policy (建立政策)**。

1. 在 **Create policy** (建立政策) 頁面上，選擇 **JSON** 標籤，並利用以下內容更換預設內容，即您將在以下步驟中修改您自己的 Change Manager 操作。
**注意**  
如果您要建立政策以搭配單一 使用 AWS 帳戶，而不是具有多個帳戶的組織 AWS 區域，並且可以省略第一個陳述式區塊。在此使用 Change Manager 的單一帳户情況中，無須使用 `iam:PassRole` 許可。

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

****  

   ```
   {
       "Version":"2012-10-17",		 	 	 
       "Statement": [
           {
               "Effect": "Allow",
               "Action": "iam:PassRole",
               "Resource": "arn:aws:iam::111122223333:role/AWS-SystemsManager-job-functionAdministrationRole",
               "Condition": {
                   "StringEquals": {
                       "iam:PassedToService": "ssm.amazonaws.com"
                   }
               }
           },
           {
               "Effect": "Allow",
               "Action": [
                   "ssm:DescribeDocument",
                   "ssm:GetDocument",
                   "ssm:StartChangeRequestExecution"
               ],
               "Resource": [
                   "arn:aws:ssm:us-east-1::document/template-name",
                   "arn:aws:ssm:us-east-1:111122223333:automation-execution/*"
               ]
           },
           {
               "Effect": "Allow",
               "Action": [
                   "ssm:ListOpsItemEvents",
                   "ssm:GetOpsItem",
                   "ssm:ListDocuments",
                   "ssm:DescribeOpsItems"
               ],
               "Resource": "*"
           }
       ]
   }
   ```

------

1. 對於 `iam:PassRole` 動作，請更新 `Resource` 值以包括為您組織定義之所有任務職能的 ARN，即您希望授與許可以啟動 Runbook 工作流程。

1. 將 *region*、*account-id*、*template-name*、*delegated-admin-account-id* 及 *job-function* 預留位置替換成您 Change Manager 操作的值。

1. 對於第二個 `Resource` 陳述式，修改列表以包括要授予許可的所有變更範本。或者，指定 `"Resource": "*"` 以向組織中的所有變更範本授與許可。

1. 選擇下**一步：標籤**。

1. (選用) 新增一個或多個標籤鍵值組來組織、追蹤或控制對此政策的存取。

1. 選擇下**一步：檢閱**。

1. 在 **Review policy** (檢閱政策) 頁面，在 **Name** (名稱) 方塊中輸入名稱 (如 **MyChangeManagerAssumeRole**)，接著輸入選用描述。

1. 選擇 **Create policy** (建立政策)，並繼續 [任務 2：建立 Change Manager 的擔任角色](#change-manager-role)。

## 任務 2：建立 Change Manager 的擔任角色
<a name="change-manager-role"></a>

使用以下程序建立 Change Manager 的 Change Manager 擔任角色 (一種服務角色類型)。

**若要建立 Change Manager 的擔任角色**

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

1. 在導覽窗格中，選擇**角色**，然後選擇**建立角色**。

1. 對於 **Select trusted entity** (選擇信任的實體)，請執行以下選項：

   1. 針對 **Trusted entity type** (信任的實體類型)，請選擇 **AWS service** ( 服務)

   1. 針對**其他的使用案例 AWS 服務**，選擇 **Systems Manager**

   1. 選擇 **Systems Manager**，如下圖所示。  
![\[螢幕擷取畫面說明選擇了 Systems Manager 選項作為使用案例。\]](http://docs.aws.amazon.com/zh_tw/systems-manager/latest/userguide/images/iam_use_cases_for_MWs.png)

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

1. 在 **Attached permissions policy** (已連接許可政策) 頁面，搜尋您在 [任務 1：建立 Change Manager 的擔任角色策略](#change-manager-role-policy) 中建立的擔任角色政策，如 **MyChangeManagerAssumeRole**。

1. 選取擔任角色政策名稱旁的核取方塊，然後選擇 **Next: Tags** (下一步：標籤)。

1. 在 **Role name (角色名稱)** 中，輸入新執行個體設定檔的名稱，如 **MyChangeManagerAssumeRole**。

1. (選用) 對於 **Description** (說明)，更新此執行個體角色的說明。

1. (選用) 新增一個或多個標籤鍵值組來組織、追蹤或控制對此角色的存取。

1. 選擇下**一步：檢閱**。

1. (選用) 對於 **Tags** (標籤)，新增一個或多個標籤鍵值組來整理、追蹤或控制存取此角色的存取權，然後選擇 **Create role** (建立角色)。系統會讓您回到 **Roles (角色)** 頁面。

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

1. 在 **Roles (角色)** 頁面，選擇您剛建立的角色，以開啟 **Summary (摘要)** 頁面。

## 任務 3：將 `iam:PassRole` 策略連接至其他角色
<a name="change-manager-passpolicy"></a>

使用以下程序將 `iam:PassRole` 政策連接至 IAM 執行個體設定檔或 IAM 服務角色。(Systems Manager 服務使用 IAM 執行個體設定檔與 EC2 執行個體進行通訊。對於[混合多雲端](operating-systems-and-machine-types.md#supported-machine-types)環境中的非 EC2 受管節點，則會改用 IAM 服務角色。)

連接 `iam:PassRole` 政策後，Change Manager 服務可以在執行執行手冊工作流程時將擔任角色許可傳送至其他服務或 Systems Manager 工具。

**將 `iam:PassRole` 政策連接至 IAM 執行個體設定檔或服務角色**

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

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

1. 搜尋您建立的 Change Manager 擔任角色 (例如 **MyChangeManagerAssumeRole**)，並選擇其名稱。

1. 在擔任角色的 **Summary** (摘要) 頁面，選擇 **Permissions** (許可) 標籤。

1. 選擇 **Add permissions, Create inline policy** (新增許可，建立內嵌政策)。

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

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

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

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

1. 在 **Specify ARN for role** (指定角色的 ARN) 欄位中，輸入要向其傳送擔任角色許可的 IAM 執行個體設定檔角色或 IAM 服務角色的 ARN。系統會填入 **Account (帳戶)** 和 **Role name with path (角色名稱與路徑)** 欄位。

1. 選擇 **Add (新增)**。

1. 選擇 **Review policy** (檢閱政策)。

1. 在 **Name** (名稱) 中，輸入名稱來識別政策，然後選擇 **Create policy** (建立政策)。

**詳細資訊**  
+ [設定 Systems Manager 所需的執行個體許可](setup-instance-permissions.md)
+ [在混合多雲端環境中建立 Systems Manager 所需的 IAM 服務角色](hybrid-multicloud-service-role.md)

## 任務 4：將內嵌政策新增至 擔任角色以叫用其他 AWS 服務
<a name="change-manager-role-add-inline-policy"></a>

當變更請求 AWS 服務 使用Change Manager擔任角色叫用其他 時，必須設定擔任角色並具有叫用這些服務的許可。此要求適用於可用於變更請求的所有 AWS Automation Runbook (AWS-\$1 Runbook)，例如 `AWS-ConfigureS3BucketLogging`、 `AWS-CreateDynamoDBBackup`和 `AWS-RestartEC2Instance` Runbook。此要求也適用於您建立的任何自訂 Runbook， AWS 服務 透過使用呼叫其他 服務的動作來叫用其他 。例如，如果您使用 `aws:executeAwsApi`、`aws:CreateStack` 或 `aws:copyImage` 等動作，則您必須為服務角色設定可叫用這些服務的許可。您可將 IAM 內嵌政策新增至角色，以啟用其他 AWS 服務 的許可。

**將內嵌政策新增至擔任角色以叫用其他 AWS 服務 (IAM 主控台）**

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

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

1. 在清單中，請選擇您要更新的擔任角色名稱 (如 `MyChangeManagerAssumeRole`)。

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

1. 選擇 **Add permissions, Create inline policy** (新增許可，建立內嵌政策)。

1. 選擇 **JSON** 標籤。

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

   **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. 在 **Name** (名稱) 中，輸入名稱來識別您正在建立的政策。檢閱政策 **Summary** (摘要) 來查看您的政策所授予的許可。然後選擇 **Create policy (建立政策)** 來儲存您的工作。

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

## 任務 5：設定使用者存取至 Change Manager
<a name="change-manager-passrole"></a>

如果使用者、群組或角色受獲指派管理員許可，則您可以存取 Change Manager。如果您沒有管理員許可，則管理員必須指派 `AmazonSSMFullAccess` 受管政策或提供相當許可的政策給使用者、群組或角色。

使用以下程序將使用者設定為使用 Change Manager。您選擇的使用者會擁有設定和執行 Change Manager 的許可。

視您在組織中使用的身分應用程式而定， 您可以選取三個可用於設定使用者存取權中的任何一個選項。設定使用者存取權時，指派或新增下列項目：

1. 指派 `AmazonSSMFullAccess` 政策或相當的政策，以授予存取 Systems Manager 的許可。

1. 指派 `iam:PassRole` 政策。

1. 新增您在 [任務 2：建立 Change Manager 的擔任角色](#change-manager-role) 結尾複製的 Change Manager 擔任角色的 ARN。

若要提供存取權，請新增權限至您的使用者、群組或角色：
+ 中的使用者和群組 AWS IAM Identity Center：

  建立權限合集。請按照《*AWS IAM Identity Center 使用者指南*》中的[建立權限合集](https://docs.aws.amazon.com//singlesignon/latest/userguide/howtocreatepermissionset.html)說明進行操作。
+ 透過身分提供者在 IAM 中管理的使用者：

  建立聯合身分的角色。遵循《*IAM 使用者指南*》的[為第三方身分提供者 (聯合) 建立角色](https://docs.aws.amazon.com//IAM/latest/UserGuide/id_roles_create_for-idp.html)中的指示。
+ IAM 使用者：
  + 建立您的使用者可擔任的角色。請按照《*IAM 使用者指南*》的[為 IAM 使用者建立角色](https://docs.aws.amazon.com//IAM/latest/UserGuide/id_roles_create_for-user.html)中的指示。
  + (不建議) 將政策直接附加至使用者，或將使用者新增至使用者群組。請遵循《*IAM 使用者指南*》的[新增許可到使用者 (主控台)](https://docs.aws.amazon.com//IAM/latest/UserGuide/id_users_change-permissions.html#users_change_permissions-add-console) 中的指示。

您已完成設定 Change Manager 所需的角色。您現在可以在 Change Manager 操作中使用 Change Manager 擔任角色 ARN。

# 控制對自動核准 Runbook 工作流程的存取
<a name="change-manager-auto-approval-access"></a>

**Change Manager 可用性變更**  
AWS Systems Manager Change Manager 自 2025 年 11 月 7 日起，不再向新客戶開放。如果您想要使用 Change Manager，請在該日期之前註冊。現有客戶可以繼續正常使用該服務。如需詳細資訊，請參閱[AWS Systems Manager Change Manager可用性變更](https://docs.aws.amazon.com/systems-manager/latest/userguide/change-manager-availability-change.html)。

在為組織或帳戶建立的每個變更範本中，您可以指定從該範本建立的變更請求是否可以作為自動核准的變更請求來執行，這表示它們會在沒有檢閱步驟的情況下自動執行 (變更凍結事件除外)。

不過，您可能想要防止某些使用者、群組或 AWS Identity and Access Management (IAM) 角色執行自動核准的變更請求，即使變更範本允許也是一樣。您可以透過在指派給使用者、群組或 IAM 角色的 IAM 政策中使用 `StartChangeRequestExecution` 操作的 `ssm:AutoApprove` 條件金鑰，來執行此操作。

您可以將下列政策新增為內嵌政策，其中條件指定為`false`，可防止使用者執行可自動核准的變更請求。

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

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
            {
            "Effect": "Allow",
            "Action": "ssm:StartChangeRequestExecution",
            "Resource": "*",
            "Condition": {
                "BoolIfExists": {
                    "ssm:AutoApprove": "false"
                }
            }
        }
    ]
}
```

------

如需有關指定內嵌政策的資訊，請參閱*《IAM 使用者指南》*中的[內嵌政策](https://docs.aws.amazon.com//IAM/latest/UserGuide/access_policies_managed-vs-inline.html#inline-policies)和[新增和移除 IAM 身分許可](https://docs.aws.amazon.com//IAM/latest/UserGuide/access_policies_manage-attach-detach.html)。

如需有關 Systems Manager 政策條件金鑰的詳細資訊，請參閱 [Systems Manager 條件金鑰](security_iam_service-with-iam.md#policy-conditions)。

# 使用 Change Manager
<a name="working-with-change-manager"></a>

**Change Manager 可用性變更**  
AWS Systems ManagerChange Manager 自 2025 年 11 月 7 日起，不再向新客戶開放。如果您想要使用 Change Manager，請在該日期之前註冊。現有客戶可以繼續正常使用服務。如需詳細資訊，請參閱[AWS Systems ManagerChange Manager可用性變更](https://docs.aws.amazon.com/systems-manager/latest/userguide/change-manager-availability-change.html)。

透過 中的Change Manager工具 AWS Systems Manager，整個組織或單一 中的使用者 AWS 帳戶 可以執行與變更相關的任務，他們已獲得必要的許可。 Change Manager任務包括下列項目：
+ 建立、檢閱及核准或拒絕變更範本。

  變更範本是 Change Manager 中的組態設定的集合，可定義必要核准、可用 Runbook 以及變更請求的通知選項等項目。
+ 建立、檢閱及核准或拒絕變更請求。

  變更請求是在 中執行 Automation Runbook Change Manager的請求，以更新 AWS 或內部部署環境中的一或多個資源。變更請求是使用變更範本建立的。
+ 指定組織或帳戶中的哪些使用者可以成為變更範本和變更請求的檢閱者。
+ 編輯組態設定，例如如何在 Change Manager 中管理使用者身分以及可在 Change Manager 營運中強制使用哪些*最佳實務*。如需有關設定這些設定的資訊，請參閱 [設定 Change Manager 選項和最佳實務](change-manager-account-setup.md)。

**Topics**
+ [使用變更範本](change-templates.md)
+ [使用變更請求](change-requests.md)
+ [檢閱變更請求詳細資訊、任務和時間表 (主控台)](reviewing-changes.md)
+ [檢視變更請求的彙總計數 (命令列)](change-requests-review-aggregate-command-line.md)

# 使用變更範本
<a name="change-templates"></a>

**Change Manager 可用性變更**  
AWS Systems ManagerChange Manager 自 2025 年 11 月 7 日起，不再向新客戶開放。如果您想要使用 Change Manager，請在該日期之前註冊。現有客戶可以繼續正常使用服務。如需詳細資訊，請參閱[AWS Systems ManagerChange Manager可用性變更](https://docs.aws.amazon.com/systems-manager/latest/userguide/change-manager-availability-change.html)。

變更範本是 Change Manager 中的組態設定的集合，可定義必要核准、可用 Runbook 以及變更請求的通知選項等項目。

**注意**  
AWS 提供範例 [Hello World](change-templates-aws-managed.md) 變更範本，您可以用來試用 Change Manager，這是 中的工具 AWS Systems Manager。但是，您可以建立自己的變更範本，以定義您要允許對您組織或帳戶中的資源的變更。

執行 Runbook 工作流程時所做的變更以自動化 Runbook 內容為基礎。在您建立的每個變更範本中，您可以包含一個或多個自動化 Runbook，而提出變更請求的使用者可以選擇在更新期間執行。您也可以建立變更範本，以允許申請者為變更請求選擇任何可用的自動化 Runbook。

若要建立變更範本，您可以使用 **Create template** (建立範本) 主控台頁面中的 **Builder** (建置器) 選項，以建置變更範本。或者，使用 **Editor** (編輯器) 選項，您可以使用您想要的 Runbook 工作流程所需的組態手動編寫 JSON 或 YAML 內容。您也可以使用命令列工具來建立變更範本，其中包含存放在外部檔案中的變更範本的 JSON 內容。

**Topics**
+ [試用 AWS 受管`Hello World`變更範本](change-templates-aws-managed.md)
+ [建立變更範本](change-templates-create.md)
+ [檢閱及核准或拒絕變更範本](change-templates-review.md)
+ [刪除變更範本](change-templates-delete.md)

# 試用 AWS 受管`Hello World`變更範本
<a name="change-templates-aws-managed"></a>

**Change Manager 可用性變更**  
AWS Systems Manager Change Manager 自 2025 年 11 月 7 日起，不再向新客戶開放。如果您想要使用 Change Manager，請在該日期之前註冊。現有客戶可以繼續正常使用該服務。如需詳細資訊，請參閱[AWS Systems Manager Change Manager可用性變更](https://docs.aws.amazon.com/systems-manager/latest/userguide/change-manager-availability-change.html)。

您可以使用範例變更範本 `AWS-HelloWorldChangeTemplate`，其會使用範例 Automation 執行手冊 `AWS-HelloWorld`，以在完成設定 Change Manager ( AWS Systems Manager中的工具) 後測試檢閱和核准程序。此範本旨在測試或驗證您已設定的許可、核准者指派和核准程序。 AWS以提供在您的組織或帳戶中使用此變更範本的核准。不過，以此變更範本為基礎的任何變更請求仍必須經過組織或帳戶中的檢閱者核准。

與此範本關聯的 Runbook 工作流程的結果，是在自動化步驟的輸出中列印訊息，而不是對資源進行變更。

**開始之前**  
開始之前，請確保您已完成下列任務：
+ 如果您使用 AWS Organizations 管理整個組織的變更，請完成中所述的組織設定任務[設定適用於組織的 Change Manager (管理帳戶)](change-manager-organization-setup.md)。
+ 如 [設定 Change Manager 選項和最佳實務](change-manager-account-setup.md) 所述，為您的委派管理員帳戶或單一帳戶設定 Change Manager。
**注意**  
當您測試 Hello World 變更範本時，如果您在 Change Manager 設定中開啟了最佳實務選項 **Require monitors for all templates** (需要監控所有範本)，請暫時將其關閉。

**試用 AWS 受管 Hello World 變更範本**

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

1. 在導覽窗格中，選擇 **Change Manager**。

1. 選擇 **Create request** (建立請求)。

1. 選擇名為 `AWS-HelloWorldChangeTemplate` 的變更範本，然後選擇 **Next** (下一步)。

1. 對於 **Name** (名稱)，輸入可輕鬆識別用途的變更請求名稱，例如 **MyChangeRequestTest**。

1. 如需建立變更請求的剩餘步驟，請參閱 [建立變更請求建立變更請求 (主控台)](change-requests-create.md)。

**後續步驟**  
如需核准變更請求的資訊，請參閱 [檢閱及核准或拒絕變更請求](change-requests-review.md)。

若要檢視變更請求的狀態和結果，請在 Change Manager 中的 **Requests** (請求) 標籤上選擇變更請求的名稱。

# 建立變更範本
<a name="change-templates-create"></a>

**Change Manager 可用性變更**  
AWS Systems ManagerChange Manager 自 2025 年 11 月 7 日起，不再向新客戶開放。如果您想要使用 Change Manager，請在該日期之前註冊。現有客戶可以繼續正常使用服務。如需詳細資訊，請參閱[AWS Systems ManagerChange Manager可用性變更](https://docs.aws.amazon.com/systems-manager/latest/userguide/change-manager-availability-change.html)。

變更範本是 Change Manager 中的組態設定的集合，可定義必要核准、可用 Runbook 以及變更請求的通知選項等項目。

您可以使用主控台 (包含建置器和編輯器選項) 或命令列工具，為 Change Manager ( AWS Systems Manager中的工具) 中的操作建立變更範本。

**Topics**
+ [關於變更範本中的核准](cm-approvals-templates.md)
+ [使用建置器建立變更範本](change-templates-custom-builder.md)
+ [使用編輯器建立變更範本](change-templates-custom-editor.md)
+ [使用命令列工具建立變更範本](change-templates-tools.md)

# 關於變更範本中的核准
<a name="cm-approvals-templates"></a>

**Change Manager 可用性變更**  
AWS Systems Manager Change Manager 自 2025 年 11 月 7 日起，不再向新客戶開放。如果您想要使用 Change Manager，請在該日期之前註冊。現有客戶可以繼續正常使用該服務。如需詳細資訊，請參閱[AWS Systems Manager Change Manager可用性變更](https://docs.aws.amazon.com/systems-manager/latest/userguide/change-manager-availability-change.html)。

對於根據您所建立的每個變更範本建立的變更請求，您最多可以指定五個核准*層級*。對於每個層級，您最多可以指定五個潛在*核准者*。核准者不限於單一使用者。您也可以將 IAM 群組或 IAM 角色指定為個別核准者。對於 IAM 群組和 IAM 角色，屬於該群組或角色的一或多名使用者可以提供核准，以獲得變更請求所需的核准總數。您還可以指定比變更範本要求數量更多的核准者。

Change Manager 支援兩種主要核准方法：*逐級核准*和*逐行核准*。在某些情況下，這兩種類型的組合也是可行的。建議您在 Change Manager 操作中僅使用逐級核准。

------
#### [ Per-level approvals ]

*建議使用*。自 2023 年 1 月 23 日起，Change Manager 支援逐級核准。在此模型中，對於變更範本中的每個核准層級，您必須先指定該層級需要的核准數量。接著，您至少要為該層級指定該數量的核准者，也可指定更多核准者。但是，只要達到您為該層級指定的核准數量，就可以核准變更請求。例如，您可以指定五名核准者，但只需要三個核准。

如需此核准類型的主控台檢視和 JSON 範例，請參閱[逐級核准組態範例](approval-type-samples.md#per-level-approvals)。

------
#### [ Per-line approvals ]

*支援回溯相容性*。Change Manager 原始版本僅支援逐行核准。在此模型中，每個核准層級指定的每名核准者都是一個核准行。變更請求必須獲得每名核准者的核准，才能在該層級獲得核准。在 2023 年 1 月 23 日前這是唯一支援的核准模型。在此日期之前建立的變更範本會繼續支援逐行核准，但我們建議改用逐級核准。

如需此核准類型的主控台檢視和 JSON 範例，請參閱[逐行核准組態範例](approval-type-samples.md#per-line-approvals)。

------
#### [ Combined per-line and per-level approvals ]

*不建議使用*。在主控台中，**建置器**索引標籤不再支援新增逐行核准。但是，在某些情況下，您的變更範本可能會同時有逐行核准與逐級核准。如果您更新在 2023 年 1 月 23 日前建立的變更範本，或者如果您手動編輯變更範本的 YAML 內容，來建立或更新變更範本，就會發生這種情況。

如需此核准類型的主控台檢視和 JSON 範例，請參閱[逐級核准和逐行核准組態組合的範例](approval-type-samples.md#combined-approval-levels)。

------

**重要**  
雖然您可以建立結合逐行核准和逐級核准的變更範本，但不建議或不需要使用此種組態。核准數量要求更高的核准類型 (逐行核准和逐級核准) 優先。例如：  
如果變更範本在逐級核准中指定了需要三個核准，但又在逐行核准中指定了需要五個核准，則需要獲得五個核准。
如果變更範本在逐級核准中指定了需要四個核准，但又在逐行核准中指定了需要兩個核准，則需要獲得四個核准。

您可以透過手動編輯 YAML 或 JSON 內容，建立同時包含逐行核准和逐級核准的層級。然後，**建置器**索引標籤會顯示控制項，以指定層級與個別行所需的核准數量。不過，您使用主控台新增的新層級仍然只支援逐級核准組態。

## 變更請求通知和拒絕
<a name="notifications-and-rejections"></a>

Amazon SNS 通知  
使用變更範本建立變更請求時，系統會向為該層級核准通知指定之 Amazon Simple Notiﬁcation Service (Amazon SNS) 主題的訂閱用戶傳送通知。您可以在變更範本中指定通知主題，或允許建立變更請求的使用者指定主題。  
在某個層級獲得所需核准達到最低數量之後，系統會將通知傳送給為下個層級核准通知指定的 Amazon SNS 主題訂閱用戶 (核准者)，依此類推。  
確保您指定的 IAM 角色、群組和使用者合起來能提供的核准者數量能夠達到您指定的所需核准數量。例如，如果您只指定一個包含三名使用者的 IAM 群組作為核准者，就無法為該層級指定需要五個核准，只能指定三個或更少數量的核准。

變更請求拒絕  
無論指定多少核准層級和核准者，只要變更請求遭到一個拒絕，就能阻止該請求的執行手冊工作流程發生。

# Change Manager 核准類型範例
<a name="approval-type-samples"></a>

**Change Manager 可用性變更**  
AWS Systems Manager Change Manager 自 2025 年 11 月 7 日起，不再向新客戶開放。如果您想要使用 Change Manager，請在該日期之前註冊。現有客戶可以繼續正常使用該服務。如需詳細資訊，請參閱[AWS Systems Manager Change Manager可用性變更](https://docs.aws.amazon.com/systems-manager/latest/userguide/change-manager-availability-change.html)。

下列範例示範 Change Manager 中三種核准類型的主控台檢視和 JSON 內容。

**Topics**
+ [逐級核准組態範例](#per-level-approvals)
+ [逐行核准組態範例](#per-line-approvals)
+ [逐級核准和逐行核准組態組合的範例](#combined-approval-levels)

## 逐級核准組態範例
<a name="per-level-approvals"></a>

在下圖中顯示的逐級核准層級設定中，需要三個核准。這些核准可來自指定為核准者的任何 IAM 使用者、群組和角色組合。指定的核准者包括兩名 IAM 使用者 (John Stiles 和 Ana Carolina Silva)、一個包含三名成員的使用者群組 (`GroupOfThree`)，以及代表十名使用者的使用者角色 (`RoleOfTen`)。

如果 `GroupOfThree` 群組中的三名使用者都核准了該變更請求，則意味著變更請求在該層級已獲得核准。不需要獲得每個使用者、群組或角色的核准。最小數量的核准可以來自任何指定核准者的組合。建議您在 Change Manager 操作中使用逐級核准。

![\[核准層級顯示需要三個核准以及指定了四名指定核准者。\]](http://docs.aws.amazon.com/zh_tw/systems-manager/latest/userguide/images/Add-approval-2.png)


下列範例說明此組態的 YAML 程式碼部分。

**注意**  
這個版本的 YAML 程式碼包括額外的輸入 `MinRequiredApprovals` (首字母大寫 `M`）。此輸入的值表示需要從所有可用檢閱者獲得的核准數量。另請注意，`Approvers` 清單中每名核准者的 `minRequiredApprovals` (首字母小寫 `m`) 值為 `0` (零)。這表示核准者可以對整體核准做出貢獻，但並不強制要求。

```
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
templateInformation: >
  #### What is the purpose of this change?
    //truncated
```

## 逐行核准組態範例
<a name="per-line-approvals"></a>

在下圖中顯示的核准層級設定中，指定了四名核准者。其中包含兩名 IAM 使用者 (John Stiles 和 Ana Carolina Silva)、一個包含三名成員的使用者群組 (`GroupOfThree`)，以及代表十名使用者的使用者角色 (`RoleOfTen`)。處於回溯相容性考慮，仍然支援逐行核准，但不建議使用。

![\[核准層級顯示需要四個必要核准者 (逐行)。\]](http://docs.aws.amazon.com/zh_tw/systems-manager/latest/userguide/images/Add-approval-1.png)


如果使用此逐行核准組態，要核准此變更請求，需要所有核准者行 (John Stilles、Ana Carolina Silva、`GroupOfThree` 群組的一名成員以及 `RoleOfTen` 角色的一名成員) 都核准此變更請求。

下列範例說明此組態的 YAML 程式碼部分。

**注意**  
請注意，每個 `minRequiredApprovals` 核准者的值都是 `1`。這表示只需要從每名核准者獲得一個核准。

```
schemaVersion: "0.3"
emergencyChange: false
autoApprovable: false
mainSteps:
  - name: ApproveAction1
    action: aws:approve
    timeoutSeconds: 10000
    inputs:
      Message: Please approve this change request
      EnhancedApprovals:
        Approvers:
          - approver: John Stiles
            type: IamUser
            minRequiredApprovals: 1
          - approver: Ana Carolina Silva
            type: IamUser
            minRequiredApprovals: 1
          - approver: GroupOfThree
            type: IamGroup
            minRequiredApprovals: 1
          - approver: RoleOfTen
            type: IamRole
            minRequiredApprovals: 1
executableRunBooks:
  - name: AWS-HelloWorld
    version: $DEFAULT
templateInformation: >
  #### What is the purpose of this change?
    //truncated
```

## 逐級核准和逐行核准組態組合的範例
<a name="combined-approval-levels"></a>

在下圖中顯示的逐級核准和逐行核准組合設定中，為該層級指定了三個核准，但行級別指定了四個核准。核准數量要求更高的核准類型會優先於其他核准類型，因此此組態需要四個核准。不建議將逐級核准和逐行核准結合使用。

![\[核准層級顯示該層級指定需要三個核准，但行級別指定需要四個核准。\]](http://docs.aws.amazon.com/zh_tw/systems-manager/latest/userguide/images/Add-approval-3.png)


```
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: 1
          - approver: Ana Carolina Silva
            type: IamUser
            minRequiredApprovals: 1
          - approver: GroupOfThree
            type: IamGroup
            minRequiredApprovals: 1
          - approver: RoleOfTen
            type: IamRole
            minRequiredApprovals: 1
templateInformation: >
  #### What is the purpose of this change?
    //truncated
```

**Topics**
+ [關於變更範本中的核准](cm-approvals-templates.md)
+ [使用建置器建立變更範本](change-templates-custom-builder.md)
+ [使用編輯器建立變更範本](change-templates-custom-editor.md)
+ [使用命令列工具建立變更範本](change-templates-tools.md)

# 使用建置器建立變更範本
<a name="change-templates-custom-builder"></a>

**Change Manager 可用性變更**  
AWS Systems Manager Change Manager 自 2025 年 11 月 7 日起，不再向新客戶開放。如果您想要使用 Change Manager，請在該日期之前註冊。現有客戶可以繼續正常使用該服務。如需詳細資訊，請參閱[AWS Systems Manager Change Manager可用性變更](https://docs.aws.amazon.com/systems-manager/latest/userguide/change-manager-availability-change.html)。

在 Change Manager ( AWS Systems Manager中的工具) 中使用適用於變更範本的建置器，您可以設定在變更範本中定義的執行手冊工作流程，而無需使用 JSON 或 YAML 語法。指定您的選項之後，系統會將您的輸入轉換成 YAML 格式，從而讓 Systems Manager 可以用來執行 Runbook 工作流程。

**若要使用建置器建立變更範本**

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

1. 在導覽窗格中，選擇 **Change Manager**。

1. 選擇**建立範本**。

1. 對於 **Name** (名稱)，輸入可輕鬆識別用途的範本名稱，例如 **UpdateEC2LinuxAMI**。

1. 在 **Change template details** (變更範本詳細資訊) 區段中，執行下列動作：
   + 對於 **Description** (描述)，簡要介紹如何及何時使用您正建立的變更範本。

     此貓叔描述可協助建立變更請求的使用者判斷他們是否使用了正確的變更範本。它可協助檢閱變更請求的使用者了解是否應該核准請求。
   + 對於 **Change template type** (變更範本類型)，指定您要建立標準變更範本還是緊急變更範本。

     緊急變更範本用於必須進行變更的情況，即使使用中的行事曆中的事件以其他方式封鎖變更 AWS Systems Manager Change Calendar。從緊急變更範本建立的變更請求仍必須由其指定的核准者核准，但即使行事曆遭到封鎖，仍然可以執行請求的變更。
   + 對於 **Runbook options** (Runbook 選項)，指定使用者在建立變更請求時可以從中選擇的 Runbook。您可以新增單一 Runbook 或多個 Runbook。或者，您可以允許申請者指定要使用的 Runbook。在任何這些情況下，變更請求中只能包含一個 Runbook。
   + 對於 **Runbook**，選取 Runbook 的名稱，以及使用者可以為其變更請求選擇的 Runbook 版本。無論您新增多少個 Runbook 至變更範本，每個變更請求只能選取一個 Runbook。

     如果您之前選擇 **Any runbook can be used** (任何 Runbook 均可使用)，則不必指定 Runbook。
**提示**  
選取 Runbook 和 Runbook 版本，然後選擇 **View** (檢視) 以在 Systems Manager 文件介面中檢查 Runbook 的內容。

1. 在 **Template information** (範本資訊) 區段中，使用 Markdown 為從此變更範本建立變更請求的使用者輸入資訊。我們提供了一組問題，您可以為建立變更請求的使用者加入這些問題，或者您可以改為新增其他資訊和問題。
**注意**  
Markdown 是一種標示語言，可讓您新增維基樣式的描述至文件內，以及在文件內新增個別步驟。如需使用 Markdown 的相關資訊，請參閱[在 AWS中使用 Markdown](https://docs.aws.amazon.com/general/latest/gr/aws-markdown.html)。

   我們建議向使用者提供有關變更請求的問題，以供其回答，進而協助核准者決定是否授予每個變更請求，例如列出作為變更的一部分而執行所需的任何手動步驟和回復計劃。
**提示**  
在 **Hide preview** (隱藏預覽) 和 **Show preview** (顯示預覽) 之間切換，即可在撰寫時查看內容的外觀。

1. 在 **Change request approvals** (變更請求核准) 區段，執行下列動作：
   + (選用) 如果您要允許自動執行從此變更範本建立的變更請求，而不需由任何核准者進行檢閱 (變更凍結事件除外)，請選取 **Enable auto-approval** (啟用自動核准)。
**注意**  
在變更範本中啟用自動核准可為使用者提供繞過檢閱者的*選項*。在建立變更請求時，他們仍然可以選擇指定檢閱者。因此，您仍必須在變更範本中指定檢閱者選項。
**重要**  
如果您啟用變更範本的自動核准，則使用者可以使用該範本提交變更請求，而這些範本在執行前不需要檢閱者進行檢閱 (變更凍結事件核准者除外)。如果您想要限制特定使用者、群組或 IAM 角色提交自動核准請求，您可以針對此目的使用 IAM 政策中的條件。如需詳細資訊，請參閱[控制對自動核准 Runbook 工作流程的存取](change-manager-auto-approval-access.md)。
   + 在**此層級所需的核准數量**中，選擇從此變更範本建立之變更請求在此層級必須獲得的核准數量。
   + 若要新增強制性第一層級核准者，請選擇 **Add approver** (新增核准者)，然後從下列選項中選擇：
     + **範本指定的核准者** – 從您的帳戶中選擇一個或多個使用者、群組或 AWS Identity and Access Management (IAM) 角色，以核准從此變更範本建立的變更請求。使用此範本建立的任何變更請求都必須由您指定的每位核准者檢閱和核准。
     + **請求指定的核准者** – 提出變更請求的使用者會在提出請求時指定檢閱者，並且可以從您的帳戶中的使用者清單進行選擇。

       您在 **Required** (必填) 欄中輸入的數字會決定使用此變更範本的變更請求必須指定的檢閱者數量。
**重要**  
在 2023 年 1 月 23 日之前，**建置器**索引標籤僅支援逐行核准。使用**建置器**索引標籤新增的新變更範本和新增至現有變更範本的新層級僅支援逐級核准。建議您在 Change Manager 操作中僅使用逐級核准。  
如需詳細資訊，請參閱[關於變更範本中的核准](cm-approvals-templates.md)。
   + 對於 **SNS topic to notify approvers** (通知核准者的 SNS 主題)，請執行下列動作：

     1. 選擇下列其中一項，以在您的帳戶中指定 Amazon Simple Notification Service (Amazon SNS) 主題，進而用於向核准者傳送變更請求已準備好進行審核的通知：
        + **Enter an SNS Amazon Resource Name (ARN)** (輸入 SNS Amazon 資源名稱 (ARN)) – 對於 **Topic ARN** (主題 ARN)，輸入現有 Amazon SNS 主題的 ARN。此主題可以位於您組織的任何帳戶中。
        + **選取現有的 SNS 主題** – 對於 **Target notification topic** (目標通知主題) 中，選取您目前 AWS 帳戶中的現有 Amazon SNS 主題的 ARN。（如果您尚未在目前的 AWS 帳戶 和 中建立任何 Amazon SNS 主題，則無法使用此選項 AWS 區域。)
        + **建立變更請求時指定 SNS 主題** – 建立變更請求的使用者可以指定要用於通知的 Amazon SNS 主題。
**注意**  
您選取的 Amazon SNS 主題必須設定為指定其傳送的通知以及要傳送的訂閱者。其存取政策也必須將許可授予 Systems Manager，以便 Change Manager 可以傳送通知。如需相關資訊，請參閱[為 Change Manager 通知設定 Amazon SNS 主題](change-manager-sns-setup.md)。

     1. 選擇 **Add notification** (新增通知)。

1. (選用) 若要新增額外層級的核准者，請選擇 **Add approval level** (新增核准層級)，然後在為此範本指定的核准者和請求指定的核准者之間進行選擇。然後選擇 SNS 主題，以通知此層級的核准者。

   在第一層級核准者收到所有核准之後，系統會通知第二層級核准者，依此類推。

   您可以在每個範本中新增最多 5 個核准者層級。例如，您可能需要第一個層級技術角色的使用者核准，然後需要第二個層級的管理核准。

1. 在 **Monitoring** (監控) 區段，對於 **CloudWatch alarm to monitor** (要監控的 CloudWatch 警示)，輸入目前帳戶中的 Amazon CloudWatch 警示的名稱，以監控基於此範本的 Runbook 工作流程的進度。
**提示**  
若要建立新的警示，或檢閱您要指定的警示設定，請選擇 **Open the Amazon CloudWatch console** (開啟 Amazon CloudWatch 主控台)。如需有關使用 CloudWatch 警示的資訊，請參閱*《Amazon CloudWatch 使用者指南》*中的[使用 CloudWatch 警示](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/AlarmThatSendsEmail.html)。

1. 在 **Notifications** (通知) 區段中，執行以下操作：

   1. 選擇下列其中一項，指定帳戶中的 Amazon SNS 主題，用於傳送使用此變更範本建立之變更請求的通知：
      + **Enter an SNS Amazon Resource Name (ARN)** (輸入 SNS Amazon 資源名稱 (ARN)) – 對於 **Topic ARN** (主題 ARN)，輸入現有 Amazon SNS 主題的 ARN。此主題可以位於您組織的任何帳戶中。
      + **選取現有的 SNS 主題** – 對於 **Target notification topic** (目標通知主題) 中，選取您目前 AWS 帳戶中的現有 Amazon SNS 主題的 ARN。（如果您尚未在目前的 AWS 帳戶 和 中建立任何 Amazon SNS 主題，則無法使用此選項 AWS 區域。)
**注意**  
您選取的 Amazon SNS 主題必須設定為指定其傳送的通知以及要傳送的訂閱者。其存取政策也必須將許可授予 Systems Manager，以便 Change Manager 可以傳送通知。如需相關資訊，請參閱[為 Change Manager 通知設定 Amazon SNS 主題](change-manager-sns-setup.md)。

   1. 選擇 **Add notification** (新增通知)。

1. (選用) 在 **Tags** (標籤) 區段中，將一個或多個標籤索引鍵名稱/值對套用到變更範本。

   標籤是您指派給資源的選用性中繼資料。使用標籤，您即可以不同的方式 (例如用途、擁有者或環境) 將資源分類。例如，您可能想要標記變更範本，以識別變更範本所進行的類型以及其執行所在的環境。在這種情況下，您可以指定以下索引鍵名稱/值對：
   + `Key=TaskType,Value=InstanceRepair`
   + `Key=Environment,Value=Production`

1. 選擇 **Save and preview** (儲存與預覽)。

1. 檢閱您正在建立之變更範本的詳細資訊。

   如果您要在提交變更範本以供檢閱之前，對變更範本進行變更，請選擇 **Actions, Edit** (動作，編輯)。

   如果您對變更範本的內容感到滿意，請選擇 **Submit for review** (提交審核)。您組織或帳戶中已在 Change Manager 中的 **Settings** (設定) 標籤上指定為範本檢閱者的使用者會收到通知：新的變更範本正待其檢閱。

   如果已為變更範本指定 Amazon SNS 主題，則會在變更範本遭到拒絕或獲得核准時傳送通知。如果您沒有收到與此變更範本相關的通知，您可以稍後返回 Change Manager，以檢查其狀態。

# 使用編輯器建立變更範本
<a name="change-templates-custom-editor"></a>

**Change Manager 可用性變更**  
AWS Systems Manager Change Manager 自 2025 年 11 月 7 日起，不再向新客戶開放。如果您想要使用 Change Manager，請在該日期之前註冊。現有客戶可以繼續正常使用該服務。如需詳細資訊，請參閱[AWS Systems Manager Change Manager可用性變更](https://docs.aws.amazon.com/systems-manager/latest/userguide/change-manager-availability-change.html)。

使用本主題中的步驟，輸入 JSON 或 YAML 以在 Change Manager ( AWS Systems Manager中的工具) 中設定變更範本，而不是使用主控台控制項。

**若要使用編輯器建立變更範本**

1. 在導覽窗格中，選擇 **Change Manager**。

1. 選擇**建立範本**。

1. 對於 **Name** (名稱)，輸入可輕鬆識別用途的範本名稱，例如 **RestartEC2LinuxInstance**。

1. 在 **Change template details** (變更範本詳細資訊) 上方，選擇 **Editor** (編輯器)。

1. 在 **Document editor** (文件編輯器) 區段中，選擇 **Edit** (編輯)，然後輸入變更範本的 JSON 或 YAML 內容。

   下列是 範例。
**注意**  
使用參數 `minRequiredApprovals` 來指定必須要有多少指定層級的審查者核准使用此範本建立的變更請求。  
此範例會示範兩個核准層級。您最多可以指定五個核准層級，但只需要一個層級。  
在第一級中，特定使用者 "John-Doe" 必須核准每個變更請求。接下來，IAM 角色 `Admin` 的任何三個成員必須核准變更請求。  
如需有關變更範本核准的詳細資訊，請參閱[關於變更範本中的核准](cm-approvals-templates.md)。

------
#### [ YAML ]

   ```
   description: >-
     This change template demonstrates the feature set available for creating
     change templates for Change Manager. This template starts a Runbook workflow
     for the Automation runbook called AWS-HelloWorld.
   templateInformation: >
     ### Document Name: HelloWorldChangeTemplate
   
     ## What does this document do?
   
     This change template demonstrates the feature set available for creating
     change templates for Change Manager. This template starts a Runbook workflow
     for the Automation runbook called AWS-HelloWorld.
   
     ## Input Parameters
   
     * ApproverSnsTopicArn: (Required) Amazon Simple Notification Service ARN for
     approvers.
   
     * Approver: (Required) The name of the approver to send this request to.
   
     * ApproverType: (Required) The type of reviewer.
       * Allowed Values: IamUser, IamGroup, IamRole, SSOGroup, SSOUser
   
     ## Output Parameters
   
     This document has no outputs
   schemaVersion: '0.3'
   parameters:
     ApproverSnsTopicArn:
       type: String
       description: Amazon Simple Notification Service ARN for approvers.
     Approver:
       type: String
       description: IAM approver
     ApproverType:
       type: String
       description: >-
         Approver types for the request. Allowed values include IamUser, IamGroup,
         IamRole, SSOGroup, and SSOUser.
   executableRunBooks:
     - name: AWS-HelloWorld
       version: '1'
   emergencyChange: false
   autoApprovable: false
   mainSteps:
     - name: ApproveAction1
       action: 'aws:approve'
       timeoutSeconds: 3600
       inputs:
         Message: >-
           A sample change request has been submitted for your review in Change
           Manager. You can approve or reject this request.
         EnhancedApprovals:
           NotificationArn: '{{ ApproverSnsTopicArn }}'
           Approvers:
             - approver: John-Doe
               type: IamUser
               minRequiredApprovals: 1
     - name: ApproveAction2
       action: 'aws:approve'
       timeoutSeconds: 3600
       inputs:
         Message: >-
           A sample change request has been submitted for your review in Change
           Manager. You can approve or reject this request.
         EnhancedApprovals:
           NotificationArn: '{{ ApproverSnsTopicArn }}'
           Approvers:
             - approver: Admin
               type: IamRole
               minRequiredApprovals: 3
   ```

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

   ```
   {
      "description": "This change template demonstrates the feature set available for creating
     change templates for Change Manager. This template starts a Runbook workflow
     for the Automation runbook called AWS-HelloWorld",
      "templateInformation": "### Document Name: HelloWorldChangeTemplate\n\n
       ## What does this document do?\n
       This change template demonstrates the feature set available for creating change templates for Change Manager. 
       This template starts a Runbook workflow for the Automation runbook called AWS-HelloWorld.\n\n
       ## Input Parameters\n* ApproverSnsTopicArn: (Required) Amazon Simple Notification Service ARN for approvers.\n
       * Approver: (Required) The name of the approver to send this request to.\n
       * ApproverType: (Required) The type of reviewer.  * Allowed Values: IamUser, IamGroup, IamRole, SSOGroup, SSOUser\n\n
       ## Output Parameters\nThis document has no outputs\n",
      "schemaVersion": "0.3",
      "parameters": {
         "ApproverSnsTopicArn": {
            "type": "String",
            "description": "Amazon Simple Notification Service ARN for approvers."
         },
         "Approver": {
            "type": "String",
            "description": "IAM approver"
         },
         "ApproverType": {
            "type": "String",
            "description": "Approver types for the request. Allowed values include IamUser, IamGroup, IamRole, SSOGroup, and SSOUser."
         }
      },
      "executableRunBooks": [
         {
            "name": "AWS-HelloWorld",
            "version": "1"
         }
      ],
      "emergencyChange": false,
      "autoApprovable": false,
      "mainSteps": [
         {
            "name": "ApproveAction1",
            "action": "aws:approve",
            "timeoutSeconds": 3600,
            "inputs": {
               "Message": "A sample change request has been submitted for your review in Change Manager. You can approve or reject this request.",
               "EnhancedApprovals": {
                  "NotificationArn": "{{ ApproverSnsTopicArn }}",
                  "Approvers": [
                     {
                        "approver": "John-Doe",
                        "type": "IamUser",
                        "minRequiredApprovals": 1
                     }
                  ]
               }
            }
         },
           {
            "name": "ApproveAction2",
            "action": "aws:approve",
            "timeoutSeconds": 3600,
            "inputs": {
               "Message": "A sample change request has been submitted for your review in Change Manager. You can approve or reject this request.",
               "EnhancedApprovals": {
                  "NotificationArn": "{{ ApproverSnsTopicArn }}",
                  "Approvers": [
                     {
                        "approver": "Admin",
                        "type": "IamRole",
                        "minRequiredApprovals": 3                  
                     }
                  ]
               }
            }
         }
      ]
   }
   ```

------

1. 選擇 **Save and preview** (儲存與預覽)。

1. 檢閱您正在建立之變更範本的詳細資訊。

   如果您要在提交變更範本以供檢閱之前，對變更範本進行變更，請選擇 **Actions, Edit** (動作，編輯)。

   如果您對變更範本的內容感到滿意，請選擇 **Submit for review** (提交審核)。您組織或帳戶中已在 Change Manager 中的 **Settings** (設定) 標籤上指定為範本檢閱者的使用者會收到通知：新的變更範本正待其檢閱。

   如果已為變更範本指定 Amazon Simple Notification Service (Amazon SNS) 主題，則會在變更範本遭到拒絕或獲得核准時傳送通知。如果您沒有收到與此變更範本相關的通知，您可以稍後返回 Change Manager，以檢查其狀態。

# 使用命令列工具建立變更範本
<a name="change-templates-tools"></a>

**Change Manager 可用性變更**  
AWS Systems Manager Change Manager 自 2025 年 11 月 7 日起，不再向新客戶開放。如果您想要使用 Change Manager，請在該日期之前註冊。現有客戶可以繼續正常使用該服務。如需詳細資訊，請參閱[AWS Systems Manager Change Manager可用性變更](https://docs.aws.amazon.com/systems-manager/latest/userguide/change-manager-availability-change.html)。

下列程序說明如何使用 AWS Command Line Interface (AWS CLI) （在 Linux、 或 上Windows Server)macOS，或在 中的Change Manager工具 中 AWS Tools for Windows PowerShell 建立變更請求 AWS Systems Manager。

**若要建立變更範本**

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. 在您的本機電腦建立名稱如 `MyChangeTemplate.json` 的 JSON 檔案，然後將您變更範本中的內容貼至其中。
**注意**  
變更範本會使用 0.3 版本的結構描述，其中並不包含與自動化 Runbook 相同的所有支援。

   下列是 範例。
**注意**  
使用參數 `minRequiredApprovals` 來指定必須要有多少指定層級的審查者核准使用此範本建立的變更請求。  
此範例會示範兩個核准層級。您最多可以指定五個核准層級，但只需要一個層級。  
在第一級中，特定使用者 "John-Doe" 必須核准每個變更請求。接下來，IAM 角色 `Admin` 的任何三個成員必須核准變更請求。  
如需有關變更範本核准的詳細資訊，請參閱[關於變更範本中的核准](cm-approvals-templates.md)。

   ```
   {
      "description": "This change template demonstrates the feature set available for creating
     change templates for Change Manager. This template starts a Runbook workflow
     for the Automation runbook called AWS-HelloWorld",
      "templateInformation": "### Document Name: HelloWorldChangeTemplate\n\n
       ## What does this document do?\n
       This change template demonstrates the feature set available for creating change templates for Change Manager. 
       This template starts a Runbook workflow for the Automation runbook called AWS-HelloWorld.\n\n
       ## Input Parameters\n* ApproverSnsTopicArn: (Required) Amazon Simple Notification Service ARN for approvers.\n
       * Approver: (Required) The name of the approver to send this request to.\n
       * ApproverType: (Required) The type of reviewer.  * Allowed Values: IamUser, IamGroup, IamRole, SSOGroup, SSOUser\n\n
       ## Output Parameters\nThis document has no outputs\n",
      "schemaVersion": "0.3",
      "parameters": {
         "ApproverSnsTopicArn": {
            "type": "String",
            "description": "Amazon Simple Notification Service ARN for approvers."
         },
         "Approver": {
            "type": "String",
            "description": "IAM approver"
         },
         "ApproverType": {
            "type": "String",
            "description": "Approver types for the request. Allowed values include IamUser, IamGroup, IamRole, SSOGroup, and SSOUser."
         }
      },
      "executableRunBooks": [
         {
            "name": "AWS-HelloWorld",
            "version": "1"
         }
      ],
      "emergencyChange": false,
      "autoApprovable": false,
      "mainSteps": [
         {
            "name": "ApproveAction1",
            "action": "aws:approve",
            "timeoutSeconds": 3600,
            "inputs": {
               "Message": "A sample change request has been submitted for your review in Change Manager. You can approve or reject this request.",
               "EnhancedApprovals": {
                  "NotificationArn": "{{ ApproverSnsTopicArn }}",
                  "Approvers": [
                     {
                        "approver": "John-Doe",
                        "type": "IamUser",
                        "minRequiredApprovals": 1
                     }
                  ]
               }
            }
         },
           {
            "name": "ApproveAction2",
            "action": "aws:approve",
            "timeoutSeconds": 3600,
            "inputs": {
               "Message": "A sample change request has been submitted for your review in Change Manager. You can approve or reject this request.",
               "EnhancedApprovals": {
                  "NotificationArn": "{{ ApproverSnsTopicArn }}",
                  "Approvers": [
                     {
                        "approver": "Admin",
                        "type": "IamRole",
                        "minRequiredApprovals": 3                  
                     }
                  ]
               }
            }
         }
      ]
   }
   ```

1. 執行以下命令來建立變更範本。

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

   ```
   aws ssm create-document \
       --name MyChangeTemplate \
       --document-format JSON \
       --document-type Automation.ChangeTemplate \
       --content file://MyChangeTemplate.json \
       --tags Key=tag-key,Value=tag-value
   ```

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

   ```
   aws ssm create-document ^
       --name MyChangeTemplate ^
       --document-format JSON ^
       --document-type Automation.ChangeTemplate ^
       --content file://MyChangeTemplate.json ^
       --tags Key=tag-key,Value=tag-value
   ```

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

   ```
   $json = Get-Content -Path "C:\path\to\file\MyChangeTemplate.json" | Out-String
   New-SSMDocument `
       -Content $json `
       -Name "MyChangeTemplate" `
       -DocumentType "Automation.ChangeTemplate" `
       -Tags "Key=tag-key,Value=tag-value"
   ```

------

   如需您可以指定之相關選項的資訊，請參閱 [https://docs.aws.amazon.com/cli/latest/reference/ssm/create-document.html](https://docs.aws.amazon.com/cli/latest/reference/ssm/create-document.html)。

   系統會傳回如下資訊。

   ```
   {
      "DocumentDescription":{
         "CreatedDate":1.585061751738E9,
         "DefaultVersion":"1",
         "Description":"Use this template to update an EC2 Linux AMI. Requires one
         approver specified in the template and an approver specified in the request.",
         "DocumentFormat":"JSON",
         "DocumentType":"Automation",
         "DocumentVersion":"1",
         "Hash":"0d3d879b3ca072e03c12638d0255ebd004d2c65bd318f8354fcde820dEXAMPLE",
         "HashType":"Sha256",
         "LatestVersion":"1",
         "Name":"MyChangeTemplate",
         "Owner":"123456789012",
         "Parameters":[
            {
               "DefaultValue":"",
               "Description":"Level one approvers",
               "Name":"LevelOneApprovers",
               "Type":"String"
            },
            {
               "DefaultValue":"",
               "Description":"Level one approver type",
               "Name":"LevelOneApproverType",
               "Type":"String"
            },
      "cloudWatchMonitors": {
         "monitors": [
            "my-cloudwatch-alarm"
         ]
      }
         ],
         "PlatformTypes":[
            "Windows",
            "Linux"
         ],
         "SchemaVersion":"0.3",
         "Status":"Creating",
         "Tags":[
   
         ]
      }
   }
   ```

您組織或帳戶中已在 Change Manager 中的 **Settings** (設定) 標籤上指定為範本檢閱者的使用者會收到通知：新的變更範本正待其檢閱。

如果已為變更範本指定 Amazon Simple Notification Service (Amazon SNS) 主題，則會在變更範本遭到拒絕或獲得核准時傳送通知。如果您沒有收到與此變更範本相關的通知，您可以稍後返回 Change Manager，以檢查其狀態。

# 檢閱及核准或拒絕變更範本
<a name="change-templates-review"></a>

**Change Manager 可用性變更**  
AWS Systems Manager Change Manager 自 2025 年 11 月 7 日起，不再向新客戶開放。如果您想要使用 Change Manager，請在該日期之前註冊。現有客戶可以繼續正常使用該服務。如需詳細資訊，請參閱[AWS Systems Manager Change Manager可用性變更](https://docs.aws.amazon.com/systems-manager/latest/userguide/change-manager-availability-change.html)。

如果您在 Change Manager ( AWS Systems Manager中的工具) 中被指定為變更範本的檢閱者，則當新的變更範本或變更範本的新版本有待您檢閱時，您會收到通知。Amazon Simple Notification Service (Amazon SNS) 主題會傳送通知。

**注意**  
此功能取決於您的帳戶是否已設定為使用 Amazon SNS 主題來傳送變更範本檢閱通知。如需有關指定範本檢閱者通知主題的資訊，請參閱 [任務 1：設定 Change Manager 使用者身分識別管理和範本檢閱者](change-manager-account-setup.md#cm-configure-account-task-1)。

若要檢閱變更範本，請遵循通知中的連結，登入 AWS 管理主控台，然後遵循此程序中的步驟。

**若要檢閱及核准或拒絕變更範本**

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

1. 在導覽窗格中，選擇 **Change Manager**。

1. 在 **Overview** (概觀) 標籤底部的 **Change templates** (變更範本) 區段中，選擇 **Pending review** (有待檢閱) 中的數字。

1. 在 **Change templates** (變更範本) 清單中，找到並選擇要檢閱的變更範本的名稱。

1. 在摘要頁面中，檢閱變更範本的提議內容，然後執行下列其中一項動作：
   + 若要核准允許在變更請求中使用變更範本，請依次選擇 **Approve** (核准)。
   + 若要拒絕變更範本，以防止變更請求中使用變更範本，請選擇 **Reject** (拒絕)。

# 刪除變更範本
<a name="change-templates-delete"></a>

**Change Manager 可用性變更**  
AWS Systems ManagerChange Manager 自 2025 年 11 月 7 日起，不再向新客戶開放。如果您想要使用 Change Manager，請在該日期之前註冊。現有客戶可以繼續正常使用服務。如需詳細資訊，請參閱[AWS Systems ManagerChange Manager可用性變更](https://docs.aws.amazon.com/systems-manager/latest/userguide/change-manager-availability-change.html)。

本主題說明如何刪除您在 Change Manager (Systems Manager 中的工具) 中建立的範本。如果您正在使用組織的 Change Manager，則會在您的委派管理員帳戶中執行此處理程序。

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

1. 在導覽窗格中，選擇 **Change Manager**。

1. 選擇 **Templates (範本)** 標籤。

1. 選擇要刪除的範本名稱。

1. 選擇 **Actions, Delete template** (動作、刪除範本)。

1. 在確認對話方塊中輸入 **DELETE**，然後選擇 **Delete** (刪除)。

# 使用變更請求
<a name="change-requests"></a>

**Change Manager 可用性變更**  
AWS Systems ManagerChange Manager 自 2025 年 11 月 7 日起，不再向新客戶開放。如果您想要使用 Change Manager，請在該日期之前註冊。現有客戶可以繼續正常使用服務。如需詳細資訊，請參閱[AWS Systems ManagerChange Manager可用性變更](https://docs.aws.amazon.com/systems-manager/latest/userguide/change-manager-availability-change.html)。

變更請求是在 中執行 Automation Runbook Change Manager的請求，以更新 AWS 或內部部署環境中的一或多個資源。變更請求是使用變更範本建立的。

您在 Change Manager ( AWS Systems Manager中的工具) 中建立變更請求後，您組織或帳戶中的一個或多個核准者必須檢閱並核准該請求。如果沒有所需的核准，則不允許執行會變更您請求的 Runbook 工作流程。

**Topics**
+ [建立變更請求](change-requests-create.md)
+ [檢閱及核准或拒絕變更請求](change-requests-review.md)

# 建立變更請求
<a name="change-requests-create"></a>

**Change Manager 可用性變更**  
AWS Systems Manager Change Manager 自 2025 年 11 月 7 日起，不再向新客戶開放。如果您想要使用 Change Manager，請在該日期之前註冊。現有客戶可以繼續正常使用該服務。如需詳細資訊，請參閱[AWS Systems Manager Change Manager可用性變更](https://docs.aws.amazon.com/systems-manager/latest/userguide/change-manager-availability-change.html)。

當您在 Change Manager ( AWS Systems Manager中的工具) 中建立變更請求時，您選取的變更範本通常會執行下列動作：
+ 指定變更請求的核准者，或指定需要多少次核准
+ 指定 Amazon Simple Notification Service (Amazon SNS) 主題，以便通知核准者有關變更請求的資訊
+ 指定 Amazon CloudWatch 警示，以監控變更請求的 Runbook 工作流程
+ 識別您可以選擇哪些自動化 Runbook 來進行請求的變更

在某些情況下，可能會設定變更範本，因此您可以指定要使用的自動化 Runbook，並指定應該檢閱和核准請求的人員。

**重要**  
如果您在整個組織中使用 Change Manager，我們建議始終從委派管理員帳戶進行變更。雖然您可以從組織中的其他帳戶進行變更，但這些變更將不會在受委派管理員帳戶中報告，也不可在其中檢視。

**Topics**
+ [關於變更請求核准](#cm-approvals-requests)
+ [建立變更請求 (主控台)](#change-requests-create-console)
+ [建立變更請求 (AWS CLI)](#change-requests-create-cli)

## 關於變更請求核准
<a name="cm-approvals-requests"></a>

視變更範本中指定的要求而定，您建立的變更請求最多可以設定五個*層級*的核准，獲得這些層級的核准後，請求的執行手冊工作流程才能進行。對於每個層級，範本建立者最多可以指定五個潛在*核准者*。核准者不限於單一使用者。從這個意義上講，核准者也可以是 IAM 群組或 IAM 角色。對於 IAM 群組和 IAM 角色，屬於該群組或角色的一或多名使用者可以提供核准，以獲得變更請求所需的核准總數。範本建立者指定的核准者數量可以比變更範本要求的更多。

**原始的核准工作流程和/或更新的核准工作流程**  
使用 2023 年 1 月 23 日之前建立的變更範本時，必須獲得每個指定核准者的核准，變更請求才能在該層級獲得核准。例如，在以下影像中顯示的核准層級設定中，指定了四個核准者。指定的核准者包括兩名使用者 (John Stiles 和 Ana Carolina Silva)、一個包含三名成員的使用者群組 (GrouPofThree)，以及代表十名使用者的使用者角色 (RoleOfTen)。

![\[核准層級顯示需要四個必要核准者 (逐行)。\]](http://docs.aws.amazon.com/zh_tw/systems-manager/latest/userguide/images/Add-approval-1.png)


變更請求若要在此層級獲得核准，必須獲得 John Stiles、Ana Carolina Silva、`GroupOfThree` 群組成員之一，以及 `RoleOfTen` 角色的一名成員的核准。

如果使用在 2023 年 1 月 23 日當日或之後建立的變更範本，範本建立者可以針對每個核准層級指定所需的核准總數。這些核准可來自指定為核准者的任何使用者、群組和角色組合。變更範本可以設定在一個層級只需要一個核准，但可以指定兩名單獨的使用者、兩個群組和一個角色作為潛在核准者。

例如，在下圖所示的核准層級區域中，需要三個核准。範本指定的核准者包括兩名使用者 (John Stiles 和 Ana Carolina Silva)、一個包含三名成員的使用者群組 (`GroupOfThree`)，以及代表十名使用者的使用者角色 (`RoleOfTen`)。

![\[核准層級顯示需要三個核准以及指定了四名指定核准者。\]](http://docs.aws.amazon.com/zh_tw/systems-manager/latest/userguide/images/Add-approval-2.png)


如果 `GroupOfThree` 群組中的三名使用者都核准了您的變更請求，則意味著變更請求在該層級已獲得核准。不需要獲得每個使用者、群組或角色的核准。最小數量的核准可以來自任何潛在核准者的組合。

建立變更請求後，系統會將通知傳送給指定為接收該層級核准通知的 Amazon SNS 主題的訂閱用戶。變更範本建立者可能已指定必須使用的通知主題或允許您進行指定。

在某個層級獲得的核准數量達到最低數量之後，系統會將通知傳送給下一層級核准通知的 Amazon SNS 主題的訂閱用戶 (核准者)，依此類推。

無論指定多少核准層級和核准者，只要變更請求遭到一個拒絕，就能阻止該請求的執行手冊工作流程發生。

## 建立變更請求 (主控台)
<a name="change-requests-create-console"></a>

下列處理程序說明如何使用 Systems Manager 主控台來建立變更請求。

**若要建立變更請求 (主控台)**

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

1. 在導覽窗格中，選擇 **Change Manager**。

1. 選擇 **Create request** (建立請求)。

1. 搜尋並選取您要用於此變更請求的變更範本。

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

1. 對於 **Name** (名稱)，輸入可輕鬆識別用途的變更請求名稱，例如 **UpdateEC2LinuxAMI-us-east-2**。

1. 對於 **Runbook** (Runbook)，選取您要用來進行請求的變更的 Runbook。
**注意**  
如果選取 Runbook 的選項不可用，則變更範本作者已指定必須使用的 Runbook。

1. 對於 **Change request information** (變更請求資訊)，請使用 Markdown 提供有關變更請求的其他資訊，以協助檢閱者決定是否要核准或拒絕變更請求。您使用的範本作者可能已提供指示或供您回答的問題。
**注意**  
Markdown 是一種標示語言，可讓您新增維基樣式的描述至文件內，以及在文件內新增個別步驟。如需使用 Markdown 的相關資訊，請參閱[在 AWS中使用 Markdown](https://docs.aws.amazon.com/general/latest/gr/aws-markdown.html)。

1. 在 **Workflow start time** (工作流程開始時間) 區段，選擇以下其中一項：
   + **在排定的時間執行作業** – 對於 **Requested start time** (請求的開始時間)，輸入您提議執行此請求之 Runbook 工作流程的日期和時間。對於 **Estimated end time** (預測結束時間)，輸入您預期完成 Runbook 工作流程的日期和時間。(該時間只是您提供給檢閱者的預測值)。
**提示**  
選擇 **View Change Calendar** (檢視變更行事曆)，檢查您指定的時間是否有任何封鎖事件。
   + **在核准之後，僅可執行操作** – 如果已核准變更請求，Runbook 工作流程會在可進行變更的非限制時期內立即執行。

1. 在 **Change request approvals** (變更請求核准) 區段，執行下列動作：

   1. 如果出現 **Approval type** (核准類型)，請選擇以下其中一個選項：
      + **Automatic approval** (自動核准) – 您選取的變更範本設定為允許自動執行變更請求，而不需經任何核准者檢閱。繼續步驟 11。
**注意**  
控管您使用 Systems Manager 的 IAM 政策中指定的許可，不得限制您提交自動核准變更請求，以便自動執行。
      + **Specify approvers** (指定核准者) – 您必須新增一個或多個使用者、群組或 IAM 角色，才能檢閱並核准此變更請求。
**注意**  
即使控管 Systems Manager 使用的 IAM 政策中指定的許可允許您執行自動核准變更請求，您也可以選擇指定檢閱者。

   1. 選擇**新增核准者**，然後從可用的檢閱者清單中選取一或多個使用者、群組或 AWS Identity and Access Management (IAM) 角色。
**注意**  
可能已經指定一個或多個核准者。這表示已在您選取的變更範本中指定強制核准者。無法從請求中移除這些核准者。如果無法使用**新增核准者**按鈕，則表示您選擇的範本不允許將其他檢閱者新增至請求。

      如需有關變更請求核准的詳細資訊，請參閱[關於變更請求核准](#cm-approvals-requests)。

   1. 在 **SNS topic to notify approvers** (通知核准者的 SNS 主題) 下，選擇以下其中一項，以在您的帳戶中指定 Amazon SNS 主題，進而用於向您新增到此變更請求的核准者傳送通知。
**注意**  
如果指定 Amazon SNS 主題的選項不可用，則您選取的變更範本已指定要使用的 Amazon SNS 主題。
      + **Enter an SNS Amazon Resource Name (ARN)** (輸入 SNS Amazon 資源名稱 (ARN)) – 對於 **Topic ARN** (主題 ARN)，輸入現有 Amazon SNS 主題的 ARN。此主題可以位於您組織的任何帳戶中。
      + **Select an existing SNS topic** (選取現有的 SNS 主題) – 對於 **Target notification topic **(目標通知主題) 中，選取您目前帳戶中的現有 Amazon SNS 主題的 ARN。（如果您尚未在目前的 AWS 帳戶 和 中建立任何 Amazon SNS 主題，則無法使用此選項 AWS 區域。)
**注意**  
您選取的 Amazon SNS 主題必須設定為指定其傳送的通知以及要傳送的訂閱者。其存取政策也必須將許可授予 Systems Manager，以便 Change Manager 可以傳送通知。如需相關資訊，請參閱[為 Change Manager 通知設定 Amazon SNS 主題](change-manager-sns-setup.md)。

   1. 選擇 **Add notification** (新增通知)。

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

1. 對於 **IAM role** (IAM 角色)，*在您的目前帳戶中*，選取 IAM 角色，而該角色具有執行為此變更請求指定的 Runbook 所需的許可。

   此角色也稱為自動化的服務角色，或擔任角色。如需有關此角色的詳細資訊，請參閱 [設定自動化](automation-setup.md)。

1. 在 **Deployment location** (部署位置) 區段中，選擇下列其中一個選項：
**注意**  
如果您 AWS 帳戶 僅使用 Change Manager搭配單一 ，而不是搭配 中設定的組織 AWS Organizations，則不需要指定部署位置。
   + **將變更套用至此帳戶** – Runbook 工作流程僅在目前帳戶中執行。對於組織而言，這表示委派管理員帳戶。
   + **Apply change to multiple organizational units (OUs)** (將變更套用至多個組織單位 (OU)) – 執行下列動作：

     1. 對於 **Accounts and organizational units (OUs)** (帳戶和組織單位 (OU))，輸入組織中成員帳戶的 ID (格式為 **123456789012**)，或組織單位的 ID (格式為 **o-o96EXAMPLE**)。

     1. (選用) **Execution role name** (執行角色名稱)，*在目標帳戶*或具有執行為此變更要求指定的 Runbook 所需許可的 OU 中，輸入 IAM 角色的名稱。您指定之任何 OU 中的所有帳戶都應該對此角色使用相同的名稱。

     1. (選用) 為要指定的每個其他帳戶或 OU 選擇 **Add another target location** (新增另一個目標位置)，然後重複步驟 a 和 b。

     1. 針對**目標 AWS 區域**，選取要進行變更的區域，例如`Ohio (us-east-2)`美國東部 （俄亥俄） 區域。

     1. 展開 **Rate control** (速率控制)。

        對於 **Concurrency** (並行)，輸入數字，然後從清單中選取這是否代表 Runbook 工作流程可同時執行的帳戶數目或百分比。

        對於 **Error threshold** (錯誤閾值)，輸入數字，然後從清單中選取這是否代表 Runbook 工作流程在停止操作之前可能會失敗的帳戶數目或百分比。

1. 在 **Deployment targets** (部署目標) 區段中，執行下列動作：

   1. 選擇下列其中一項：
      + **Single resource** (單一資源) – 只針對一個資源進行變更。例如，單一節點或單一 Amazon Machine Image (AMI)，視此變更請求的 Runbook 中定義的操作而定。
      + **Multiple resources** (多個資源) – 對於 **Parameter** (參數)，從 Runbook 中為此變更請求選取可用參數。此選項會反映正在更新的資源類型。

        例如，如果此變更請求的 Runbook 是 `AWS-RetartEC2Instance`，您可能選擇 `InstanceId`，然後從下列選項中進行選取，定義要更新的執行個體：
        + **Specify tags** (指定標籤) – 輸入鍵值對，其要更新的所有資源都應使用此鍵值對標記。
        + **Choose a resource group** (選擇資源群組) – 選擇要更新之所有資源所屬的資源群組名稱。
        + **Specify parameter values** (指定參數值) – 識別要在 **Runbook parameters** (Runbook 參數) 區段中更新的資源。
        + **Target all instances** (將所有執行個體設為目標) – 對目標位置中的所有受管節點進行變更。

   1. 如果您選擇 **Multiple resources** (多個資源)，展開 **Rate control** (速率控制)。

      對於 **Concurrency** (並行)，輸入數字，然後從清單中選取這是否代表 Runbook 工作流程可同時更新的目標數目或百分比。

      對於 **Error threshold** (錯誤閾值)，輸入數字，然後從清單中選取這是否代表更新在停止操作之前可能會失敗的目標數目或百分比。

1. 如果您選擇 **Specify parameter values** (指定參數值) 來更新上一個步驟中的多個資源：在 **Runbook parameters** (Runbook 參數) 區段中，指定所需輸入參數的值。您必須提供的參數值是以與您選擇的變更範本關聯的 Automation Runbook 內容為基礎。

   例如，如果變更範本使用 `AWS-RetartEC2Instance` Runbook，則必須為 **InstanceId** 參數輸入一個或多個執行個體 ID。或者，選擇 **Show interactive instance picker** (顯示互動式執行個體選擇器)，然後逐一選取可用的執行個體。

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

1. 在 **Review and submit** (檢閱及提交) 頁面上，再次檢查您為此變更請求指定的資源和選項。

   對於任何您想要變更的區段，選擇 **Edit** (編輯) 按鈕。

   當您對變更請求的詳細資訊感到滿意時，請選擇 **Submit for approval** (提交核准)。

如果已為所選請求的變更範本指定 Amazon SNS 主題，則會在請求遭到拒絕或獲得核准時傳送通知。如果您沒有收到請求的通知，您可以返回 Change Manager，檢查請求的狀態。

## 建立變更請求 (AWS CLI)
<a name="change-requests-create-cli"></a>

您可以使用 AWS Command Line Interface (AWS CLI) 建立變更請求，方法是在 JSON 檔案中指定變更請求的選項和參數，並使用 `--cli-input-json`選項將其包含在命令中。

**若要建立變更請求 (AWS CLI)**

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. 在您的本機電腦建立名稱如 `MyChangeRequest.json` 的 JSON 檔案，然後將以下內容貼至其中。

   將*預留位置*取代為變更請求的值。
**注意**  
此範例 JSON 會使用 `AWS-HelloWorldChangeTemplate` 變更範本和 `AWS-HelloWorld` Runbook 建立變更請求。若要針對自己的變更請求調整此範例，請參閱《AWS Systems Manager API 參考》**中的 [https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_StartChangeRequestExecution.html](https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_StartChangeRequestExecution.html) 一節，以獲取所有可用參數的相關資訊  
如需有關變更請求核准的詳細資訊，請參閱[關於變更請求核准](#cm-approvals-requests)。

   ```
   {
       "ChangeRequestName": "MyChangeRequest",
       "DocumentName": "AWS-HelloWorldChangeTemplate",
       "DocumentVersion": "$DEFAULT",
       "ScheduledTime": "2021-12-30T03:00:00",
       "ScheduledEndTime": "2021-12-30T03:05:00",
       "Tags": [
           {
               "Key": "Purpose",
               "Value": "Testing"
           }
       ],
       "Parameters": {
           "Approver": [
               "JohnDoe"
           ],
           "ApproverType": [
               "IamUser"
           ],
           "ApproverSnsTopicArn": [
               "arn:aws:sns:us-east-2:123456789012:MyNotificationTopic"
           ]
       },
       "Runbooks": [
           {
               "DocumentName": "AWS-HelloWorld",
               "DocumentVersion": "1",
               "MaxConcurrency": "1",
               "MaxErrors": "1",
               "Parameters": {
                   "AutomationAssumeRole": [
                       "arn:aws:iam::123456789012:role/MyChangeManagerAssumeRole"
                   ]
               }
           }
       ],
       "ChangeDetails": "### Document Name: HelloWorldChangeTemplate\n\n## What does this document do?\nThis change template demonstrates the feature set available for creating change templates for Change Manager. This template starts a Runbook workflow for the Automation document called AWS-HelloWorld.\n\n## Input Parameters\n* ApproverSnsTopicArn: (Required) Amazon Simple Notification Service ARN for approvers.\n* Approver: (Required) The name of the approver to send this request to.\n* ApproverType: (Required) The type of reviewer.\n  * Allowed Values: IamUser, IamGroup, IamRole, SSOGroup, SSOUser\n\n## Output Parameters\nThis document has no outputs \n"
   }
   ```

1. 在您建立 JSON 檔案的目錄裡執行下列命令。

   ```
   aws ssm start-change-request-execution --cli-input-json file://MyChangeRequest.json
   ```

   系統會傳回如下資訊。

   ```
   {
       "AutomationExecutionId": "b3c1357a-5756-4839-8617-2d2a4EXAMPLE"
   }
   ```

# 檢閱及核准或拒絕變更請求
<a name="change-requests-review"></a>

**Change Manager 可用性變更**  
AWS Systems Manager Change Manager 自 2025 年 11 月 7 日起，不再向新客戶開放。如果您想要使用 Change Manager，請在該日期之前註冊。現有客戶可以繼續正常使用該服務。如需詳細資訊，請參閱[AWS Systems Manager Change Manager可用性變更](https://docs.aws.amazon.com/systems-manager/latest/userguide/change-manager-availability-change.html)。

如果您在 Change Manager ( AWS Systems Manager中的工具) 中被指定為變更請求的檢閱者，則當新的變更請求有待您檢閱時，您會透過 Amazon Simple Notification Service (Amazon SNS) 主題收到通知。

**注意**  
此功能取決於變更範本中是否指定了 Amazon SNS 來傳送檢閱通知。如需相關資訊，請參閱[為 Change Manager 通知設定 Amazon SNS 主題](change-manager-sns-setup.md)。

若要檢閱變更請求，您可以遵循通知中的連結，或 AWS 管理主控台 直接登入 並遵循此程序中的步驟。

**注意**  
如果將 Amazon SNS 主題指派給變更範本中的檢閱者，則當變更請求狀態變更時，會將通知傳送給該主題的訂閱者。  
如需有關變更請求核准的詳細資訊，請參閱[關於變更請求核准](change-requests-create.md#cm-approvals-requests)。

## 檢閱及核准或拒絕變更請求 (主控台)
<a name="change-requests-review-console"></a>

以下程序說明如何使用 Systems Manager 主控台來檢閱及核准或拒絕變更請求。

**若要檢閱及核准或拒絕單一變更請求**

1. 開啟您收到的電子郵件通知中的連結，並登入 AWS 管理主控台，這會引導您前往變更請求以供檢閱。

1. 在摘要頁面中，檢閱變更請求的提議內容。

   若要核准變更請求，請選擇 **Approve** (核准)。在對話方塊中，提供您要為此核准新增的任何註解，然後選擇 **Approve** (核准)。此請求所代表的 Runbook 工作流程會在排程時開始執行，或只要變更未被任何限制封鎖即可。

   -或-

   若要拒絕變更請求，請選擇 **Reject** (拒絕)。在對話方塊中，提供您要為此拒絕新增的任何註解，然後選擇 **Reject** (拒絕)。

**若要檢閱及核准或拒絕大量變更請求**

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

1. 在導覽窗格中，選擇 **Change Manager**。

1. 選擇 **Approvals** (核准) 標籤。

1. (選用) 選擇各項請求的名稱即可檢閱待核准之請求的詳細資料，然後返回 **Approvals** (核准) 標籤。

1. 選取您要核准之每項變更請求的核取方塊。

   -或-

   選取您要拒絕之每項變更請求的核取方塊。

1. 在對話方塊中，提供您要為此核准或拒絕新增的任何註解。

1. 視您要核准或拒絕選取的變更請求而定，選擇 **Approve** (核准) 或 **Reject** (拒絕)。

## 檢閱及核准或拒絕變更請求 (命令列)
<a name="change-requests-review-command-line"></a>

下列程序說明如何使用 AWS Command Line Interface (AWS CLI) （在 Linux、 macOS或 上Windows Server) 來檢閱和核准或拒絕變更請求。

**若要檢閱及核准或拒絕變更請求**

1. 如果您尚未安裝並設定 AWS Command Line Interface (AWS CLI)，請安裝並設定 。

   如需相關資訊，請參閱[安裝或更新最新版本的 AWS CLI](https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html)。

1. 在本機電腦上建立 JSON 檔案，指定 AWS CLI 呼叫的參數。

   ```
   {
     "OpsItemFilters": 
     [
       {
         "Key": "OpsItemType",
         "Values": ["/aws/changerequest"],
         "Operator": "Equal"
       }
     ],
     "MaxResults": number
   }
   ```

   您可以在 JSON 檔案中指定核准者的 Amazon Resource Name (ARN)，以篩選特定核准者的結果。請見此處範例。

   ```
   {
     "OpsItemFilters": 
     [
       {
         "Key": "OpsItemType",
         "Values": ["/aws/changerequest"],
         "Operator": "Equal"
       },
       {
         "Key": "ChangeRequestByApproverArn",
         "Values": ["arn:aws:iam::account-id:user/user-name"],
         "Operator": "Equal"
       }
     ],
     "MaxResults": number
   }
   ```

1. 執行以下命令，以檢視您在 JSON 檔案中指定的變更請求數目上限。

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

   ```
   aws ssm describe-ops-items \
   --cli-input-json file://filename.json
   ```

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

   ```
   aws ssm describe-ops-items ^
   --cli-input-json file://filename.json
   ```

------

1. 執行以下命令，以核准或拒絕變更請求。

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

   ```
   aws ssm send-automation-signal \
       --automation-execution-id ID \
       --signal-type Approve_or_Reject \
       --payload Comment="message"
   ```

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

   ```
   aws ssm send-automation-signal ^
   --automation-execution-id ID ^
       --signal-type Approve_or_Reject ^
       --payload Comment="message"
   ```

------

   如果已為所選請求的變更範本指定 Amazon SNS 主題，則會在請求遭到拒絕或獲得核准時傳送通知。如果您沒有收到請求的通知，您可以返回 Change Manager，檢查請求的狀態。如需有關使用此命令時可搭配使用的其他選項的資訊，請參閱《AWS CLI 命令參考》**中 AWS Systems Manager 一節的 [https://docs.aws.amazon.com/cli/latest/reference/ssm/send-automation-signal.html](https://docs.aws.amazon.com/cli/latest/reference/ssm/send-automation-signal.html)。

# 檢閱變更請求詳細資訊、任務和時間表 (主控台)
<a name="reviewing-changes"></a>

**Change Manager 可用性變更**  
AWS Systems Manager Change Manager 自 2025 年 11 月 7 日起，不再向新客戶開放。如果您想要使用 Change Manager，請在該日期之前註冊。現有客戶可以繼續正常使用該服務。如需詳細資訊，請參閱[AWS Systems Manager Change Manager可用性變更](https://docs.aws.amazon.com/systems-manager/latest/userguide/change-manager-availability-change.html)。

您可以檢視有關變更請求的資訊，包括已在 AWS Systems Manager(Change Manager 中的工具) 儀表板中處理變更的請求。這些詳細資訊包括執行 Runbook 進行變更之 Automation 操作的連結。建立請求時會產生自動化執行 ID，但是在指定所有核准且沒有限制來封鎖變更之前，程序才會執行。

**若要檢閱變更請求詳細資訊、任務和時間表**

1. 在導覽窗格中，選擇 **Change Manager**。

1. 選擇 **Requests** (請求) 標籤。

1. 在 **Change requests** (變更請求) 區段中，搜尋您要檢閱的變更請求。

   您可以使用 **Create date range** (建立日期範圍) 選項，將結果限制在特定期間內。

   您可以依下列屬性篩選請求：
   + `Status`
   + `Request ID`
   + `Approver`
   + `Requester`

   例如，若要檢視過去 24 小時內成功完成之所有變更請求的詳細資訊，請執行下列動作：

   1. 對於 **Create date range** (建立日期範圍)，選擇 **1d**。

   1. 在搜尋方塊中，選取 **Status, CompletedWithSuccess** (狀態 CompletedWithSuccess)。

   1. 在結果中，選擇成功完成的變更請求的名稱，以檢閱其結果。

1. 在下列標籤上檢視變更請求的相關資訊：
   + **Request details** (請求詳細資訊) – 檢視有關變更請求的基本詳細資訊，包括申請者、變更範本，以及為變更選取的 Automation Runbook。您也可以遵循 Automation 操作詳細資訊的連結，檢視有關請求中指定的任何 Runbook 參數、指派給變更請求的 Amazon CloudWatch 警示，以及針對該請求提供的核准和註解的資訊。
   + **Task** (任務) – 檢視變更中有關任務的資訊，包括已完成變更請求的任務狀態、目標資源、關聯的自動化 Runbook 中的步驟，以及並行和錯誤閾值詳細資訊。
   + **Timeline** (時間表) – 檢視與變更請求關聯之所有事件的摘要，按照日期和時間列出。摘要會指出建立變更請求的時間、指派核准者的動作、排定執行核准變更請求的時間備註、Runbook 工作流程詳細資訊，以及整體變更流程和 Runbook 中每個步驟的狀態變更。
   + **Associated events** (關聯事件) – 檢視有關 [AWS CloudTrail Lake](https://docs.aws.amazon.com/awscloudtrail/latest/userguide/cloudtrail-lake.html) 中記錄之變更請求的可稽核詳細資訊。詳細資訊包括執行的 API 動作、針對這些動作所包含的請求參數、執行動作的使用者帳戶、在處理期間更新的資源等等。

     當您啟用 CloudTrail Lake 事件追蹤時，CloudTrail Lake 會針對變更請求相關事件建立事件資料存放區。事件詳細資訊可用於執行變更請求的帳戶或組織。您可以透過帳戶或組織中的任何變更請求來開啟 CloudTrail Lake 事件追蹤。如需有關啟用 CloudTrail Lake 整合以及建立事件資料存放區的資訊，請參閱 [監控您的變更請求事件](monitoring-change-request-events.md)。
**注意**  
使用 **CloudTrail Lake** 需要支付費用。如需詳細資訊，請參閱 [AWS CloudTrail 定價](https://aws.amazon.com/cloudtrail/pricing/)。

# 檢視變更請求的彙總計數 (命令列)
<a name="change-requests-review-aggregate-command-line"></a>

**Change Manager 可用性變更**  
AWS Systems Manager Change Manager 自 2025 年 11 月 7 日起，不再向新客戶開放。如果您想要使用 Change Manager，請在該日期之前註冊。現有客戶可以繼續正常使用該服務。如需詳細資訊，請參閱[AWS Systems Manager Change Manager可用性變更](https://docs.aws.amazon.com/systems-manager/latest/userguide/change-manager-availability-change.html)。

您可以使用 [GetOpsSummary](https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_GetOpsSummary.html) API 操作，在 Change Manager ( AWS Systems Manager中的工具) 中檢視變更請求的彙總計數。此 API 操作可以傳回單一 AWS 帳戶 或 AWS 區域 多個帳戶和多個區域中的單一 計數。

**注意**  
如果您想要檢視多個 AWS 帳戶 和多個 的變更請求彙總計數 AWS 區域，您必須設定資源資料同步。如需詳細資訊，請參閱[建立庫存的資源資料同步](inventory-create-resource-data-sync.md)。

下列程序說明如何使用 AWS Command Line Interface (AWS CLI) （在 Linux、 macOS或 上Windows Server) 來檢視變更請求的彙總計數。

**若有檢視變更請求的彙總計數**

1. 如果您尚未安裝並設定 AWS Command Line Interface (AWS CLI)，請安裝並設定 。

   如需相關資訊，請參閱[安裝或更新最新版本的 AWS CLI](https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html)。

1. 請執行下列其中一個命令：

   **單一帳戶和區域**

   此命令會傳回已設定 AWS CLI 工作階段之 AWS 帳戶 和 AWS 區域 的所有變更請求計數。

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

   ```
   aws ssm get-ops-summary \
   --filters Key=AWS:OpsItem.OpsItemType,Values="/aws/changerequests",Type=Equal \
   --aggregators AggregatorType=count,AttributeName=Status,TypeName=AWS:OpsItem
   ```

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

   ```
   aws ssm get-ops-summary ^
   --filters Key=AWS:OpsItem.OpsItemType,Values="/aws/changerequests",Type=Equal ^
   --aggregators AggregatorType=count,AttributeName=Status,TypeName=AWS:OpsItem
   ```

------

   呼叫會傳回相關資訊，如下所示。

   ```
   {
       "Entities": [
           {
               "Data": {
                   "AWS:OpsItem": {
                       "Content": [
                           {
                               "Count": "38",
                               "Status": "Open"
                           }
                       ]
                   }
               }
           }
       ]
   }
   ```

   **多個帳戶及/或區域**

   此命令會傳回 資源資料同步中 AWS 區域 指定的 AWS 帳戶 和 的所有變更請求計數。

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

   ```
   aws ssm get-ops-summary \
       --sync-name resource_data_sync_name \
       --filters Key=AWS:OpsItem.OpsItemType,Values="/aws/changerequests",Type=Equal \
       --aggregators AggregatorType=count,AttributeName=Status,TypeName=AWS:OpsItem
   ```

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

   ```
   aws ssm get-ops-summary ^
       --sync-name resource_data_sync_name ^
       --filters Key=AWS:OpsItem.OpsItemType,Values="/aws/changerequests",Type=Equal ^
       --aggregators AggregatorType=count,AttributeName=Status,TypeName=AWS:OpsItem
   ```

------

   呼叫會傳回相關資訊，如下所示。

   ```
   {
       "Entities": [
           {
               "Data": {
                   "AWS:OpsItem": {
                       "Content": [
                           {
                               "Count": "43",
                               "Status": "Open"
                           },
                           {
                               "Count": "2",
                               "Status": "Resolved"
                           }
                       ]
                   }
               }
           }
       ]
   }
   ```

   **多個帳戶及特定區域**

   此命令會傳回針對資源資料同步中指定的 AWS 帳戶 的所有變更請求的計數。但是，它只會傳回來自命令中指定的區域的資料

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

   ```
   aws ssm get-ops-summary \
       --sync-name resource_data_sync_name \
       --filters Key=AWS:OpsItem.SourceRegion,Values='Region',Type=Equal Key=AWS:OpsItem.OpsItemType,Values="/aws/changerequests",Type=Equal \
       --aggregators AggregatorType=count,AttributeName=Status,TypeName=AWS:OpsItem
   ```

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

   ```
   aws ssm get-ops-summary ^
       --sync-name resource_data_sync_name ^
       --filters Key=AWS:OpsItem.SourceRegion,Values='Region',Type=Equal Key=AWS:OpsItem.OpsItemType,Values="/aws/changerequests",Type=Equal ^
       --aggregators AggregatorType=count,AttributeName=Status,TypeName=AWS:OpsItem
   ```

------

   **多個帳戶和區域 (具有按區域分組的輸出)**

   此命令會傳回 資源資料同步中 AWS 區域 指定的 AWS 帳戶 和 的所有變更請求計數。輸出會顯示每個區域的計數資訊。

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

   ```
   aws ssm get-ops-summary \
       --sync-name resource_data_sync_name \
       --filters Key=AWS:OpsItem.OpsItemType,Values="/aws/changerequests",Type=Equal \
       --aggregators '[{"AggregatorType":"count","TypeName":"AWS:OpsItem","AttributeName":"Status","Aggregators":[{"AggregatorType":"count","TypeName":"AWS:OpsItem","AttributeName":"SourceRegion"}]}]'
   ```

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

   ```
   aws ssm get-ops-summary ^
       --sync-name resource_data_sync_name ^
       --filters Key=AWS:OpsItem.OpsItemType,Values="/aws/changerequests",Type=Equal ^
       --aggregators '[{"AggregatorType":"count","TypeName":"AWS:OpsItem","AttributeName":"Status","Aggregators":[{"AggregatorType":"count","TypeName":"AWS:OpsItem","AttributeName":"SourceRegion"}]}]'
   ```

------

   呼叫會傳回相關資訊，如下所示。

   ```
   {
           "Entities": [
               {
                   "Data": {
                       "AWS:OpsItem": {
                           "Content": [
                               {
                                   "Count": "38",
                                   "SourceRegion": "us-east-1",
                                   "Status": "Open"
                               },
                               {
                                   "Count": "4",
                                   "SourceRegion": "us-east-2",
                                   "Status": "Open"
                               },
                               {
                                   "Count": "1",
                                   "SourceRegion": "us-west-1",
                                   "Status": "Open"
                               },
                               {
                                   "Count": "2",
                                   "SourceRegion": "us-east-2",
                                   "Status": "Resolved"
                               }
                           ]
                       }
                   }
               }
           ]
       }
   ```

   **多個帳戶和區域 (具有按區域分組的輸出)**

   此命令會傳回 資源資料同步中 AWS 區域 指定的 AWS 帳戶 和 的所有變更請求計數。輸出按帳戶和區域分組計數資訊。

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

   ```
   aws ssm get-ops-summary \
       --sync-name resource_data_sync_name \
       --filters Key=AWS:OpsItem.OpsItemType,Values="/aws/changerequests",Type=Equal \
       --aggregators '[{"AggregatorType":"count","TypeName":"AWS:OpsItem","AttributeName":"Status","Aggregators":[{"AggregatorType":"count","TypeName":"AWS:OpsItem","AttributeName":"SourceAccountId","Aggregators":[{"AggregatorType":"count","TypeName":"AWS:OpsItem","AttributeName":"SourceRegion"}]}]}]'
   ```

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

   ```
   aws ssm get-ops-summary ^
       --sync-name resource_data_sync_name ^
       --filters Key=AWS:OpsItem.OpsItemType,Values="/aws/changerequests",Type=Equal ^
       --aggregators '[{"AggregatorType":"count","TypeName":"AWS:OpsItem","AttributeName":"Status","Aggregators":[{"AggregatorType":"count","TypeName":"AWS:OpsItem","AttributeName":"SourceAccountId","Aggregators":[{"AggregatorType":"count","TypeName":"AWS:OpsItem","AttributeName":"SourceRegion"}]}]}]'
   ```

------

   呼叫會傳回相關資訊，如下所示。

   ```
   {
       "Entities": [
           {
               "Data": {
                   "AWS:OpsItem": {
                       "Content": [
                           {
                               "Count": "38",
                               "SourceAccountId": "123456789012",
                               "SourceRegion": "us-east-1",
                               "Status": "Open"
                           },
                           {
                               "Count": "4",
                               "SourceAccountId": "111122223333",
                               "SourceRegion": "us-east-2",
                               "Status": "Open"
                           },
                           {
                               "Count": "1",
                               "SourceAccountId": "111122223333",
                               "SourceRegion": "us-west-1",
                               "Status": "Open"
                           },
                           {
                               "Count": "2",
                               "SourceAccountId": "444455556666",
                               "SourceRegion": "us-east-2",
                               "Status": "Resolved"
                           },
                           {
                               "Count": "1",
                               "SourceAccountId": "222222222222",
                               "SourceRegion": "us-east-1",
                               "Status": "Open"
                           }
                       ]
                   }
               }
           }
       ]
   }
   ```

# 稽核和記錄 Change Manager 活動
<a name="change-manager-auditing"></a>

**Change Manager 可用性變更**  
AWS Systems Manager Change Manager 自 2025 年 11 月 7 日起，不再向新客戶開放。如果您想要使用 Change Manager，請在該日期之前註冊。現有客戶可以繼續正常使用該服務。如需詳細資訊，請參閱[AWS Systems Manager Change Manager可用性變更](https://docs.aws.amazon.com/systems-manager/latest/userguide/change-manager-availability-change.html)。

您可以使用 Amazon CloudWatch 和 AWS CloudTrail 警示稽核 Change Manager ( AWS Systems Manager中的工具) 中的活動。

如需稽核和記錄 Systems Manager 選項的詳細資訊，請參閱 [在 中記錄和監控 AWS Systems Manager](monitoring.md)。

## 使用 CloudWatch 警示稽核 Change Manager 活動。
<a name="change-manager-logging-auditing-alarms"></a>

您可以設定 CloudWatch 警示並將其指派給變更範本。如果符合警示中定義的任何條件，則會採取針對警示指定的動作。在警示組態中，您可以指定 Amazon Simple Notification Service (Amazon SNS) 主題，以便在符合警示條件時進行通知。

如需有關建立 Change Manager 範本的資訊，請參閱 [使用變更範本](change-templates.md)。

如需有關建立 CloudWatch 警示的資訊，請參閱《*Amazon CloudWatch 使用者指南*》中的[使用 CloudWatch 警示](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/AlarmThatSendsEmail.html)。

## 使用 CloudTrail 稽核 Change Manager 活動
<a name="change-manager-logging-auditing-cloudtrail"></a>

CloudTrail 會擷取 Systems Manager 主控台、 AWS Command Line Interface (AWS CLI) 和 Systems Manager SDK 中發出的 API 呼叫。您可以在 CloudTrail 主控台中，或在存放資訊的 Amazon Simple Storage Service (Amazon S3) 儲存貯體中檢視資訊。一個儲存貯體可用於您帳戶中所有 CloudTrail 日誌。

Change Manager 動作的日誌會顯示變更範本文件建立、變更範本和變更請求核准和拒絕、自動化 Runbook 產生的活動等等。如需檢視和使用 Systems Manager 活動的 CloudTrail 日誌的詳細資訊，請參閱 [使用 記錄 AWS Systems Manager API 呼叫 AWS CloudTrail](monitoring-cloudtrail-logs.md)。

# Change Manager 疑難排解
<a name="change-manager-troubleshooting"></a>

**Change Manager 可用性變更**  
AWS Systems Manager Change Manager 自 2025 年 11 月 7 日起，不再向新客戶開放。如果您想要使用 Change Manager，請在該日期之前註冊。現有客戶可以繼續正常使用該服務。如需詳細資訊，請參閱[AWS Systems Manager Change Manager可用性變更](https://docs.aws.amazon.com/systems-manager/latest/userguide/change-manager-availability-change.html)。

使用下列資訊以協助您對 Change Manager ( AWS Systems Manager中的工具) 的問題進行疑難排解。

**Topics**
+ [使用 Active Directory (群組) 時變更請求核准期間出現 “Group *\$1GUID\$1* not found” (找不到群組 \$1GUID\$1) 錯誤。](#change-manager-troubleshooting-sso)

## 使用 Active Directory (群組) 時變更請求核准期間出現 “Group *\$1GUID\$1* not found” (找不到群組 \$1GUID\$1) 錯誤。
<a name="change-manager-troubleshooting-sso"></a>

**問題**：當 AWS IAM Identity Center (IAM Identity Center) 用於使用者身分管理時，在 中授予核准許可的 Active Directory 群組成員Change Manager會收到「未授權」或「找不到群組」錯誤。
+ **解決方案**：當您在 IAM Identity Center 中選取 Active Directory 群組以存取 時 AWS 管理主控台，系統會排程定期同步，將來自這些 Active Directory 群組的資訊複製到 IAM Identity Center。在透過 Active Directory 群組成員資格授權的使用者可以成功核准請求之前，必須先完成此程序。如需詳細資訊，請參閱《*AWS IAM Identity Center 使用者指南*》中的[連接到您的 Microsoft AD 目錄](https://docs.aws.amazon.com/singlesignon/latest/userguide/manage-your-identity-source-ad.html)。

# AWS Systems Manager Documents
<a name="documents"></a>

 AWS Systems Manager 文件 (SSM 文件） 定義 Systems Manager 在受管執行個體上執行的動作。Systems Manager 包含 100 多個預先設定的文件，可讓您用來在執行時間時指定參數。透過選擇 **Owned by Amazon** (Amazon 擁有) 索引標籤，或者在呼叫 `ListDocuments` API 操作時為 `Owner` 篩選條件指定 Amazon，您可以在 Systems Manager 文件主控台中找到預先設定的文件。文件使用 JavaScript 物件標記法 (JSON) 或 YAML，其中包括您指定的步驟和參數。

為了增強安全性，截至 2025 年 7 月 14 日，SSM 文件在處理參數時支援環境變數插補。此功能 (在結構描述為 2.2 版，SSM Agent 為 3.3.2746.0 版或更新版本時可用) 有助於防止命令注入攻擊。

若要開始使用 SSM 文件，請開啟 [Systems Manager 主控台](https://console.aws.amazon.com/systems-manager/documents)。在導覽窗格中，選擇 **Documents (文件)**。

**重要**  
在 Systems Manager 中，*Amazon 擁有的* SSM 文件是由 Amazon Web Services 本身建立和管理的文件。*Amazon 擁有的*文件的文件名中包含如 `AWS-*` 的字首。文件的擁有者被視為 Amazon，而不是其中的特定使用者帳戶 AWS。這些文件公開供所有人使用。

## 文件工具對我的組織有哪些益處？
<a name="ssm-docs-benefits"></a>

文件是 中的工具 AWS Systems Manager，可提供以下優點：
+ **文件類別**

  為了幫助您找到所需文件，請根據要搜尋的文件類型選擇類別。若要擴大搜尋範圍，您可以選擇同一文件類型的多個類別。不支援選擇不同文件類型的類別。僅支援 Amazon 擁有的文件類別。
+  **文件版本** 

  您可以建立和儲存不同版本的文件。然後，您可以為每個文件指定一個預設版本。預設版本的文件更新到較新版本或可恢復到舊版的文件。當您變更文件的內容時，Systems Manager 會自動增加文件版本。您可以在 主控台、 AWS Command Line Interface (AWS CLI) 命令或 API 呼叫中指定文件版本，以擷取或使用文件的任何版本。
+  **根據需求自訂文件** 

  如果您要在文件中自訂步驟和動作，您可以建立自己的步驟和動作。系統會將 文件與 存放在 AWS 區域 您建立文件的 AWS 帳戶 中。如需有關如何建立 SSM 文件的詳細資訊，請參閱 [建立 SSM 文件內容](documents-creating-content.md)。
+  **標記文件** 

  您可以在文件加上標籤，根據您指派給文件的標籤可以協助您快速找出一或多個文件。例如，您可以為用定的環境、部門、使用者、群組或時段來標記文件。您也可以透過建立指定使用者或群組可存取之標籤的 AWS Identity and Access Management (IAM) 政策來限制文件的存取。
+  **共用文件** 

  您可以將文件設定為公開或者與相同 AWS 區域中特定的 AWS 帳戶 分享。例如，若想讓您提供給客戶或員工的所有 Amazon Elastic Compute Cloud (Amazon EC2) 執行個體都有相同的組態，在帳戶之間共用文件就非常實用。除了將執行個體上的應用程式或修補程式保持在最新狀態，您可能想要限制客戶執行個體避免進行特定的活動。或者，您可能想要確保在組織中員工帳戶所使用的執行個體獲得特定內部資源的存取權。如需詳細資訊，請參閱[共用 SSM 文件](documents-ssm-sharing.md)。

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

## SSM 文件有哪些類型？
<a name="what-are-document-types"></a>

下表說明不同類型的 SSM 文件和其使用案例。


****  

| Type | 搭配使用 | 詳細資訊 | 
| --- | --- | --- | 
|  ApplicationConfiguration ApplicationConfigurationSchema  |   [AWS AppConfig](https://docs.aws.amazon.com/appconfig/latest/userguide/what-is-appconfig.html)   |  AWS AppConfig是 中的工具 AWS Systems Manager，可讓您建立、管理和快速部署應用程式組態。您可以藉由建立使用 `ApplicationConfiguration` 文件類型的文件，在 SSM 文件中存放組態資料。如需詳細資訊，請參閱*《AWS AppConfig 使用者指南》*中的 [Freeform 組態](https://docs.aws.amazon.com/appconfig/latest/userguide/appconfig-creating-configuration-and-profile.html#free-form-configurations)。 如果您在 SSM 文件中建立組態，則必須指定相應的 JSON 結構描述。該結構描述使用 `ApplicationConfigurationSchema` 文件類型，且與一組規則一樣，會定義每個應用程式組態設定允許的屬性。如需詳細資訊，請參閱*《AWS AppConfig 使用者指南》*中的[關於驗證器](https://docs.aws.amazon.com/appconfig/latest/userguide/appconfig-creating-configuration-and-profile-validators.html)。  | 
|  Automation Runbook  |   [自動化](systems-manager-automation.md)   [State Manager](systems-manager-state.md)   [Maintenance Windows](maintenance-windows.md)   |  在執行常見的維護和部署任務 (例如建立或更新 Amazon Machine Image (AMI)) 時使用 Automation Runbook。State Manager 會使用 Automation Runbook 來套用組態。您可以在執行個體生命週期期間的任何時間點對一個或多個目標執行這些動作。Maintenance Windows 會使用 Automation Runbook，根據指定的排程執行常見的維護和部署任務。 基於 Linux 的作業系統支援的所有 Automation Runbook 在 macOS 的 EC2 執行個體上也受支援。  | 
|  變更行事曆文件  |   [Change Calendar](systems-manager-change-calendar.md)   |  Change Calendar中的工具 AWS Systems Manager使用 `ChangeCalendar` 文件類型。Change Calendar 文件會存放行事曆項目和相關聯事件，這些事件可允許或防止自動化動作變更您的環境。在 Change Calendar 中，文件會以純文字格式存放 [iCalendar 2.0](https://icalendar.org/) 資料。 macOS 的 EC2 執行個體不支援 Change Calendar。  | 
|  AWS CloudFormation 範本  |   [AWS CloudFormation](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/Welcome.html)   |  AWS CloudFormation 範本說明您要在 CloudFormation 堆疊中佈建的資源。透過將 CloudFormation 範本存放為 Systems Manager 文件，可讓您從 Systems Manager 文件功能中受益。其中包括建立和比較範本的多個版本，以及與相同 AWS 區域中的其他帳戶共用範本。 使用 Application Manager (Systems Manager 中的工具)，您可以建立和編輯 CloudFormation 範本和堆疊。如需詳細資訊，請參閱[在 中使用 CloudFormation 範本和堆疊 Application Manager](application-manager-working-stacks.md)。  | 
|  指令文件  |   [Run Command](run-command.md)   [State Manager](systems-manager-state.md)   [Maintenance Windows](maintenance-windows.md)   |  Run Command中的工具 AWS Systems Manager會使用命令文件來執行命令。 State Manager中的工具 AWS Systems Manager會使用命令文件來套用組態。這些動作可以在執行個體生命週期的任何時間點於一或多個目標上執行。 Maintenance Windows是 中的工具 AWS Systems Manager，使用 命令文件來根據指定的排程套用組態。 Systems Manager 支援的所有 Linux 和 Windows Server 作業系統支援大部分命令文件。macOS 的 EC2 執行個體支援下列 Command 文件： [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/systems-manager/latest/userguide/documents.html)  | 
|  AWS Config 一致性套件範本  |   [AWS Config](https://docs.aws.amazon.com/config/latest/developerguide/WhatIsConfig.html)   |  AWS Config 一致性套件範本是 YAML 格式的文件，用於建立一致性套件，其中包含受管或自訂規則和修補動作的 AWS Config 清單。 如需詳細資訊，請參閱[一致性套件](https://docs.aws.amazon.com/config/latest/developerguide/conformance-packs.html)。  | 
|  套件文件  |   [Distributor](distributor.md)   |  在 Distributor ( AWS Systems Manager中的工具) 中，套件由 SSM 文件來表示。套件文件包含 ZIP 封存檔案，封存檔包含要安裝在受管執行個體上的軟體或資產。在 Distributor 中建立套件會建立套件文件。 Oracle Linux 和 macOS 受管執行個體不支援 Distributor。  | 
|  政策文件  |   [State Manager](systems-manager-state.md)   |  中的庫存工具 AWS Systems Manager會使用`AWS-GatherSoftwareInventory`政策文件與State Manager關聯，從受管執行個體收集庫存資料。建立您自己的 SSM 文件時，Automation Runbook 和命令文件是在受管執行個體上強制執行政策的慣用方法。 Systems Manager 支援的所有作業系統都支援 Systems Manager Inventory 和 `AWS-GatherSoftwareInventory` 政策文件。  | 
|  事件後分析範本  |   [Incident Manager 事件後分析](https://docs.aws.amazon.com/incident-manager/latest/userguide/analysis.html)   |  Incident Manager 會使用事件後分析範本，根據 AWS 操作管理最佳實務建立分析。 使用範本建立的分析可供團隊用來找出事件回應的改進。  | 
|  工作階段文件  |   [Session Manager](session-manager.md)   |  Session Manager中的工具 AWS Systems Manager會使用工作階段文件來決定要啟動的工作階段類型，例如連接埠轉送工作階段、執行互動式命令的工作階段，或建立 SSH 通道的工作階段。 Systems Manager 支援的所有 Linux 和 Windows Server 作業系統支援工作階段文件。macOS 的 EC2 執行個體支援下列命令文件： [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/systems-manager/latest/userguide/documents.html)  | 

**SSM 文件配額**  
如需有關 SSM 文件配額的資訊，請參閱《Amazon Web Services 一般參考》**中的 [Systems Manager 服務配額](https://docs.aws.amazon.com/general/latest/gr/ssm.html#limits_ssm)一節。

**Topics**
+ [文件工具對我的組織有哪些益處？](#ssm-docs-benefits)
+ [誰應該使用 Documents？](#documents-who)
+ [SSM 文件有哪些類型？](#what-are-document-types)
+ [文件組成部分](documents-components.md)
+ [建立 SSM 文件內容](documents-creating-content.md)
+ [使用文件](documents-using.md)
+ [對參數處理問題進行疑難排解](parameter-troubleshooting.md)

# 文件組成部分
<a name="documents-components"></a>

本節包含有關 SSM 文件組成部分件的資訊。

**Topics**
+ [結構描述、功能以及範例](documents-schemas-features.md)
+ [資料元素和參數](documents-syntax-data-elements-parameters.md)
+ [命令文件外掛程式參考](documents-command-ssm-plugin-reference.md)

# 結構描述、功能以及範例
<a name="documents-schemas-features"></a>

AWS Systems Manager (SSM) 文件使用以下結構描述版本。
+ `Command` 類型的文件可以使用結構描述 1.2、2.0 和 2.2 版本。如果您使用的文件為結構描述 1.2 版本，我們建議您使用結構描述 2.2 版本建立文件。
+ `Policy` 類型的文件必須使用結構描述 2.0 版本或更新版本。
+ `Automation` 類型的文件必須使用結構描述 0.3 版本。
+ `Session` 類型的文件必須使用結構描述 1.0 版本。
+ 您可以以 JSON 或 YAML 建立文件。

如需有關`Session`文件結構描述的詳細資訊，請參閱[工作階段文件結構描述](session-manager-schema.md)。

`Command` 和 `Policy` 文件使用最新的結構描述版本，您可以善用以下功能。


**結構描述版本 2.2 文件的功能**  

| 功能 | 詳細資訊 | 
| --- | --- | 
|  文件編輯  |  文件現在可以進行更新。在版本 1.2 中，您需要將文件中任何更新儲存為不同名稱的文件。  | 
|  自動版本控制  |  文件中任何更新建立新的版本。這並非結構描述的版本，而是文件的版本。  | 
|  預設版本  |  如果您有多個版本的文件，您可以指定哪個版本為預設的文件。  | 
|  定序  |  文件中中的外掛程式或*步驟*將按照您所指定的順序執行。  | 
|  跨平台支援  |  跨平台支援允許您在相同的 SSM 文件中為不同的外掛程式指定不同的作業系統。跨平台支援使用 `precondition` 參數，只需要幾個步驟。  | 
| 參數插補 | 插補表示將變數值插入或替換為字串。將其視為在使用字串前，使用實際值填入空格。在 SSM 文件環境中，參數插補允許字串參數在命令執行之前，插入到環境變數中，提供更高安全性以防止命令注入。設定為 `ENV_VAR` 時，Agent 會建立名為 `SSM_parameter-name` 的環境變數，其中包含參數的值。 | 

**注意**  
您必須將執行個體上的 AWS Systems Manager SSM Agent 更新為最新版本，才能使用新的 Systems Manager 功能和 SSM 文件功能。如需詳細資訊，請參閱[使用 Run Command 更新 SSM Agent](run-command-tutorial-update-software.md#rc-console-agentexample)。

下表列出了主要的結構描述各版本的差異。


****  

| 第 1.2 版 | 版本 2.2 (最新版本) | 詳細資訊 | 
| --- | --- | --- | 
|  runtimeConfig  |  mainSteps  |  在版本 2.2 中，`mainSteps` 區塊取代了 `runtimeConfig`。`mainSteps` 區段可讓 Systems Manager 按順序執行步驟。  | 
|  屬性  |  inputs  |  在版本 2.2 中，`inputs` 區塊取代了 `properties` 區塊。`inputs` 區塊接受了參數的做法步驟。  | 
|  commands  |  runCommand  |  在版本 2.2 中，`inputs` 區塊接受 `runCommand` 的參數，而非 `commands` 的參數。  | 
|  id  |  動作  |  在版本 2.2 中，`Action` 取代了 `ID`。這是名稱變更。  | 
|  不適用  |  name  |  在版本 2.2 中，`name` 是一個任何使用者替步驟定義的名稱。  | 

**使用 precondition 參數**  
使用結構描述 2.2 版或更新版本，您可以使用 `precondition` 參數為每個外掛程式指定目標作業系統，或驗證您在 SSM 文件中定義的輸入參數。`precondition` 參數支援引用 SSM 文件的輸入參數，以及使用值 `Linux`、`MacOS` 以及 `Windows` 的 `platformType`。只支援 `StringEquals` 運算子。

對於文件使用結構描述版本 2.2 或更新版本，如果未指定 `precondition`，每個外掛程式是根據外掛程式的相容性來決定在作業系統執行或略過。與作業系統的外掛程式相容性會在 `precondition` 之前評估。對於文件使用結構描述 2.0 或更舊版本，不相容的外掛程式會產生錯誤。

例如，在結構描述版本 2.2 文件中，如果未指定 `precondition` 但有列出`aws:runShellScript` 外掛程式，則在 Linux 執行個體上會執行該步驟，但在 Windows Server 執行個體上會略過該步驟，因為 `aws:runShellScript` 與 Windows Server 執行個體不相容。但就結構描述版本 2.0 文件來說，如果您指定 `aws:runShellScript` 外掛程式，然後在 Windows Server 執行個體上執行該文件，則執行會失敗。您可以在本節稍後的 SSM 文件中查看先決條件參數範例。

## 結構描述版本 2.2
<a name="documents-schema-twox"></a>

**頂層元素**  
以下範例顯示使用結構描述版本 2.2 的 SSM 文件上層元素。

------
#### [ YAML ]

```
---
schemaVersion: "2.2"
description: A description of the document.
parameters:
  parameter 1:
    property 1: "value"
    property 2: "value"
  parameter 2:
    property 1: "value"
    property 2: "value"
mainSteps:
  - action: Plugin name
    name: A name for the step.
    inputs:
      input 1: "value"
      input 2: "value"
      input 3: "{{ parameter 1 }}"
```

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

```
{
   "schemaVersion": "2.2",
   "description": "A description of the document.",
   "parameters": {
       "parameter 1": {
           "property 1": "value",
           "property 2": "value"
        },
        "parameter 2":{
           "property 1": "value",
           "property 2": "value"
        } 
    },
   "mainSteps": [
      {
         "action": "Plugin name",
         "name": "A name for the step.",
         "inputs": {
            "input 1": "value",
            "input 2": "value",
            "input 3": "{{ parameter 1 }}"
         }
      }
   ]
}
```

------

**結構描述版本 2.2 範例**  
下列範例會使用 `aws:runPowerShellScript` 外掛程式在目標執行個體上執行 PowerShell 命令。

------
#### [ YAML ]

```
---
schemaVersion: "2.2"
description: "Example document"
parameters:
  Message:
    type: "String"
    description: "Example parameter"
    default: "Hello World"
    allowedValues: 
    - "Hello World"
mainSteps:
  - action: "aws:runPowerShellScript"
    name: "example"
    inputs:
      timeoutSeconds: '60'
      runCommand:
      - "Write-Output {{Message}}"
```

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

```
{
   "schemaVersion": "2.2",
   "description": "Example document",
   "parameters": {
      "Message": {
         "type": "String",
         "description": "Example parameter",
         "default": "Hello World",
         "allowedValues": ["Hello World"]
      }
   },
   "mainSteps": [
      {
         "action": "aws:runPowerShellScript",
         "name": "example",
         "inputs": {
            "timeoutSeconds": "60",
            "runCommand": [
               "Write-Output {{Message}}"
            ]
         }
      }
   ]
}
```

------

**結構描述版本 2.2 precondition 參數範例**  
結構描述版本 2.2 提供跨平台支援。這表示您可以在同一個 SSM 文件中為不同的外掛程式指定不同的作業系統。跨平台支援在步驟中使用 `precondition` 參數，如下所示。您也可以使用 `precondition` 參數來驗證您在 SSM 文件中定義的輸入參數。您可以在以下第二個範例中看到它。

------
#### [ YAML ]

```
---
schemaVersion: '2.2'
description: cross-platform sample
mainSteps:
- action: aws:runPowerShellScript
  name: PatchWindows
  precondition:
    StringEquals:
    - platformType
    - Windows
  inputs:
    runCommand:
    - cmds
- action: aws:runShellScript
  name: PatchLinux
  precondition:
    StringEquals:
    - platformType
    - Linux
  inputs:
    runCommand:
    - cmds
```

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

```
{
   "schemaVersion": "2.2",
   "description": "cross-platform sample",
   "mainSteps": [
      {
         "action": "aws:runPowerShellScript",
         "name": "PatchWindows",
         "precondition": {
            "StringEquals": [
               "platformType",
               "Windows"
            ]
         },
         "inputs": {
            "runCommand": [
               "cmds"
            ]
         }
      },
      {
         "action": "aws:runShellScript",
         "name": "PatchLinux",
         "precondition": {
            "StringEquals": [
               "platformType",
               "Linux"
            ]
         },
         "inputs": {
            "runCommand": [
               "cmds"
            ]
         }
      }
   ]
}
```

------

------
#### [ YAML ]

```
---
schemaVersion: '2.2'
parameters:
  action:
    type: String
    allowedValues:
    - Install
    - Uninstall
  confirmed:
    type: String
    allowedValues:
    - True
    - False
mainSteps:
- action: aws:runShellScript
  name: InstallAwsCLI
  precondition:
    StringEquals:
    - "{{ action }}"
    - "Install"
  inputs:
    runCommand:
    - sudo apt install aws-cli
- action: aws:runShellScript
  name: UninstallAwsCLI
  precondition:
    StringEquals:
    - "{{ action }} {{ confirmed }}"
    - "Uninstall True"
  inputs:
    runCommand:
    - sudo apt remove aws-cli
```

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

```
{
   "schemaVersion": "2.2",
   "parameters": {
      "action": {
         "type": "String",
         "allowedValues": [
            "Install",
            "Uninstall"
         ]
      },
      "confirmed": {
         "type": "String",
         "allowedValues": [
            true,
            false
         ]
      }
   },
   "mainSteps": [
      {
         "action": "aws:runShellScript",
         "name": "InstallAwsCLI",
         "precondition": {
            "StringEquals": [
               "{{ action }}",
               "Install"
            ]
         },
         "inputs": {
            "runCommand": [
               "sudo apt install aws-cli"
            ]
         }
      },
      {
         "action": "aws:runShellScript",
         "name": "UninstallAwsCLI",
         "precondition": {
            "StringEquals": [
               "{{ action }} {{ confirmed }}",
               "Uninstall True"
            ]
         },
         "inputs": {
            "runCommand": [
               "sudo apt remove aws-cli"
            ]
         }
      }
   ]
}
```

------

**具有 3.3.2746.0 之前 SSM Agent 版本的結構描述 2.2 版插補範例**  
在 3.3.2746.0 之前的 SSM Agent 版本上，Agent 會忽略 `interpolationType` 參數，並改為執行原始字串替換。如果您明確參考 `SSM_parameter-name`，則必須明確設定此項目。在下列的 Linux 範例中，明確參考了 `SSM_Message` 環境變數。

```
{
    "schemaVersion": "2.2",
    "description": "An example document",
    "parameters": {
        "Message": {
            "type": "String",
            "description": "Message to be printed",
            "default": "Hello",
            "interpolationType" : "ENV_VAR",
	     "allowedPattern: "^[^"]*$"

        }
    },
    "mainSteps": [{
        "action": "aws:runShellScript",
        "name": "printMessage",
        "inputs": {
            "runCommand": [
              "if [ -z "${SSM_Message+x}" ]; then",
              "    export SSM_Message=\"{{Message}}\"",
              "fi",
              "",
              "echo $SSM_Message"
            ]
        }
    }
}
```

**注意**  
如果 SSM 文件不使用雙括號，則技術上不需要 `allowedPattern`：`{{ }}`

**結構描述版本 2.2 State Manager 範例**  
您可以搭配使用以下 SSM 文件與 State Manager (Systems Manager 中的工具)，以下載並安裝 ClamAV 防毒軟體。State Manager 會強制實施特定組態，這表示每次執行 State Manager 關聯時，系統會檢查是否已安裝 ClamAV 軟體。如果不是，State Manager 會重新執行此文件。

------
#### [ YAML ]

```
---
schemaVersion: '2.2'
description: State Manager Bootstrap Example
parameters: {}
mainSteps:
- action: aws:runShellScript
  name: configureServer
  inputs:
    runCommand:
    - sudo yum install -y httpd24
    - sudo yum --enablerepo=epel install -y clamav
```

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

```
{
   "schemaVersion": "2.2",
   "description": "State Manager Bootstrap Example",
   "parameters": {},
   "mainSteps": [
      {
         "action": "aws:runShellScript",
         "name": "configureServer",
         "inputs": {
            "runCommand": [
               "sudo yum install -y httpd24",
               "sudo yum --enablerepo=epel install -y clamav"
            ]
         }
      }
   ]
}
```

------

**結構描述版本 2.2 庫存範例**  
您可以搭配使用以下 SSM 文件與 State Manager，收集有關執行個體的庫存中繼資料。

------
#### [ YAML ]

```
---
schemaVersion: '2.2'
description: Software Inventory Policy Document.
parameters:
  applications:
    type: String
    default: Enabled
    description: "(Optional) Collect data for installed applications."
    allowedValues:
    - Enabled
    - Disabled
  awsComponents:
    type: String
    default: Enabled
    description: "(Optional) Collect data for AWS Components like amazon-ssm-agent."
    allowedValues:
    - Enabled
    - Disabled
  networkConfig:
    type: String
    default: Enabled
    description: "(Optional) Collect data for Network configurations."
    allowedValues:
    - Enabled
    - Disabled
  windowsUpdates:
    type: String
    default: Enabled
    description: "(Optional) Collect data for all Windows Updates."
    allowedValues:
    - Enabled
    - Disabled
  instanceDetailedInformation:
    type: String
    default: Enabled
    description: "(Optional) Collect additional information about the instance, including
      the CPU model, speed, and the number of cores, to name a few."
    allowedValues:
    - Enabled
    - Disabled
  customInventory:
    type: String
    default: Enabled
    description: "(Optional) Collect data for custom inventory."
    allowedValues:
    - Enabled
    - Disabled
mainSteps:
- action: aws:softwareInventory
  name: collectSoftwareInventoryItems
  inputs:
    applications: "{{ applications }}"
    awsComponents: "{{ awsComponents }}"
    networkConfig: "{{ networkConfig }}"
    windowsUpdates: "{{ windowsUpdates }}"
    instanceDetailedInformation: "{{ instanceDetailedInformation }}"
    customInventory: "{{ customInventory }}"
```

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

```
{
   "schemaVersion": "2.2",
   "description": "Software Inventory Policy Document.",
   "parameters": {
      "applications": {
         "type": "String",
         "default": "Enabled",
         "description": "(Optional) Collect data for installed applications.",
         "allowedValues": [
            "Enabled",
            "Disabled"
         ]
      },
      "awsComponents": {
         "type": "String",
         "default": "Enabled",
         "description": "(Optional) Collect data for AWS Components like amazon-ssm-agent.",
         "allowedValues": [
            "Enabled",
            "Disabled"
         ]
      },
      "networkConfig": {
         "type": "String",
         "default": "Enabled",
         "description": "(Optional) Collect data for Network configurations.",
         "allowedValues": [
            "Enabled",
            "Disabled"
         ]
      },
      "windowsUpdates": {
         "type": "String",
         "default": "Enabled",
         "description": "(Optional) Collect data for all Windows Updates.",
         "allowedValues": [
            "Enabled",
            "Disabled"
         ]
      },
      "instanceDetailedInformation": {
         "type": "String",
         "default": "Enabled",
         "description": "(Optional) Collect additional information about the instance, including\nthe CPU model, speed, and the number of cores, to name a few.",
         "allowedValues": [
            "Enabled",
            "Disabled"
         ]
      },
      "customInventory": {
         "type": "String",
         "default": "Enabled",
         "description": "(Optional) Collect data for custom inventory.",
         "allowedValues": [
            "Enabled",
            "Disabled"
         ]
      }
   },
   "mainSteps": [
      {
         "action": "aws:softwareInventory",
         "name": "collectSoftwareInventoryItems",
         "inputs": {
            "applications": "{{ applications }}",
            "awsComponents": "{{ awsComponents }}",
            "networkConfig": "{{ networkConfig }}",
            "windowsUpdates": "{{ windowsUpdates }}",
            "instanceDetailedInformation": "{{ instanceDetailedInformation }}",
            "customInventory": "{{ customInventory }}"
         }
      }
   ]
}
```

------

**結構描述版本 2.2 `AWS-ConfigureAWSPackage` 範例**  
以下範例顯示 `AWS-ConfigureAWSPackage` 文件。`mainSteps` 區段包含 `action` 步驟中的 `aws:configurePackage` 外掛程式。

**注意**  
在 Linux 作業系統上，只有支援 `AmazonCloudWatchAgent` 和 `AWSSupport-EC2Rescue` 的套件。

------
#### [ YAML ]

```
---
schemaVersion: '2.2'
description: 'Install or uninstall the latest version or specified version of an AWS
package. Available packages include the following: AWSPVDriver, AwsEnaNetworkDriver,
  AwsVssComponents, and AmazonCloudWatchAgent, and AWSSupport-EC2Rescue.'
parameters:
  action:
    description: "(Required) Specify whether or not to install or uninstall the package."
    type: String
    allowedValues:
    - Install
    - Uninstall
  name:
    description: "(Required) The package to install/uninstall."
    type: String
    allowedPattern: "^arn:[a-z0-9][-.a-z0-9]{0,62}:[a-z0-9][-.a-z0-9]{0,62}:([a-z0-9][-.a-z0-9]{0,62})?:([a-z0-9][-.a-z0-9]{0,62})?:package\\/[a-zA-Z][a-zA-Z0-9\\-_]{0,39}$|^[a-zA-Z][a-zA-Z0-9\\-_]{0,39}$"
  version:
    type: String
    description: "(Optional) A specific version of the package to install or uninstall."
mainSteps:
- action: aws:configurePackage
  name: configurePackage
  inputs:
    name: "{{ name }}"
    action: "{{ action }}"
    version: "{{ version }}"
```

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

```
{
   "schemaVersion": "2.2",
   "description": "Install or uninstall the latest version or specified version of an AWS package. Available packages include the following: AWSPVDriver, AwsEnaNetworkDriver, AwsVssComponents, and AmazonCloudWatchAgent, and AWSSupport-EC2Rescue.",
   "parameters": {
      "action": {
         "description":"(Required) Specify whether or not to install or uninstall the package.",
         "type":"String",
         "allowedValues":[
            "Install",
            "Uninstall"
         ]
      },
      "name": {
         "description": "(Required) The package to install/uninstall.",
         "type": "String",
         "allowedPattern": "^arn:[a-z0-9][-.a-z0-9]{0,62}:[a-z0-9][-.a-z0-9]{0,62}:([a-z0-9][-.a-z0-9]{0,62})?:([a-z0-9][-.a-z0-9]{0,62})?:package\\/[a-zA-Z][a-zA-Z0-9\\-_]{0,39}$|^[a-zA-Z][a-zA-Z0-9\\-_]{0,39}$"
      },
      "version": {
         "type": "String",
         "description": "(Optional) A specific version of the package to install or uninstall."
      }
   },
   "mainSteps":[
      {
         "action": "aws:configurePackage",
         "name": "configurePackage",
         "inputs": {
            "name": "{{ name }}",
            "action": "{{ action }}",
            "version": "{{ version }}"
         }
      }
   ]
}
```

------

## 結構描述版本 1.2
<a name="documents-schema-onex"></a>

以下範例顯示結構描述版本 1.2 文件的上層元素。

```
{
   "schemaVersion":"1.2",
   "description":"A description of the SSM document.",
   "parameters":{
      "parameter 1":{
         "one or more parameter properties"
      },
      "parameter 2":{
         "one or more parameter properties"
      },
      "parameter 3":{
         "one or more parameter properties"
      }
   },
   "runtimeConfig":{
      "plugin 1":{
         "properties":[
            {
               "one or more plugin properties"
            }
         ]
      }
   }
}
```

**結構描述版本 1.2 `aws:runShellScript` 範例**  
以下範例顯示 `AWS-RunShellScript` SSM 文件。**runtimeConfig** 區段包含 `aws:runShellScript` 外掛程式。

```
{
    "schemaVersion":"1.2",
    "description":"Run a shell script or specify the commands to run.",
    "parameters":{
        "commands":{
            "type":"StringList",
            "description":"(Required) Specify a shell script or a command to run.",
            "minItems":1,
            "displayType":"textarea"
        },
        "workingDirectory":{
            "type":"String",
            "default":"",
            "description":"(Optional) The path to the working directory on your instance.",
            "maxChars":4096
        },
        "executionTimeout":{
            "type":"String",
            "default":"3600",
            "description":"(Optional) The time in seconds for a command to complete before it is considered to have failed. Default is 3600 (1 hour). Maximum is 172800 (48 hours).",
            "allowedPattern":"([1-9][0-9]{0,3})|(1[0-9]{1,4})|(2[0-7][0-9]{1,3})|(28[0-7][0-9]{1,2})|(28800)"
        }
    },
    "runtimeConfig":{
        "aws:runShellScript":{
            "properties":[
                {
                    "id":"0.aws:runShellScript",
                    "runCommand":"{{ commands }}",
                    "workingDirectory":"{{ workingDirectory }}",
                    "timeoutSeconds":"{{ executionTimeout }}"
                }
            ]
        }
    }
}
```

## 結構描述版本 0.3
<a name="automation-doc-syntax-examples"></a>

**頂層元素**  
下列範例以 JSON 格式顯示結構描述 0.3 版 Automation Runbook 的最上層元素。

```
{
    "description": "document-description",
    "schemaVersion": "0.3",
    "assumeRole": "{{assumeRole}}",
    "parameters": {
        "parameter1": {
            "type": "String",
            "description": "parameter-1-description",
            "default": ""
        },
        "parameter2": {
            "type": "String",
            "description": "parameter-2-description",
            "default": ""
        }
    },
    "variables": {
        "variable1": {
            "type": "StringMap",
            "description": "variable-1-description",
            "default": {}
        },
        "variable2": {
            "type": "String",
            "description": "variable-2-description",
            "default": "default-value"
        }
    },
    "mainSteps": [
        {
            "name": "myStepName",
            "action": "action-name",
            "maxAttempts": 1,
            "inputs": {
                "Handler": "python-only-handler-name",
                "Runtime": "runtime-name",
                "Attachment": "script-or-zip-name"
            },
            "outputs": {
                "Name": "output-name",
                "Selector": "selector.value",
                "Type": "data-type"
            }
        }
    ],
    "files": {
        "script-or-zip-name": {
            "checksums": {
                "sha256": "checksum"
            },
            "size": 1234
        }
    }
}
```

**YAML Automation Runbook 範例**  
下列範例以 YAML 格式顯示 Automation Runbook 的內容。文件結構描述的這份 0.3 版運作範例，也示範了如何使用 Markdown 來格式化文件描述。

```
description: >-
  ##Title: LaunchInstanceAndCheckState

  -----

  **Purpose**: This Automation runbook first launches an EC2 instance
  using the AMI ID provided in the parameter ```imageId```. The second step of
  this document 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 AMI ID available. | {{
  ssm:/aws/service/ami-amazon-linux-latest/al2023-ami-kernel-6.1-x86_64 }}
schemaVersion: '0.3'
assumeRole: 'arn:aws:iam::111122223333::role/AutomationServiceRole'
parameters:
  imageId:
    type: String
    default: '{{ ssm:/aws/service/ami-amazon-linux-latest/al2023-ami-kernel-6.1-x86_64 }}'
    description: >-
      (Optional) The AMI ID to use for launching the instance. The default value
      uses the latest released Amazon Linux AMI ID.
  tagValue:
    type: String
    default: ' LaunchedBySsmAutomation'
    description: >-
      (Optional) The tag value to add to the instance. The default value is
      LaunchedBySsmAutomation.
  instanceType:
    type: String
    default: t2.micro
    description: >-
      (Optional) The instance type to use for the instance. The default value is
      t2.micro.
mainSteps:
  - name: LaunchEc2Instance
    action: 'aws:executeScript'
    outputs:
      - Name: payload
        Selector: $.Payload
        Type: StringMap
    inputs:
      Runtime: python3.11
      Handler: launch_instance
      Script: ''
      InputPayload:
        image_id: '{{ imageId }}'
        tag_value: '{{ tagValue }}'
        instance_type: '{{ instanceType }}'
      Attachment: launch.py
    description: >-
      **About This Step**


      This step first launches an EC2 instance using the ```aws:executeScript```
      action and the provided python script.
  - name: WaitForInstanceStatusOk
    action: 'aws:executeScript'
    inputs:
      Runtime: python3.11
      Handler: poll_instance
      Script: |-
        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}
      InputPayload: '{{ LaunchEc2Instance.payload }}'
    description: >-
      **About This Step**


      The python script continuously polls the instance status check value for
      the instance launched in Step 1 until the ```ok``` status is returned.
files:
  launch.py:
    checksums:
      sha256: 18871b1311b295c43d0f...[truncated]...772da97b67e99d84d342ef4aEXAMPLE
```

## 安全參數處理範例
<a name="secure-parameter-examples"></a>

下列範例示範使用環境變數 `interpolationType` 來安全處理參數。

### 基本安全命令執行
<a name="basic-secure-command"></a>

此範例說明如何安全地處理命令參數：

**注意**  
在不使用雙括號的 SSM 文件中，技術上不需要 `allowedPattern`：`{{ }}`

------
#### [ YAML ]

```
---

schemaVersion: '2.2'
description: An example document.
parameters:
  Message:
    type: String
    description: "Message to be printed"
    default: Hello
    interpolationType: ENV_VAR
    allowedPattern: "^[^"]*$"
mainSteps:
  - action: aws:runShellScript
    name: printMessage
    precondition:
      StringEquals:
        - platformType
        - Linux
    inputs:
      runCommand:
        - echo {{Message}}
```

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

```
{
    "schemaVersion": "2.2",
    "description": "An example document.",
    "parameters": {
        "Message": {
            "type": "String",
            "description": "Message to be printed",
            "default": "Hello",
            "interpolationType": "ENV_VAR",
            "allowedPattern": "^[^"]*$"
        }
    },
    "mainSteps": [{
        "action": "aws:runShellScript",
        "name": "printMessage",
        "precondition": {
           "StringEquals": ["platformType", "Linux"]
        },
        "inputs": {
            "runCommand": [
              "echo {{Message}}"
            ]
        }
    }]
}
```

------

### 以編譯語言使用參數
<a name="interpreted-language-example"></a>

此範例示範在 Python 中安全處理參數：

------
#### [ YAML ]

```
---
schemaVersion: '2.2'
description: 'Secure Python script execution'
parameters:
  inputData:
    type: String
    description: 'Input data for processing'
    interpolationType: 'ENV_VAR'
mainSteps:
  - action: aws:runPowerShellScript
    name: runPython
    inputs:
      runCommand:
        - |
          python3 -c '
          import os
          import json
          
          # Safely access parameter through environment variable
          input_data = os.environ.get("SSM_inputData", "")
          
          # Process the data
          try:
              processed_data = json.loads(input_data)
              print(f"Successfully processed: {processed_data}")
          except json.JSONDecodeError:
              print("Invalid JSON input")
          '
```

------

### 回溯相容性範例
<a name="backwards-compatibility-example"></a>

此範例說明如何安全地處理參數，同時保持回溯相容性：

------
#### [ YAML ]

```
---
schemaVersion: '2.2'
description: 'Backwards compatible secure parameter handling'
parameters:
  userInput:
    type: String
    description: 'User input to process'
    interpolationType: 'ENV_VAR'
    allowedPattern: '^[^"]*$'

mainSteps:
  - action: aws:runShellScript
    name: processInput
    inputs:
      runCommand:
        - |
          # Handle both modern and legacy agent versions
          if [ -z "${SSM_userInput+x}" ]; then
              # Legacy agent - fall back to direct parameter reference
              export SSM_userInput="{{userInput}}"
          fi
          
          # Process the input securely
          echo "Processing input: $SSM_userInput"
```

------

**注意**  
在不使用雙括號的 SSM 文件中，技術上不需要 `allowedPattern`：`{{ }}`

## 參數安全最佳實務
<a name="parameter-security-best-practices"></a>

處理 SSM 文件中的參數時，請遵循下列最佳實務：
+ **使用環境變數插補** – 一律將 `interpolationType: "ENV_VAR"` 用於在命令執行中使用的字串參數。
+ **實作輸入驗證** – 使用 `allowedPattern`，將參數值限制為安全模式。
+ **處理舊式系統** – 包含不支援環境變數插補之舊版 SSM Agent 的備用邏輯。
+ **逸出特殊字元** – 在命令中使用參數值時，請正確逸出特殊字元，以防止 shell 解譯。
+ **限制參數範圍** – 為您的使用案例使用最嚴格的參數模式。

# 資料元素和參數
<a name="documents-syntax-data-elements-parameters"></a>

本主題描述 SSM 文件中使用的資料元素。用於建立文件的結構描述版本會定義文件接受的語法和資料元素。建議命令文件使用結構描述版本 2.2 或更新版本。Automation Runbook 使用結構描述版本 0.3。此外，Automation Runbook 支援使用 Markdown (一種標示語言)，可讓您新增維基樣式的描述至文件內，以及在文件內新增個別步驟。如需關於使用 Markdown 的詳細資訊，請參閱《AWS 管理主控台 入門指南》中的[在主控台中使用 Markdown](https://docs.aws.amazon.com/general/latest/gr/aws-markdown.html)。

下一節說明您可以在 SSM 文件中包含的資料元素。

## 頂層資料元素
<a name="top-level"></a>

**schemaVersion**  
要使用的結構描述版本。  
類型：版本  
必要：是

**description**  
您提供來描述文件用途的資訊。您也可以使用此欄位來指定參數是否需要執行文件的值，或者提供參數的值是否為選用項目。您可以在本主題的範例中看到必要參數和選用參數。  
類型：字串  
必要：否

**parameters**  
一種結構，定義文件接受的參數。  
為了在處理字串參數時增強安全性，您可以透過指定 `interpolationType` 屬性，使用環境變數插補。設定為 `ENV_VAR` 時，系統會建立名為 `SSM_parameter-name` 的環境變數，其中包含參數值。  
以下包含使用環境變數 `interpolationType` 的參數範例：  

```
{
    "schemaVersion": "2.2",
    "description": "An example document.",
    "parameters": {
        "Message": {
            "type": "String",
            "description": "Message to be printed",
            "default": "Hello",
            "interpolationType" : "ENV_VAR",
            "allowedPattern": "^[^"]*$"

        }
    },
    "mainSteps": [{
        "action": "aws:runShellScript",
        "name": "printMessage",
        "precondition" : {
           "StringEquals" : ["platformType", "Linux"]
        },
        "inputs": {
            "runCommand": [
              "echo {{Message}}"
            ]
        }
    }
}
```
在不使用雙括號的 SSM 文件中，技術上不需要 `allowedPattern`：`{{ }}`
對於常用的參數，建議您將這些參數存放在 Parameter Store ( AWS Systems Manager中的工具) 中。然後，您可以在文件中定義參考 Parameter Store 參數作為預設值的參數。若要參考 Parameter Store 參數，請使用下列語法。  

```
{{ssm:parameter-name}}
```
您可以使用參考 Parameter Store 參數的參數，方式與任何其他文件參數相同。在下列範例中，`commands` 參數的預設值是 Parameter Store 參數 `myShellCommands`。透過將 `commands` 參數指定為 `runCommand` 字串，文件會執行在 `myShellCommands` 參數中儲存的命令。  

```
---
schemaVersion: '2.2'
description: runShellScript with command strings stored as Parameter Store parameter
parameters:
  commands:
    type: StringList
    description: "(Required) The commands to run on the instance."
    default: ["{{ ssm:myShellCommands }}"],
            interpolationType : 'ENV_VAR'
            allowedPattern: '^[^"]*$'

mainSteps:
- action: aws:runShellScript
  name: runShellScriptDefaultParams
  inputs:
    runCommand:"{{ commands }}"
```

```
{
    "schemaVersion": "2.2",
    "description": "runShellScript with command strings stored as Parameter Store parameter",
    "parameters": {
      "commands": {
        "type": "StringList",
        "description": "(Required) The commands to run on the instance.",
        "default": ["{{ ssm:myShellCommands }}"],
        "interpolationType" : "ENV_VAR"
      }
    },
    "mainSteps": [
      {
        "action": "aws:runShellScript",
        "name": "runShellScriptDefaultParams",
        "inputs": {
            "runCommand": [
              "{{ commands }}"
          ]
        }
      }
    ]
  }
```
您在文件的 `parameters` 部分可以參考 `String` 和 `StringList` Parameter Store 參數。您無法參考 `SecureString` Parameter Store 參數。
如需有關 Parameter Store 的詳細資訊，請參閱「[AWS Systems Manager Parameter Store](systems-manager-parameter-store.md)」。  
類型：結構  
`parameters` 結結構接受下列的欄位和數值：  
+ `type`：(必要) 允許的值包括：`String`、`StringList`、`Integer`、`Boolean`、`MapList` 和 `StringMap`。若要查看每個類型的範例，在下一個部分請參閱 [SSM 文件參數 `type` 範例](#top-level-properties-type)。
**注意**  
指令類型文件僅支援 `String` 和 `StringList` 參數類型。
+ `description`(選用) 參數說明。
+ `default`：(選擇性) 在 Parameter Store 中預設的參數值或參考值。
+ `allowedValues`：(選擇性) 參數允許的值陣列。定義參數的允許值會驗證使用者輸入。如果使用者輸入不允許的值，則無法開始執行。

------
#### [ YAML ]

  ```
  DirectoryType:
    type: String
    description: "(Required) The directory type to launch."
    default: AwsMad
    allowedValues:
    - AdConnector
    - AwsMad
    - SimpleAd
  ```

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

  ```
  "DirectoryType": {
    "type": "String",
    "description": "(Required) The directory type to launch.",
    "default": "AwsMad",
    "allowedValues": [
      "AdConnector",
      "AwsMad",
      "SimpleAd"
    ]
  }
  ```

------
+ `allowedPattern`：(選擇性) 規則運算式，可驗證使用者輸入是否符合參數定義的模式。如果使用者輸入不符合允許的模式，則無法開始執行。
**注意**  
Systems Manager 執行兩次 `allowedPattern` 驗證。當您使用文件時，在 API 層級使用 [Java regex 程式庫](https://docs.oracle.com/javase/8/docs/api/java/util/regex/package-summary.html)執行第一次驗證。在處理文件之前，藉由使用 [GO Regexp 程式庫](https://pkg.go.dev/regexp)，在 SSM Agent 上執行第二次驗證。

------
#### [ YAML ]

  ```
  InstanceId:
    type: String
    description: "(Required) The instance ID to target."
    allowedPattern: "^i-(?:[a-f0-9]{8}|[a-f0-9]{17})$"
    default: ''
  ```

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

  ```
  "InstanceId": {
    "type": "String",
    "description": "(Required) The instance ID to target.",
    "allowedPattern": "^i-(?:[a-f0-9]{8}|[a-f0-9]{17})$",
    "default": ""
  }
  ```

------
+ `displayType`：（選用） 用來在 `textarea`中顯示 `textfield`或 AWS 管理主控台。 `textfield` 是單行文字方塊。 `textarea` 是多行文字區域。
+ `minItems`：(選擇性) 允許項目數量的最小值。
+ `maxItems`：(選擇性) 允許項目數量的最大值。
+ `minChars`：(選擇性) 允許參數字元數量的最小值。
+ `maxChars`：(選擇性) 允許參數字元數量的最大值。
+ `interpolationType`：(選用) 定義在命令執行之前如何處理參數值。設定為 `ENV_VAR` 時，參數值將作為名為 `SSM_parameter-name` 的環境變數。此功能將參數值視為常值字串，有助於防止命令注入。

  類型：字串

  有效值：`ENV_VAR`
必要：否

**variables**  
(僅限結構描述版本 0.3) 您可以在 Automation 執行手冊中的整個步驟中參考或更新的值。變數類似於參數，但有一個非常重要的差異。參數值在執行手冊的內容中是靜態的，但變數的值可以在執行手冊的內容中進行變更。更新變數的值時，資料類型必須與定義的資料類型相符。如需有關在自動化操作中更新變數值的資訊，請參閱 [`aws:updateVariable` - 更新執行手冊變數的值](automation-action-update-variable.md)  
類型：布林值 \$1 整數 \$1 MapList \$1 字串 \$1 StringList \$1 StringMap  
必要：否  

```
variables:
    payload:
        type: StringMap
        default: "{}"
```

```
{
    "variables": [
        "payload": {
            "type": "StringMap",
            "default": "{}"
        }
    ]
}
```

**runtimeConfig**  
(結構描述 1.2 版) 一個或多個 Systems Manager 外掛程式套用的執行個體組態。不能保證外掛程式按順序執行。  
類型：Dictionary<string,PluginConfiguration>  
必要：否

**mainSteps**  
(僅限結構描述版本 0.3、2.0 和 2.2) 可以包含多個步驟 (外掛程式) 的物件。外掛程式在步驟中定義。步驟會按文件中列出的順序執行。  
類型：Dictionary<string,PluginConfiguration>  
必要：是

**outputs**  
(僅限結構描述版本 0.3) 執行此文件所產生的資料，可用於其他程序。例如，如果您的文件建立新 AMI，您可以將 "CreateImage.ImageId" 指定為輸出值，然後使用此輸出在後續自動化執行中建立新的執行個體。如需輸出的詳細資訊，請參閱 [使用動作輸出作為輸入](automation-action-outputs-inputs.md)。  
類型：Dictionary<string,OutputConfiguration>  
必要：否

**files**  
(僅限結構描述 0.3) 連接至文件並在自動化執行期間執行的指令碼檔案 (及其檢查總和)。僅適用於包含 `aws:executeScript` 動作，以及已在一或多個步驟中指定附件的文件。  
若要了解 Automation 執行手冊支援的執行時期，請參閱 [`aws:executeScript` – 執行指令碼](automation-action-executeScript.md)。如需有關在 Automation Runbook 中包含指令碼的詳細資訊，請參閱 [在執行手冊中使用指令碼](automation-document-script-considerations.md) 和 [Automation 執行手冊的視覺化設計體驗](automation-visual-designer.md)。  
使用附件建立 Automation Runbook 時，您還必須使用 `--attachments` 選項 （適用於 AWS CLI) 或 `Attachments`（適用於 API 和 SDK) 指定附件檔案。您可以為存放在 Amazon Simple Storage Service (Amazon S3) 儲存貯體中的 SSM 文件和檔案指定檔案位置。如需詳細資訊，請參閱 AWS Systems Manager API 參考中的[附件](https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_CreateDocument.html#systemsmanager-CreateDocument-request-Attachments)。  

```
---
files:
  launch.py:
    checksums:
      sha256: 18871b1311b295c43d0f...[truncated]...772da97b67e99d84d342ef4aEXAMPLE
```

```
"files": {
    "launch.py": {
        "checksums": {
            "sha256": "18871b1311b295c43d0f...[truncated]...772da97b67e99d84d342ef4aEXAMPLE"
        }
    }
}
```
類型：Dictionary<string,FilesConfiguration>  
必要：否

## SSM 文件參數 `type` 範例
<a name="top-level-properties-type"></a>

SSM 文件中的參數類型是靜態的。這意味著參數類型在定義後便無法變更。將參數與 SSM 文件外掛程式搭配使用時，無法在外掛程式的輸入中動態變更參數的類型。例如，您無法在 `aws:runShellScript` 外掛程式的 `runCommand` 輸入中參考 `Integer` 參數，因為此輸入接受字串或字串清單。若要對外掛程式輸入使用參數，參數類型必須與接受的類型相符。例如，您必須為 `aws:updateSsmAgent` 外掛程式的 `allowDowngrade` 輸入指定 `Boolean` 類型參數。如果您的參數類型與外掛程式的輸入類型不相符，則 SSM 文件便無法驗證，且系統不會建立文件。在其他外掛程式或 AWS Systems Manager 自動化動作的輸入內使用下游參數時，也是如此。例如，您無法參考 `aws:runDocument` 外掛程式 `documentParameters` 輸入中的 `StringList` 參數。即使下游 SSM 文件參數類型是 `StringList` 參數且與您參考的參數相符，此 `documentParameters` 輸入仍會接受字串映射。

搭配使用參數與 自動化動作時，在大多數情況下建立 SSM 文件並不會驗證參數類型。只有當您使用 `aws:runCommand` 動作時，才會在您建立 SSM 文件時驗證參數類型。在所有其他情況下，則會在執行動作之前驗證動作的輸入之時，在自動化執行期間進行參數驗證。例如，如果您的輸入參數為 `String`，而您將其參考為 `aws:runInstances` 動作的 `MaxInstanceCount` 輸入的數值，則會建立 SSM 文件。不過，執行文件時，自動化會在驗證 `aws:runInstances` 動作時會失敗，因為 `MaxInstanceCount` 輸入需要 `Integer`.

以下是每個參數 `type` 的範例。

String  
一連串零或多個 Unicode 字元以雙引號框住。例如，"i-1234567890abcdef0"。使用反斜線逸出。  
字串參數可包含具有 `ENV_VAR` 值的選用 `interpolationType` 欄位，以啟用環境變數插補，進而提升安全性。  

```
---
InstanceId:
  type: String
  description: "(Optional) The target EC2 instance ID."
  interpolationType: ENV_VAR
```

```
"InstanceId":{
  "type":"String",
  "description":"(Optional) The target EC2 instance ID.",
  "interpolationType": "ENV_VAR"
}
```

StringList  
由逗號分隔的字串項目清單。例如，["cd 〜", "pwd"]。  

```
---
commands:
  type: StringList
  description: "(Required) Specify a shell script or a command to run."
  default: ""
  minItems: 1
  displayType: textarea
```

```
"commands":{
  "type":"StringList",
  "description":"(Required) Specify a shell script or a command to run.",
  "minItems":1,
  "displayType":"textarea"
}
```

Boolean  
僅接受 `true` 或 `false`。不接受「true」或 0。  

```
---
canRun:
  type: Boolean
  description: ''
  default: true
```

```
"canRun": {
  "type": "Boolean",
  "description": "",
  "default": true
}
```

Integer  
整數號碼。不接受十進位小數，例如 3.14159 或以雙引號括住的號碼，例如 "3"。  

```
---
timeout:
  type: Integer
  description: The type of action to perform.
  default: 100
```

```
"timeout": {
  "type": "Integer",
  "description": "The type of action to perform.",
  "default": 100    
}
```

StringMap  
金鑰與值的映射。金鑰和值必須是字串。例如，\$1"Env": "Prod"\$1。  

```
---
notificationConfig:
  type: StringMap
  description: The configuration for events to be notified about
  default:
    NotificationType: 'Command'
    NotificationEvents:
    - 'Failed'
    NotificationArn: "$dependency.topicArn"
  maxChars: 150
```

```
"notificationConfig" : {
  "type" : "StringMap",
  "description" : "The configuration for events to be notified about",
  "default" : {
    "NotificationType" : "Command",
    "NotificationEvents" : ["Failed"],
    "NotificationArn" : "$dependency.topicArn"
  },
  "maxChars" : 150
}
```

MapList  
StringMap 物件清單。  

```
blockDeviceMappings:
  type: MapList
  description: The mappings for the create image inputs
  default:
  - DeviceName: "/dev/sda1"
    Ebs:
      VolumeSize: "50"
  - DeviceName: "/dev/sdm"
    Ebs:
      VolumeSize: "100"
  maxItems: 2
```

```
"blockDeviceMappings":{
  "type":"MapList",
  "description":"The mappings for the create image inputs",
  "default":[
    {
      "DeviceName":"/dev/sda1",
      "Ebs":{
        "VolumeSize":"50"
      }
    },
    {
      "DeviceName":"/dev/sdm",
      "Ebs":{
        "VolumeSize":"100"
      }
    }
  ],
  "maxItems":2
}
```

## 檢視 SSM 命令文件內容
<a name="viewing-ssm-document-content"></a>

若要預覽 AWS Systems Manager (SSM) 命令文件的必要和選用參數，除了文件執行的動作之外，您還可以在 Systems Manager 主控台中檢視文件的內容。

**若要檢視 SSM 命令文件內容**

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

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

1. 在搜尋方塊中，選取 **Document type** (文件類型)，然後選取 **Command** (命令)。

1. 選擇文件名稱，然後選擇 ** Content** (內容) 標籤。

1. 在內容欄位中，檢閱文件的可用參數和動作步驟。

   例如，下圖顯示 (1) `version` 與 (2) `allowDowngrade` 是 `AWS-UpdateSSMAgent` 文件的可選參數，並且文件執行的第一個操作是 (3) `aws:updateSsmAgent`。  
![\[在 Systems Manager 主控台中檢視 SSM 文件內容\]](http://docs.aws.amazon.com/zh_tw/systems-manager/latest/userguide/images/view-document-content.png)

# 命令文件外掛程式參考
<a name="documents-command-ssm-plugin-reference"></a>

此參考說明您可以在 AWS Systems Manager (SSM) 命令類型文件中指定的外掛程式。這些外掛程式無法在使用 Automation 動作時用於 SSM Automation Runbook。如需 AWS Systems Manager 自動化動作的詳細資訊，請參閱 [Systems Manager Automation 動作參考](automation-actions.md)。

Systems Manager 會讀取 SSM 文件的內容，以決定在受管執行個體上執行的動作。每個文件包含程式碼執行部分。根據您文件的結構描述版本，這個程式碼執行部分可以包含一或多個外掛程式或步驟。有關於此的說明主題，外掛程式和步驟稱為 *外掛程式*。本節包含關於每個 Systems Manager 外掛程式的資訊。如需有關文件，包含建立文件和結構描述版本之間差異的更多資訊，請參閱 [AWS Systems Manager Documents](documents.md)。

對於接受字串參數的外掛程式 (例如 `aws:runShellScript` 和 `aws:runPowerShellScript`)，`interpolationType` 參數可以透過將參數輸入視為字串常值，而非潛在的可執行命令，來增強安全性。例如：

```
{
    "schemaVersion": "2.2",
    "description": "runShellScript with command strings stored as Parameter Store parameter",
    "parameters": {
      "commands": {
        "type": "StringList",
        "description": "(Required) The commands to run on the instance.",
        "default": ["{{ ssm:myShellCommands }}"],
        "interpolationType" : "ENV_VAR"
      }
    },
    //truncated
 }
```

**注意**  
此處說明的一些外掛程式僅能夠在 Windows Server 執行個體或 Linux 執行個體上執行。每個外掛程式須注意平台相容性。  
macOS 的 Amazon Elastic Compute Cloud (Amazon EC2) 執行個體支援下列文件外掛程式：  
`aws:refreshAssociation`
`aws:runShellScript`
`aws:runPowerShellScript`
`aws:softwareInventory`
`aws:updateSsmAgent`

**Topics**
+ [共用的輸入](#shared-inputs)
+ [`aws:applications`](#aws-applications)
+ [`aws:cloudWatch`](#aws-cloudWatch)
+ [`aws:configureDocker`](#aws-configuredocker)
+ [`aws:configurePackage`](#aws-configurepackage)
+ [`aws:domainJoin`](#aws-domainJoin)
+ [`aws:downloadContent`](#aws-downloadContent)
+ [`aws:psModule`](#aws-psModule)
+ [`aws:refreshAssociation`](#aws-refreshassociation)
+ [`aws:runDockerAction`](#aws-rundockeraction)
+ [`aws:runDocument`](#aws-rundocument)
+ [`aws:runPowerShellScript`](#aws-runPowerShellScript)
+ [`aws:runShellScript`](#aws-runShellScript)
+ [`aws:softwareInventory`](#aws-softwareinventory)
+ [`aws:updateAgent`](#aws-updateagent)
+ [`aws:updateSsmAgent`](#aws-updatessmagent)

## 共用的輸入
<a name="shared-inputs"></a>

透過 SSM Agent 3.0.502 版及更新版本，所有外掛程式都可使用以下輸入：

**finallyStep**  
您想要文件執行的最後一個步驟。如果對步驟定義了此輸入，則它的優先順序高於在 `onFailure` 或 `onSuccess` 輸入中指定的 `exit` 值。若要讓具有此輸入的步驟預期執行，該步驟必須是在文件的 `mainSteps` 中定義的最後一步。  
類型：布林值  
有效值：`true` \$1 `false`  
必要：否

**onFailure**  
如果您為具有 `exit` 值的外掛程式指定此輸入，且該步驟失敗，則步驟狀態會反映失敗，而且文件不會執行任何剩餘的步驟，除非已定義 `finallyStep`。如果您為具有 `successAndExit` 值的外掛程式指定此輸入，且該步驟失敗，則步驟狀態會顯示成功，而且文件不會執行任何剩餘的步驟，除非已定義 `finallyStep`。  
類型：字串  
有效值：`exit` \$1 `successAndExit`  
必要：否

**onSuccess**  
如果您為外掛程式指定此輸入，且該步驟成功執行，則文件不會執行任何剩餘的步驟，除非已定義 `finallyStep`。  
類型：字串  
有效值：`exit`  
必要：否

------
#### [ YAML ]

```
---
schemaVersion: '2.2'
description: Shared inputs example
parameters:
  customDocumentParameter:
    type: String
    description: Example parameter for a custom Command-type document.
mainSteps:
- action: aws:runDocument
  name: runCustomConfiguration
  inputs:
    documentType: SSMDocument
    documentPath: "yourCustomDocument"
    documentParameters: '"documentParameter":{{customDocumentParameter}}'
    onSuccess: exit
- action: aws:runDocument
  name: ifConfigurationFailure
  inputs:
    documentType: SSMDocument
    documentPath: "yourCustomRepairDocument"
    onFailure: exit
- action: aws:runDocument
  name: finalConfiguration
  inputs:
    documentType: SSMDocument
    documentPath: "yourCustomFinalDocument"
    finallyStep: true
```

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

```
{
   "schemaVersion": "2.2",
   "description": "Shared inputs example",
   "parameters": {
      "customDocumentParameter": {
         "type": "String",
         "description": "Example parameter for a custom Command-type document."
      }
   },
   "mainSteps":[
      {
         "action": "aws:runDocument",
         "name": "runCustomConfiguration",
         "inputs": {
            "documentType": "SSMDocument",
            "documentPath": "yourCustomDocument",
            "documentParameters": "\"documentParameter\":{{customDocumentParameter}}",
            "onSuccess": "exit"
         }
      },
      {
         "action": "aws:runDocument",
         "name": "ifConfigurationFailure",
         "inputs": {
            "documentType": "SSMDocument",
            "documentPath": "yourCustomRepairDocument",
            "onFailure": "exit"
         }
      },
      {
         "action": "aws:runDocument",
         "name":"finalConfiguration",
         "inputs": {
            "documentType": "SSMDocument",
            "documentPath": "yourCustomFinalDocument",
            "finallyStep": true
         }
      }
   ]
}
```

------

## `aws:applications`
<a name="aws-applications"></a>

安裝、修復或解除安裝在 EC2 執行個體上的應用程式。這個外掛程式只能在 Windows Server 作業系統上執行。

### 語法
<a name="applications-syntax"></a>

#### 結構描述 2.2
<a name="applications-syntax-2.2"></a>

------
#### [ YAML ]

```
---
schemaVersion: '2.2'
description: aws:applications plugin
parameters:
  source:
    description: "(Required) Source of msi."
    type: String
mainSteps:
- action: aws:applications
  name: example
  inputs:
    action: Install
    source: "{{ source }}"
```

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

```
{
  "schemaVersion":"2.2",
  "description":"aws:applications",
  "parameters":{
    "source":{
    "description":"(Required) Source of msi.",
    "type":"String"
    }
  },
  "mainSteps":[
    {
      "action":"aws:applications",
      "name":"example",
      "inputs":{
        "action":"Install",
        "source":"{{ source }}"
      }
    }
  ]
}
```

------

#### 結構描述 1.2
<a name="applications-syntax-1.2"></a>

------
#### [ YAML ]

```
---
runtimeConfig:
  aws:applications:
    properties:
    - id: 0.aws:applications
      action: "{{ action }}"
      parameters: "{{ parameters }}"
      source: "{{ source }}"
      sourceHash: "{{ sourceHash }}"
```

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

```
{
   "runtimeConfig":{
      "aws:applications":{
         "properties":[
            {
               "id":"0.aws:applications",
               "action":"{{ action }}",
               "parameters":"{{ parameters }}",
               "source":"{{ source }}",
               "sourceHash":"{{ sourceHash }}"
            }
         ]
      }
   }
}
```

------

### Properties
<a name="applications-properties"></a>

**動作**  
採取動作  
類型：列舉  
有效值：`Install` \$1 `Repair` \$1 `Uninstall`  
必要：是

**parameters**  
安裝的參數。  
類型：字串  
必要：否

**source**  
應用程式的 `.msi` 檔案 URL。  
類型：字串  
必要：是

**sourceHash**  
`.msi` 檔案的 SHA256 雜湊。  
類型：字串  
必要：否

## `aws:cloudWatch`
<a name="aws-cloudWatch"></a>

將資料從 Windows Server 匯出到 Amazon CloudWatch 或 Amazon CloudWatch Logs，並使用 CloudWatch 指標監控資料。這個外掛程式只能在 Windows Server 作業系統上執行。如需有關設定 CloudWatch 與 Amazon Elastic Compute Cloud (Amazon EC2) 整合的詳細資訊，請參閱《Amazon CloudWatch 使用者指南》**中的 [Collecting metrics, logs, and traces with the CloudWatch agent](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/Install-CloudWatch-Agent.html)。

**重要**  
統一的 CloudWatch 代理程式已取代 SSM Agent 作為將日誌資料傳送至 Amazon CloudWatch Logs 的工具。不支援 SSM Agent aws:cloudWatch 插件。建議只使用統一的 CloudWatch 代理程式來執行日誌收集流程。如需詳細資訊，請參閱下列主題：  
[將節點日誌傳送至統一 CloudWatch Logs (CloudWatch 代理程式)](monitoring-cloudwatch-agent.md)
[將 Windows Server 節點日誌收集遷移到 CloudWatch 代理程式](monitoring-cloudwatch-agent.md#monitoring-cloudwatch-agent-migrate)
《Amazon CloudWatch 使用者指南》**中的 [Collecting metrics, logs, and traces with the CloudWatch agent](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/Install-CloudWatch-Agent.html)。

您可以匯出和監控以下資料類型：

**ApplicationEventLog**  
將應用程式事件日誌資料傳送至 CloudWatch Logs。

**CustomLogs**  
將任何文字類日誌檔案傳送至 Amazon CloudWatch Logs。CloudWatch 外掛程式為日誌檔案建立指紋。系統會將資料位移與每個指紋建立關聯。當檔案改變時，外掛程式上傳檔案並記錄位移然後建立與指紋的關聯。此方法用於避免使用者開啟外掛程式，將服務與包含大量檔案的目錄關聯，並且系統會上傳所有檔案。  
請注意，如果您的應用程式在輪詢時嘗試截斷或清理日誌的任何日誌，任何 `LogDirectoryPath` 指定的日誌將可能遺失項目。例如，如果您想要限制的日誌檔案大小，達到該限制時建立新的日誌檔，然後持續將資料寫入新的檔案。

**ETW**  
將 Event Tracing for Windows (ETW) 資料傳送到 CloudWatch Logs。

**IIS**  
將 IIS 日誌資料傳送到 CloudWatch Logs。

**PerformanceCounter**  
將 Windows 效能計數器傳送到 CloudWatch。您可以選擇不同類別以作為指標上傳至 CloudWatch。對於每個您要上傳的效能計數器，建立一個 **PerformanceCounter** 部分具有唯一的 ID (例如，「PerformanceCounter2」、」 PerformanceCounter3」等) 和屬性設定。  
如果 AWS Systems Manager SSM Agent或 CloudWatch 外掛程式停止，效能計數器資料不會記錄在 CloudWatch 中。此行為不同於自訂日誌或 Windows 事件日誌。自訂日誌和 Windows 事件日誌會保留效能計數器資料，並且在 SSM Agent 或 CloudWatch 外掛程式能夠使用之後，將這些資料上傳到 CloudWatch。

**SecurityEventLog**  
將安全性日誌資料傳送至 CloudWatch Logs。

**SystemEventLog**  
將系統事件日誌資料傳送至 CloudWatch Logs。

您可以定義以下資料的目的地：

**CloudWatch**  
傳送您的效能計數器指標資料的目的地。您可以用唯一的 ID 增加多個區段 (例如「CloudWatch2」和「CloudWatch3」)，並替不同的區域指定新的 ID 然後傳遞相同的資料到不同的地點。

**CloudWatchLogs**  
傳送您的效能計數器日誌資料的目的地。您可以用唯一的 ID 增加多個區段 (例如「CloudWatchLogs2」和「CloudWatchLogs3」)，並替不同的區域指定新的 ID 然後傳遞相同的資料到不同的地點。

### 語法
<a name="cloudWatch-syntax"></a>

```
"runtimeConfig":{
        "aws:cloudWatch":{
            "settings":{
                "startType":"{{ status }}"
            },
            "properties":"{{ properties }}"
        }
    }
```

### 設定和屬性
<a name="cloudWatch-properties"></a>

**AccessKey**  
您的 存取金鑰 ID。此屬性是必要的，除非您使用 IAM 角色啟動執行個體。此屬性無法用於 SSM。  
類型：字串  
必要：否

**CategoryName**  
效能監控從效能計數器類別而來。  
類型：字串  
必要：是

**CounterName**  
效能監控的名稱從效能計數器類別而來。  
類型：字串  
必要：是

**CultureName**  
要記錄時間戳記的所在地區。如果 **CultureName** 為空白，它會預設為 Windows Server 執行個體使用的相同地區設定。  
類型：字串  
有效的數值: 支援數值的清單，請參閱 Microsoft 網頁中的 [National Language Support (NLS) (國家語言支援 (NLS) 參考)](https://msdn.microsoft.com/en-us/library/cc233982.aspx)。不支援 **div**、**div-MV**、**hu** 和 **hu-HU** 值。  
必要：否

**DimensionName**  
Amazon CloudWatch 指標的維度。若您指定 `DimensionName`，您必須指定 `DimensionValue`。在列出指標時，這些參數會提供另一種視圖。您也可以針對多個指標使用同一種維度，如此就能檢視屬於特定維度的所有指標。  
類型：字串  
必要：否

**DimensionValue**  
Amazon CloudWatch 指標的維度值。  
類型：字串  
必要：否

**編碼**  
使用的檔案編碼 (例如，UTF-8)。使用編碼名稱，而非顯示名稱。  
類型：字串  
有效數值: 如需支援值的清單，請參閱 Microsoft Learn Library 中的[編碼類別](https://learn.microsoft.com/en-us/dotnet/api/system.text.encoding?view=net-7.0)。  
必要：是

**篩選條件**  
日誌名稱的字首。將此參數留白，以監控所有檔案。  
類型：字串  
有效數值: 如需支援值的清單，請參閱 [ MSDN 上的 FileSystemWatcherFilter 屬性](http://msdn.microsoft.com/en-us/library/system.io.filesystemwatcher.filter.aspx)主題。  
必要：否

**流程**  
要上傳的每個資料類型，以及資料目的地 (CloudWatch 或 CloudWatch Logs)。例如，若要將在 `"Id": "PerformanceCounter"` 下定義的效能計數器傳送至在 `"Id": "CloudWatch"` 下定義的 CloudWatch 目的地，請輸入 **"PerformanceCounter,CloudWatch"**。同樣，若要將自訂日誌、ETW 日誌和系統日誌傳送至在 `"Id": "ETW"` 下定義的 CloudWatch Logs 目的地，請輸入 **"(ETW),CloudWatchLogs"**。除此之外，您可以將相同的效能計數器或日誌檔案傳送到一個以上的目的地。例如，如果要將應用程式日誌傳送到您在 `"Id": "CloudWatchLogs"` 和 `"Id": "CloudWatchLogs2"` 區段中所定義的兩個不同目的地，輸入 **"ApplicationEventLog,(CloudWatchLogs, CloudWatchLogs2)"**。  
類型：字串  
有效數值 (來源): `ApplicationEventLog` \$1 `CustomLogs` \$1 `ETW` \$1 `PerformanceCounter` \$1 `SystemEventLog` \$1 `SecurityEventLog`   
有效值 (目的地)：`CloudWatch` \$1 `CloudWatchLogs` \$1 `CloudWatch`*n* \$1 `CloudWatchLogs`*n*   
必要：是

**FullName**  
元件的完全名稱。  
類型：字串  
必要：是

**Id**  
識別資料來源或目的地。這識別符在組態檔案中必須是唯一的。  
類型：字串  
必要：是

**InstanceName**  
效能計數器執行個體的名稱。請勿使用星號 (\$1) 來表示所有的執行個體，因為每個效能計數器元件只支援一個指標。不過您可以使用 **\$1Total**。  
類型：字串  
必要：是

**層級**  
要傳送至 Amazon CloudWatch 的訊息類型。  
類型：字串  
有效值：  
+ **1** – 只上傳錯誤訊息。
+ **2** – 只上傳警告訊息。
+ **4** – 只上傳資訊訊息。
您可以一起新增值，以包含多個類型訊息。例如，**3** 表示錯誤訊息 (**1**) 和警告訊息 (**2**)都包含。數值 **7** 表示包含錯誤訊息 (**1**)、警告訊息 (**2**) 和資訊訊息 (**4**)。  
必要：是  
Windows Security Logs 應該設定層級為 7。

**LineCount**  
標頭中的行數，以辨識日誌檔案。例如，IIS 日誌檔幾乎都具有相同的標頭。您可以輸入 **3**，這會讀取日誌檔標頭的前三行來進行辨識。在 IIS 日誌檔中，第三行是日期和時間戳記，這在不同的日誌檔中是不一樣的。  
類型：整數  
必要：否

**LogDirectoryPath**  
對於 CustomLogs，此屬性是指 EC2 執行個體上存放日誌的路徑。對於 IIS 日誌，資料夾替個別的網站存放 IIS 日誌 (例如，**C:\$1\$1inetpub\$1\$1logs\$1\$1LogFiles\$1\$1W3SVC*n***)。IIS 日誌只支援 W3C 日誌格式。不支援 IIS、NCSA 和自訂格式。  
類型：字串  
必要：是

**LogGroup**  
您的日誌群組名稱。CloudWatch 主控台的 **Log Groups** (日誌群組) 畫面中會顯示此名稱。  
類型：字串  
必要：是

**LogName**  
日誌檔案的名稱。  

1. 若要在導覽窗格的事件檢視器中查找日誌名稱，請選取 **Applications and Services Logs** (應用程式和服務日誌)。

1. 在日誌清單中，在您要上傳的日誌上按一下滑鼠右鍵 (例如 `Microsoft` > `Windows` > `Backup` > `Operational`)，然後選取**建立自訂檢視**。

1. 在 **Create Custom View** (建立自訂檢視) 對話方塊中，選取 **XML** 標籤。**LogName** 位於 < 選取途徑 => 標籤 (例如，`Microsoft-Windows-Backup`)。複製此文字到 **LogName** 參數。
類型：字串  
有效值：`Application` \$1 `Security` \$1 `System` \$1 `Microsoft-Windows-WinINet/Analytic`  
必要：是

**LogStream**  
日誌串流目的地的名稱 若您使用 **\$1instance\$1id\$1**，日誌串流名稱是這個執行個體 ID 的預設值。  
類型：字串  
有效值：`{instance_id}` \$1 `{hostname}` \$1 `{ip_address}` *<log\$1stream\$1name>*  
如果輸入的日誌串流名稱尚未存在，CloudWatch Logs 會自動為您建立。您可以使用文字字串或預先定義的變數 (**\$1instance\$1id\$1**, **\$1hostname\$1**, **\$1ip\$1address\$1**，或是組合全部三者來定義日誌串流名稱。  
此參數中指定的日誌串流名稱會顯示在 CloudWatch 主控台的**Log Groups > Streams for *<YourLogStream>*** (日誌群組 > YourLogStream 串流) 畫面中。  
必要：是

**MetricName**  
您希望能包含效能資料的 CloudWatch 指標。  
請不要在名稱中使用特殊字元。如果您這麼做了、指標和相關警示可能不會運作。
類型：字串  
必要：是

**NameSpace**  
將會在指標命名空間寫入效能計數器資料。  
類型：字串  
必要：是

**PollInterval**  
上傳新的效能計數器和日誌資料時需要延遲多少秒。  
類型：整數  
有效值：將此屬性設為 5 個或多個秒。十五秒 (00:00:15) 是建議。  
必要：是

**區域**  
您要傳送日誌資料的 AWS 區域 。雖然您可以將效能計數器，傳送到與您傳送日誌資料所在位置不同的區域，還是建議您將此參數，設定為與執行個體執行位置相同的區域。  
類型：字串  
有效值：Systems Manager 和 CloudWatch Logs AWS 區域 支援的 區域 IDs，例如 `us-east-2`、 `eu-west-1`和 `ap-southeast-1`。如需每個服務 AWS 區域 支援的 清單，請參閱《》中的 [Amazon CloudWatch Logs Service Endpoints](https://docs.aws.amazon.com/general/latest/gr/cwl_region.html#cwl_region) 和 [Systems Manager 服務端點](https://docs.aws.amazon.com/general/latest/gr/ssm.html#ssm_region)*Amazon Web Services 一般參考*。  
必要：是

**SecretKey**  
您的 私密存取金鑰。此屬性是必要的，除非您使用 IAM 角色啟動執行個體。  
類型：字串  
必要：否

**startType**  
開啟或關閉執行個體上的 CloudWatch。  
類型：字串  
有效值：`Enabled` \$1 `Disabled`  
必要：是

**TimestampFormat**  
要使用的時間戳記格式。如需支援值的清單，請參閱 MSDN 上的[自訂日期和時間格式字串](http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx)主題。  
類型：字串  
必要：是

**TimeZoneKind**  
當您的日誌時間戳記中沒有時區資訊時，您需要提供時區資訊。如果此參數保留空白，且如果您的時間戳記不包含時區資訊，則 CloudWatch Logs 預設為本機時區。如果時間戳記已包含時區資訊，則會忽略此參數。  
類型：字串  
有效值：`Local` \$1 `UTC`  
必要：否

**單位**  
適合指標的測量單位。  
類型：字串  
有效數值: 秒 \$1 微秒 \$1 毫秒 \$1 位元組 \$1 千位元組 (KB) \$1 百萬位元組 (MB) \$1 十億位元組 (GB) \$1 兆位元組 (TB) \$1 位元 \$1 千位元 (kb) \$1 百萬位元 (Mb) \$1 十億位元 (Gb) \$1 兆位元 (Tb) \$1 百分比 \$1 計數 \$1 位元組/秒 \$1 千位元組 (KB)/秒 \$1 百萬位元組 (MB)/秒 \$1 十億位元組 (GB)/秒 \$1 兆位元組 (TB)/秒 \$1 位元/秒 \$1 千位元 (kb)/ 秒 \$1 百萬位元 (Mb)/秒 \$1 十億位元 (Gb)/秒 \$1 兆位元 (Tb)/秒 \$1 計數/秒 \$1 無。  
必要：是

## `aws:configureDocker`
<a name="aws-configuredocker"></a>

(結構描述 2.0 版本或更新版本) 設定執行個體來處理 Docker 和容器。大部分 Linux 變體和 Windows Server 作業系統都支援此外掛程式。

### 語法
<a name="configuredocker-syntax"></a>

#### 結構描述 2.2
<a name="configuredocker-syntax-2.2"></a>

------
#### [ YAML ]

```
---
schemaVersion: '2.2'
description: aws:configureDocker
parameters:
  action:
    description: "(Required) The type of action to perform."
    type: String
    default: Install
    allowedValues:
    - Install
    - Uninstall
mainSteps:
- action: aws:configureDocker
  name: configureDocker
  inputs:
    action: "{{ action }}"
```

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

```
{
  "schemaVersion": "2.2",
  "description": "aws:configureDocker plugin",
  "parameters": {
    "action": {
      "description": "(Required) The type of action to perform.",
      "type": "String",
      "default": "Install",
      "allowedValues": [
        "Install",
        "Uninstall"
      ]
    }
  },
  "mainSteps": [
    {
      "action": "aws:configureDocker",
      "name": "configureDocker",
      "inputs": {
        "action": "{{ action }}"
      }
    }
  ]
}
```

------

### 輸入
<a name="configuredocker-properties"></a>

**動作**  
執行動作的類型。  
類型：列舉  
有效值：`Install` \$1 `Uninstall`  
必要：是

## `aws:configurePackage`
<a name="aws-configurepackage"></a>

（結構描述 2.0 版或更新版本） 安裝或解除安裝 AWS Systems Manager Distributor套件。您可以安裝最新版本、預設版本或您指定的套件版本。也支援 AWS 提供的套件。這個外掛程式可在 Windows Server 和 Linux 作業系統上執行，但 Linux 作業系統不支援所有的可用套件。

的可用 AWS 套件Windows Server包括下列項目：`AWSPVDriver`、`AWSNVMe`、`AwsEnaNetworkDriver`、`AwsVssComponents`、`CodeDeployAgent`、 `AmazonCloudWatchAgent`和 `AWSSupport-EC2Rescue.`

Linux 作業系統的可用 AWS 套件包括下列項目：`CodeDeployAgent`、 `AmazonCloudWatchAgent`和 `AWSSupport-EC2Rescue`。

### 語法
<a name="configurepackage-syntax"></a>

#### 結構描述 2.2
<a name="configurepackage-syntax-2.2"></a>

------
#### [ YAML ]

```
---
schemaVersion: '2.2'
description: aws:configurePackage
parameters:
  name:
    description: "(Required) The name of the AWS package to install or uninstall."
    type: String
  action:
    description: "(Required) The type of action to perform."
    type: String
    default: Install
    allowedValues:
    - Install
    - Uninstall
  ssmParameter:
    description: "(Required) Argument stored in Parameter Store."
    type: String
    default: "{{ ssm:parameter_store_arg }}"
mainSteps:
- action: aws:configurePackage
  name: configurePackage
  inputs:
    name: "{{ name }}"
    action: "{{ action }}"
    additionalArguments: 
      "{\"SSM_parameter_store_arg\": \"{{ ssmParameter }}\", \"SSM_custom_arg\": \"myValue\"}"
```

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

```
{
   "schemaVersion": "2.2",
   "description": "aws:configurePackage",
   "parameters": {
      "name": {
         "description": "(Required) The name of the AWS package to install or uninstall.",
         "type": "String"
      },
      "action": {
         "description": "(Required) The type of action to perform.",
         "type": "String",
         "default": "Install",
         "allowedValues": [
            "Install",
            "Uninstall"
         ]
      },
      "ssmParameter": {
         "description": "(Required) Argument stored in Parameter Store.",
         "type": "String",
         "default": "{{ ssm:parameter_store_arg }}"
      }
   },
   "mainSteps": [
      {
         "action": "aws:configurePackage",
         "name": "configurePackage",
         "inputs": {
            "name": "{{ name }}",
            "action": "{{ action }}",
            "additionalArguments": "{\"SSM_parameter_store_arg\": \"{{ ssmParameter }}\", \"SSM_custom_arg\": \"myValue\"}"
         }
      }
   ]
}
```

------

### 輸入
<a name="configurepackage-properties"></a>

**name**  
要安裝或解除安裝的 AWS 套件名稱。可用套件包括：`AWSPVDriver`、`AwsEnaNetworkDriver`、`AwsVssComponents` 和 `AmazonCloudWatchAgent`。  
類型：字串  
必要：是

**動作**  
安裝或解除安裝套件  
類型：列舉  
有效值：`Install` \$1 `Uninstall`  
必要：是

**installationType**  
要執行的安裝類型。如果您指定 `Uninstall and reinstall`，套件會完全解除安裝，然後重新安裝。在重新安裝完成之前，應用程式無法使用。如果您指定 `In-place update`，根據您在更新指令碼中提供的指示，只會將新的或變更的檔案新增至現有的安裝。應用程式在整個更新程序中仍然可用。已發佈 AWS的套件不支援 `In-place update`選項。 `Uninstall and reinstall`是預設值。  
類型：列舉  
有效值：`Uninstall and reinstall` \$1 `In-place update`  
必要：否

**additionalArguments**  
提供給安裝、解除安裝或更新指令碼的 JSON 字串格式的其他參數。每個參數必須加上字首 `SSM_`。通過使用慣例 `{{ssm:parameter-name}}`，您可以參考其他引數中的 Parameter Store 參數。若要在安裝、解除安裝或更新指令碼中使用其他參數，您必須使用適用於作業系統的語法，將參數作為環境變數參考。例如，在 PowerShell 中，將 `SSM_arg` 引數作為 `$Env:SSM_arg` 參考。您定義的引數數目沒有限制，但額外的引數輸入有 4096 個字元限制。此限制包括您定義的所有金鑰和值。  
類型：StringMap  
必要：否

**version**  
特定版本的套件安裝或解除安裝。如果安裝，系統預設會安裝最新發佈的版本。如果移除，系統預設移除目前已安裝的版本。如果沒有找到任何安裝的版本，執行下載和解除安裝最新版本的動作。  
類型：字串  
必要：否

## `aws:domainJoin`
<a name="aws-domainJoin"></a>

將 EC2 執行個體加入網域。這個外掛程式可在 Linux 和 Windows Server 作業系統上執行。此外掛程式會將 Linux 執行個體的主機名稱變更為 EC2AMAZ-*XXXXXXX* 格式。如需加入 EC2 執行個體的詳細資訊，請參閱《 *AWS Directory Service 管理指南*》中的[將 EC2 執行個體加入您的 AWS Managed Microsoft AD Directory](https://docs.aws.amazon.com/directoryservice/latest/admin-guide/ms_ad_join_instance.html)。

### 語法
<a name="domainJoin-syntax"></a>

#### 結構描述 2.2
<a name="domainJoin-syntax-2.2"></a>

------
#### [ YAML ]

```
---
schemaVersion: '2.2'
description: aws:domainJoin
parameters:
  directoryId:
    description: "(Required) The ID of the directory."
    type: String
  directoryName:
    description: "(Required) The name of the domain."
    type: String
  directoryOU:
    description: "(Optional) The organizational unit to assign the computer object to."
    type: String
  dnsIpAddresses:
    description: "(Required) The IP addresses of the DNS servers for your directory."
    type: StringList
  hostname:
    description: "(Optional) The hostname you want to assign to the node."
    type: String
mainSteps:
- action: aws:domainJoin
  name: domainJoin
  inputs:
    directoryId: "{{ directoryId }}"
    directoryName: "{{ directoryName }}"
    directoryOU: "{{ directoryOU }}"
    dnsIpAddresses: "{{ dnsIpAddresses }}"
    hostname: "{{ hostname }}"
```

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

```
{
  "schemaVersion": "2.2",
  "description": "aws:domainJoin",
  "parameters": {
    "directoryId": {
      "description": "(Required) The ID of the directory.",
      "type": "String"
    },
    "directoryName": {
      "description": "(Required) The name of the domain.",
      "type": "String"
    },
    "directoryOU": {
        "description": "(Optional) The organizational unit to assign the computer object to.",
        "type": "String"
      },
    "dnsIpAddresses": {
      "description": "(Required) The IP addresses of the DNS servers for your directory.",
      "type": "StringList"
    },
    "hostname": {
        "description": "(Optional) The hostname you want to assign to the node.",
        "type": "String"
      }
  },
  "mainSteps": [
    {
      "action": "aws:domainJoin",
      "name": "domainJoin",
      "inputs": {
        "directoryId": "{{ directoryId }}",
        "directoryName": "{{ directoryName }}",
        "directoryOU":"{{ directoryOU }}",
        "dnsIpAddresses":"{{ dnsIpAddresses }}",
        "hostname":"{{ hostname }}"
      }
    }
  ]
}
```

------

#### 結構描述 1.2
<a name="domainJoin-syntax-1.2"></a>

------
#### [ YAML ]

```
---
runtimeConfig:
  aws:domainJoin:
    properties:
      directoryId: "{{ directoryId }}"
      directoryName: "{{ directoryName }}"
      directoryOU: "{{ directoryOU }}"
      dnsIpAddresses: "{{ dnsIpAddresses }}"
```

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

```
{
   "runtimeConfig":{
      "aws:domainJoin":{
         "properties":{
            "directoryId":"{{ directoryId }}",
            "directoryName":"{{ directoryName }}",
            "directoryOU":"{{ directoryOU }}",
            "dnsIpAddresses":"{{ dnsIpAddresses }}"
         }
      }
   }
}
```

------

### Properties
<a name="domainJoin-properties"></a>

**directoryId**  
目錄的 ID。  
類型：字串  
必要：是  
範例："directoryId": "d-1234567890"

**directoryName**  
網域的名稱。  
類型：字串  
必要：是  
範例："directoryName": "example.com"

**directoryOU**  
組織單位 (OU)。  
類型：字串  
必要：否  
範例："directoryOU": "OU=test,DC=example,DC=com"

**dnsIpAddresses**  
DNS 的 IP 地址。  
類型：StringList  
必要：是  
範例："dnsIpAddresses": ["198.51.100.1","198.51.100.2"]

**hostname**  
要指派給節點的主機名稱。如果未提供，則不會變更 Windows Server 執行個體的名稱，而 Linux 執行個體將使用預設命名模式。如果提供，Windows Server 執行個體將使用確切提供的值，而對於 Linux 執行個體，其作為字首 (除非 `keepHostName` 設定為 "true")。  
類型：字串  
必要：否

**keepHostName**  
確定在加入網域時是否變更 Linux 執行個體的主機名稱。這是僅限 Linux 的參數。依預設 (沒有對 `hostname`、`hostnameNumAppendDigits` 的輸入，而且 `keepHostName` 為 "false")，Linux 主機將被重新命名為模式 EC2AMAZ-XXXXXX。設定為 "true" 時，主機會保留原始主機名稱，並忽略對 `hostname` 和 `hostnameNumAppendDigits` 的輸入。  
類型：布林值  
必要：否

**hostnameNumAppendDigits**  
定義要在主機名稱值之後附加的隨機數字位數數量。這是僅限 Linux 的參數，並且可與 `hostname` 參數搭配使用。如果未提供 `hostname`，則會予以忽略。  
類型：字串  
允許的值：1 至 5  
必要：否

### 範例
<a name="domainJoin-examples"></a>

如需範例，請參閱[AWS Managed Microsoft AD管理指南](https://docs.aws.amazon.com/directoryservice/latest/admin-guide/ec2-join-aws-domain.html)中的*將 Amazon EC2 執行個體加入您的AWS Directory Service *。

## `aws:downloadContent`
<a name="aws-downloadContent"></a>

(結構描述 2.0 版本或更新版本) 從遠端位置下載 SSM 文件和指令碼。不支援 GitHub Enterprise 儲存庫。Linux 和 Windows Server 作業系統上支援此外掛程式。

### 語法
<a name="downloadContent-syntax"></a>

#### 結構描述 2.2
<a name="downloadContent-syntax-2.2"></a>

------
#### [ YAML ]

```
---
schemaVersion: '2.2'
description: aws:downloadContent
parameters:
  sourceType:
    description: "(Required) The download source."
    type: String
  sourceInfo:
    description: "(Required) The information required to retrieve the content from
      the required source."
    type: StringMap
mainSteps:
- action: aws:downloadContent
  name: downloadContent
  inputs:
    sourceType: "{{ sourceType }}"
    sourceInfo: "{{ sourceInfo }}"
```

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

```
{
  "schemaVersion": "2.2",
  "description": "aws:downloadContent",
  "parameters": {
    "sourceType": {
    "description": "(Required) The download source.",
    "type": "String"
  },
  "sourceInfo": {
    "description": "(Required) The information required to retrieve the content from the required source.",
    "type": "StringMap"
    }
  },
  "mainSteps": [
    {
      "action": "aws:downloadContent",
      "name": "downloadContent",
      "inputs": {
        "sourceType":"{{ sourceType }}",
        "sourceInfo":"{{ sourceInfo }}"
      }
    }
  ]
}
```

------

### 輸入
<a name="downloadContent-inputs"></a>

**sourceType**  
下載來源。Systems Manager 支援下列來源類型，用於下載指令碼和 SSM 文件：`GitHub`、`Git`、`HTTP`、`S3` 和 `SSMDocument`。  
類型：字串  
必要：是

**sourceInfo**  
從所需的來源中擷取所需的資訊內容。  
類型：StringMap  
必要：是  
 **對於來源類型 `GitHub,`，請指定以下資訊：**  
+ 擁有者：儲存庫擁有者。
+ 儲存庫: 儲存庫的名稱。
+ 路徑：您想要下載的檔案或目錄路徑。
+ getOptions：可從主要分支以外的分支或從儲存庫中的特定遞交中擷取內容的額外選項。如果您使用主要分支中的最新遞交，則可省略 getOptions。如果您的儲存庫是在 2020 年 10 月 1 日之後建立的，則預設分支可能被命名為 main 而不是 master。在此情況下，您需要指定 getOptions 參數的值。

  此參數使用以下的格式：
  + branch:refs/heads/*branch\$1name*

    預設值為 `master`。

    若要指定非預設分支，請使用以下格式：

    branch:refs/heads/*branch\$1name*
  + commitID：*commitID*

    預設值為 `head`。

    若要在最新遞交以外之其他遞交中使用您 SSM 文件的版本，請指定完整的遞交 ID。例如：

    ```
    "getOptions": "commitID:bbc1ddb94...b76d3bEXAMPLE",
    ```
+ tokenInfo：您存放 GitHub 存取權杖資訊所在的 Systems Manager 參數 (SecureString 參數)，格式為 `{{ssm-secure:secure-string-token-name}}`。
**注意**  
此 `tokenInfo` 欄位是唯一支援 SecureString 參數的 SSM 文件外掛程式欄位。其他欄位不支援 SecureString 參數，其他 SSM 文件外掛程式也不支援。

```
{
    "owner":"TestUser",
    "repository":"GitHubTest",
    "path":"scripts/python/test-script",
    "getOptions":"branch:master",
    "tokenInfo":"{{ssm-secure:secure-string-token}}"
}
```
 **對於來源類型 `Git`，您必須指定以下資訊：**  
+ repository

  您想要下載的檔案或目錄的 Git 存放庫 URL。

  類型：字串
此外，您還可以指定下列選用參數：  
+ getOptions

  可從主要分支以外的分支或從儲存庫中的特定遞交中擷取內容的額外選項。如果您使用主要分支中的最新遞交，則可省略 getOptions。

  類型：字串

  此參數使用以下的格式：
  + branch:refs/heads/*branch\$1name*

    預設值為 `master`。

    只有當 SSM 文件存放於 `master` 以外的分支時，才需要 `"branch"`。例如：

    ```
    "getOptions": "branch:refs/heads/main"
    ```
  + commitID：*commitID*

    預設值為 `head`。

    若要在最新遞交以外之其他遞交中使用您 SSM 文件的版本，請指定完整的遞交 ID。例如：

    ```
    "getOptions": "commitID:bbc1ddb94...b76d3bEXAMPLE",
    ```
+ privateSSHKey

  連線至您指定的 `repository` 時，要使用的 SSH 金鑰。您可以使用下列格式來參考 SSH 金鑰值的 `SecureString` 參數：`{{ssm-secure:your-secure-string-parameter}}`。

  類型：字串
+ skipHostKeyChecking

  連線至您指定的 `repository` 時，確定 StrictHostKeyChecking 選項的值。預設值為 `false`。

  類型：布林值
+ 使用者名稱

  使用 HTTP 連線至您指定的 `repository` 時，要使用的使用者名稱。您可以使用下列格式來參考使用者名稱值的 `SecureString` 參數：`{{ssm-secure:your-secure-string-parameter}}`。

  類型：字串
+ password

  使用 HTTP 連線至您指定的 `repository` 時，要使用的密碼。您可以使用下列格式來參考密碼值的 `SecureString` 參數：`{{ssm-secure:your-secure-string-parameter}}`。

  類型：字串
 **對於來源類型 `HTTP`，您必須指定以下資訊：**  
+ url

  您想要下載的檔案或目錄的 URL。

  類型：字串
此外，您還可以指定下列選用參數：  
+ allowInsecureDownload

  判斷是否可透過未使用 Secure Socket Layer (SSL) 或 Transport Layer Security (TLS) 進行加密的連線來執行下載。預設值為 `false`。不建議在未加密的情況下執行下載。如果您選擇這樣做，您應承擔所有相關風險。安全性是 AWS 與您之間的共同責任。這被描述為共同的責任模式。如需進一步了解，請參閱[共同的責任模型](https://aws.amazon.com/compliance/shared-responsibility-model/)。

  類型：布林值
+ authMethod

  當連線至您指定的 `url` 時，判斷是否要使用使用者名稱和密碼進行身分驗證。如果您指定 `Basic` 或 `Digest`，則必須提供 `username` 和 `password` 參數的值。若要使用 `Digest` 方法，必須在您的執行個體上安裝 SSM Agent 3.0.1181.0 版或更新版本。`Digest` 方法支援 MD5 和 SHA256 加密。

  類型：字串

  有效值：`None` \$1 `Basic` \$1 `Digest`
+ 使用者名稱

  使用 `Basic` 身分驗證連線至您指定的 `url` 時，要使用的使用者名稱。您可以使用下列格式來參考使用者名稱值的 `SecureString` 參數：`{{ssm-secure:your-secure-string-parameter}}`。

  類型：字串
+ password

  使用 `Basic` 身分驗證連線至您指定的 `url` 時，要使用的密碼。您可以使用下列格式來參考密碼值的 `SecureString` 參數：`{{ssm-secure:your-secure-string-parameter}}`。

  類型：字串
 **對於來源類型 `S3`，請指定以下資訊：**  
+ 路徑：您想要從 Amazon S3 中下載的檔案或目錄的 URL。
從 S3 儲存貯體下載檔案時，.etag 檔案會在下載目錄中產生。

```
{
    "path": "https://s3.amazonaws.com/amzn-s3-demo-bucket/powershell/helloPowershell.ps1" 
}
```
 **對於來源類型 `SSMDocument`，請指定下列其中*一項*：**  
+ 名稱：名稱和文件的版本，格式如下：`name:version`。版本是非必須的。

  ```
  {
      "name": "Example-RunPowerShellScript:3" 
  }
  ```
+ 名稱：文件的 ARN，格式如下：`arn:aws:ssm:region:account_id:document/document_name`

  ```
  {
     "name":"arn:aws:ssm:us-east-2:3344556677:document/MySharedDoc"
  }
  ```

**destinationPath**  
將您想要下載的檔案選用在的執行個體上的本機路徑。如果您不指定路徑的相對路徑，內容會下載到您的命令 ID 相對應的路徑。  
類型：字串  
必要：否

## `aws:psModule`
<a name="aws-psModule"></a>

在 Amazon EC2 執行個體上安裝 PowerShell 模組。這個外掛程式只能在 Windows Server 作業系統上執行。

### 語法
<a name="psModule-syntax"></a>

#### 結構描述 2.2
<a name="psModule-syntax-2.2"></a>

------
#### [ YAML ]

```
---
schemaVersion: '2.2'
description: aws:psModule
parameters:
  source:
    description: "(Required) The URL or local path on the instance to the application
      .zip file."
    type: String
mainSteps:
- action: aws:psModule
  name: psModule
  inputs:
    source: "{{ source }}"
```

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

```
{
  "schemaVersion": "2.2",
  "description": "aws:psModule",
  "parameters": {
    "source": {
      "description": "(Required) The URL or local path on the instance to the application .zip file.",
      "type": "String"
    }
  },
  "mainSteps": [
    {
      "action": "aws:psModule",
      "name": "psModule",
      "inputs": {
        "source": "{{ source }}"
      }
    }
  ]
}
```

------

#### 結構描述 1.2
<a name="domainJoin-syntax-1.2"></a>

------
#### [ YAML ]

```
---
runtimeConfig:
  aws:psModule:
    properties:
    - runCommand: "{{ commands }}"
      source: "{{ source }}"
      sourceHash: "{{ sourceHash }}"
      workingDirectory: "{{ workingDirectory }}"
      timeoutSeconds: "{{ executionTimeout }}"
```

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

```
{
   "runtimeConfig":{
      "aws:psModule":{
         "properties":[
            {
               "runCommand":"{{ commands }}",
               "source":"{{ source }}",
               "sourceHash":"{{ sourceHash }}",
               "workingDirectory":"{{ workingDirectory }}",
               "timeoutSeconds":"{{ executionTimeout }}"
            }
         ]
      }
   }
}
```

------

### Properties
<a name="psModule-properties"></a>

**runCommand**  
在模組安裝完畢後，PowerShell 的命令來執行。  
類型：StringList  
必要：否

**source**  
在的執行個體上應用程式 `.zip` 檔案的本機路徑或 URL。  
類型：字串  
必要：是

**sourceHash**  
`.zip` 檔案的 SHA256 雜湊。  
類型：字串  
必要：否

**timeoutSeconds**  
在命令完成到被認定為失敗之間的秒數。  
類型：字串  
必要：否

**workingDirectory**  
在您的執行個體上的工作目錄路徑。  
類型：字串  
必要：否

## `aws:refreshAssociation`
<a name="aws-refreshassociation"></a>

(結構描述 2.0 版本或更新版本) 更新 (強制套用) 有需要的關聯。這個動作會根據選中的關聯或者全部與目標有聯結的關聯裡的定義來改變系統的狀態。這個外掛程式可在 Linux 和 Microsoft Windows Server 作業系統上執行。

### 語法
<a name="refreshassociation-syntax"></a>

#### 結構描述 2.2
<a name="refreshassociation-syntax-2.2"></a>

------
#### [ YAML ]

```
---
schemaVersion: '2.2'
description: aws:refreshAssociation
parameters:
  associationIds:
    description: "(Optional) List of association IDs. If empty, all associations bound
      to the specified target are applied."
    type: StringList
mainSteps:
- action: aws:refreshAssociation
  name: refreshAssociation
  inputs:
    associationIds:
    - "{{ associationIds }}"
```

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

```
{
  "schemaVersion": "2.2",
  "description": "aws:refreshAssociation",
  "parameters": {
    "associationIds": {
      "description": "(Optional) List of association IDs. If empty, all associations bound to the specified target are applied.",
      "type": "StringList"
    }
  },
  "mainSteps": [
    {
      "action": "aws:refreshAssociation",
      "name": "refreshAssociation",
      "inputs": {
        "associationIds": [
          "{{ associationIds }}"
        ]
      }
    }
  ]
}
```

------

### 輸入
<a name="refreshassociation-properties"></a>

**associationIds**  
列出的關聯 ID。如果空，所有綁定到指定的目標的關聯都會被套用。  
類型：StringList  
必要：否

## `aws:runDockerAction`
<a name="aws-rundockeraction"></a>

(結構描述 2.0 版本或更新版本) 在容器上執行 Docker 動作。這個外掛程式可在 Linux 和 Microsoft Windows Server 作業系統上執行。

### 語法
<a name="rundockeraction-syntax"></a>

#### 結構描述 2.2
<a name="rundockeraction-syntax-2.2"></a>

------
#### [ YAML ]

```
---
mainSteps:
- action: aws:runDockerAction
  name: RunDockerAction
  inputs:
    action: "{{ action }}"
    container: "{{ container }}"
    image: "{{ image }}"
    memory: "{{ memory }}"
    cpuShares: "{{ cpuShares }}"
    volume: "{{ volume }}"
    cmd: "{{ cmd }}"
    env: "{{ env }}"
    user: "{{ user }}"
    publish: "{{ publish }}"
    workingDirectory: "{{ workingDirectory }}"
    timeoutSeconds: "{{ timeoutSeconds }}"
```

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

```
{
   "mainSteps":[
      {
         "action":"aws:runDockerAction",
         "name":"RunDockerAction",
         "inputs":{
            "action":"{{ action }}",
            "container":"{{ container }}",
            "image":"{{ image }}",
            "memory":"{{ memory }}",
            "cpuShares":"{{ cpuShares }}",
            "volume":"{{ volume }}",
            "cmd":"{{ cmd }}",
            "env":"{{ env }}",
            "user":"{{ user }}",
            "publish":"{{ publish }}",
            "workingDirectory": "{{ workingDirectory }}",
            "timeoutSeconds": "{{ timeoutSeconds }}"
         }
      }
   ]
}
```

------

### 輸入
<a name="rundockeraction-properties"></a>

**動作**  
執行動作的類型。  
類型：字串  
必要：是

**容器**  
Docker 容器的 ID。  
類型：字串  
必要：否

**image**  
Docker 影像名稱  
類型：字串  
必要：否

**命令提示字元**  
容器指令  
類型：字串  
必要：否

**memory**  
容器記憶體限制。  
類型：字串  
必要：否

**cpuShares**  
CPU 容器共享 (相對重量)。  
類型：字串  
必要：否

**磁碟區**  
容器磁碟容量。  
類型：StringList  
必要：否

**env**  
容器的環境變數。  
類型：字串  
必要：否

**user**  
容器的使用者名稱。  
類型：字串  
必要：否

**發布**  
容器發佈的連接埠。  
類型：字串  
必要：否

**workingDirectory**  
您受管節點上的工作目錄路徑。  
類型：字串  
必要：否

**timeoutSeconds**  
在命令完成到被認定為失敗之間的秒數。  
類型：字串  
必要：否

## `aws:runDocument`
<a name="aws-rundocument"></a>

(結構描述 2.0 版本或更新版本) 執行存放在 Systems Manager 或在本機共用的 SSM 文件。您可以搭配使用此外掛程式與 [`aws:downloadContent`](#aws-downloadContent)外掛程式，將 SSM 文件從遠端位置下載到本機共用，然後執行它。Linux 和 Windows Server 作業系統上支援此外掛程式。此外掛程式不支援執行 `AWS-UpdateSSMAgent` 文件或任何使用 `aws:updateSsmAgent` 外掛程式的文件。

### 語法
<a name="rundocument-syntax"></a>

#### 結構描述 2.2
<a name="aws-rundocument-syntax-2.2"></a>

------
#### [ YAML ]

```
---
schemaVersion: '2.2'
description: aws:runDocument
parameters:
  documentType:
    description: "(Required) The document type to run."
    type: String
    allowedValues:
    - LocalPath
    - SSMDocument
mainSteps:
- action: aws:runDocument
  name: runDocument
  inputs:
    documentType: "{{ documentType }}"
```

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

```
{
  "schemaVersion": "2.2",
  "description": "aws:runDocument",
  "parameters": {
    "documentType": {
      "description": "(Required) The document type to run.",
      "type": "String",
      "allowedValues": [
        "LocalPath",
        "SSMDocument"
      ]
    }
  },
  "mainSteps": [
    {
      "action": "aws:runDocument",
      "name": "runDocument",
      "inputs": {
        "documentType": "{{ documentType }}"
      }
    }
  ]
}
```

------

### 輸入
<a name="rundocument-properties"></a>

**documentType**  
執行的文件類型。您可以執行本機文件 (`LocalPath`) 或存放在 Systems Manager (`SSMDocument`) 的文件。  
類型：字串  
必要：是

**documentPath**  
文件的路徑。如果 `documentType` 是 `LocalPath`，請指定在本機共享的文件路徑。如果 `documentType` 是 `SSMDocument`，請指定文件的名稱。  
類型：字串  
必要：否

**documentParameters**  
文件的參數。  
類型：StringMap  
必要：否

## `aws:runPowerShellScript`
<a name="aws-runPowerShellScript"></a>

執行 PowerShell 指令碼或指定路徑來執行指令碼。這個外掛程式可在 Microsoft Windows Server 和 Linux 作業系統上執行。

### 語法
<a name="runPowerShellScript-syntax"></a>

#### 結構描述 2.2
<a name="runPowerShellScript-syntax-2.2"></a>

------
#### [ YAML ]

```
---
schemaVersion: '2.2'
description: aws:runPowerShellScript
parameters:
  commands:
    type: String
    description: "(Required) The commands to run or the path to an existing script
      on the instance."
    default: Write-Host "Hello World"
mainSteps:
- action: aws:runPowerShellScript
  name: runPowerShellScript
  inputs:
    timeoutSeconds: '60'
    runCommand:
    - "{{ commands }}"
```

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

```
{
  "schemaVersion": "2.2",
  "description": "aws:runPowerShellScript",
  "parameters": {
    "commands": {
      "type": "String",
      "description": "(Required) The commands to run or the path to an existing script on the instance.",
      "default": "Write-Host \"Hello World\""
    }
  },
  "mainSteps": [
    {
      "action": "aws:runPowerShellScript",
      "name": "runPowerShellScript",
      "inputs": {
        "timeoutSeconds": "60",
        "runCommand": [
          "{{ commands }}"
        ]
      }
    }
  ]
}
```

------

#### 結構描述 1.2
<a name="runPowerShellScript-syntax-1.2"></a>

------
#### [ YAML ]

```
---
runtimeConfig:
  aws:runPowerShellScript:
    properties:
    - id: 0.aws:runPowerShellScript
      runCommand: "{{ commands }}"
      workingDirectory: "{{ workingDirectory }}"
      timeoutSeconds: "{{ executionTimeout }}"
```

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

```
{
   "runtimeConfig":{
      "aws:runPowerShellScript":{
         "properties":[
            {
               "id":"0.aws:runPowerShellScript",
               "runCommand":"{{ commands }}",
               "workingDirectory":"{{ workingDirectory }}",
               "timeoutSeconds":"{{ executionTimeout }}"
            }
         ]
      }
   }
}
```

------

### Properties
<a name="runPowerShellScript-properties"></a>

**runCommand**  
指定命令或指定在執行個體上現有的指令碼的路徑來執行。  
類型：StringList  
必要：是

**timeoutSeconds**  
在命令完成到被認定為失敗之間的秒數。如果達到逾時，Systems Manager 停止命令執行。  
類型：字串  
必要：否

**workingDirectory**  
在您的執行個體上的工作目錄路徑。  
類型：字串  
必要：否

## `aws:runShellScript`
<a name="aws-runShellScript"></a>

執行 Linux shell 指令碼或指定路徑來執行指令碼。這個外掛程式只可在 Linux 作業系統上執行。

### 語法
<a name="runShellScript-syntax"></a>

#### 結構描述 2.2
<a name="runShellScript-syntax-2.2"></a>

------
#### [ YAML ]

```
---
schemaVersion: '2.2'
description: aws:runShellScript
parameters:
  commands:
    type: String
    description: "(Required) The commands to run or the path to an existing script
      on the instance."
    default: echo Hello World
mainSteps:
- action: aws:runShellScript
  name: runShellScript
  inputs:
    timeoutSeconds: '60'
    runCommand:
    - "{{ commands }}"
```

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

```
{
  "schemaVersion": "2.2",
  "description": "aws:runShellScript",
  "parameters": {
    "commands": {
      "type": "String",
      "description": "(Required) The commands to run or the path to an existing script on the instance.",
      "default": "echo Hello World"
    }
  },
  "mainSteps": [
    {
      "action": "aws:runShellScript",
      "name": "runShellScript",
      "inputs": {
        "timeoutSeconds": "60",
        "runCommand": [
          "{{ commands }}"
        ]
      }
    }
  ]
}
```

------

#### 結構描述 1.2
<a name="runShellScript-syntax-1.2"></a>

------
#### [ YAML ]

```
---
runtimeConfig:
  aws:runShellScript:
    properties:
    - runCommand: "{{ commands }}"
      workingDirectory: "{{ workingDirectory }}"
      timeoutSeconds: "{{ executionTimeout }}"
```

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

```
{
   "runtimeConfig":{
      "aws:runShellScript":{
         "properties":[
            {
               "runCommand":"{{ commands }}",
               "workingDirectory":"{{ workingDirectory }}",
               "timeoutSeconds":"{{ executionTimeout }}"
            }
         ]
      }
   }
}
```

------

### Properties
<a name="runShellScript-properties"></a>

**runCommand**  
指定命令或指定在執行個體上現有的指令碼的路徑來執行。  
類型：StringList  
必要：是

**timeoutSeconds**  
在命令完成到被認定為失敗之間的秒數。如果達到逾時，Systems Manager 停止命令執行。  
類型：字串  
必要：否

**workingDirectory**  
在您的執行個體上的工作目錄路徑。  
類型：字串  
必要：否

## `aws:softwareInventory`
<a name="aws-softwareinventory"></a>

(結構描述 2.0 版本或更新版本) 在受管執行個體上收集與應用程式、檔案和組態相關的中繼資料。這個外掛程式可在 Linux 和 Microsoft Windows Server 作業系統上執行。當您設定清查集合時，請先建立 AWS Systems Manager State Manager關聯。Systems Manager 會在執行關聯時收集庫存資料。如果沒有先建立關聯，則當您試圖叫用 `aws:softwareInventory` 外掛程式時，系統會傳回以下錯誤：

```
The aws:softwareInventory plugin can only be invoked via ssm-associate.
```

執行個體一次只能設定一個庫存關聯。若您為執行個體設定兩個以上的關聯，庫存關聯便不會執行，並且也不會收集任何庫存資料。如需收集庫存的相關資訊，請參閱 [AWS Systems Manager庫存](systems-manager-inventory.md)。

### 語法
<a name="softwareinventory-syntax"></a>

#### 結構描述 2.2
<a name="softwareinventory-syntax-2.2"></a>

------
#### [ YAML ]

```
---
mainSteps:
- action: aws:softwareInventory
  name: collectSoftwareInventoryItems
  inputs:
    applications: "{{ applications }}"
    awsComponents: "{{ awsComponents }}"
    networkConfig: "{{ networkConfig }}"
    files: "{{ files }}"
    services: "{{ services }}"
    windowsRoles: "{{ windowsRoles }}"
    windowsRegistry: "{{ windowsRegistry}}"
    windowsUpdates: "{{ windowsUpdates }}"
    instanceDetailedInformation: "{{ instanceDetailedInformation }}"
    customInventory: "{{ customInventory }}"
```

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

```
{
   "mainSteps":[
      {
         "action":"aws:softwareInventory",
         "name":"collectSoftwareInventoryItems",
         "inputs":{
            "applications":"{{ applications }}",
            "awsComponents":"{{ awsComponents }}",
            "networkConfig":"{{ networkConfig }}",
            "files":"{{ files }}",
            "services":"{{ services }}",
            "windowsRoles":"{{ windowsRoles }}",
            "windowsRegistry":"{{ windowsRegistry}}",
            "windowsUpdates":"{{ windowsUpdates }}",
            "instanceDetailedInformation":"{{ instanceDetailedInformation }}",
            "customInventory":"{{ customInventory }}"
         }
      }
   ]
}
```

------

### 輸入
<a name="softwareinventory-properties"></a>

**應用程式**  
(選用) 收集已安裝應用程式的中繼資料。  
類型：字串  
必要：否

**awsComponents**  
（選用） 收集 amazon-ssm-agent 等 AWS 元件的中繼資料。  
類型：字串  
必要：否

**files**  
(選用，需要 SSM Agent 2.2.64.0 版或更新版本) 收集檔案的中繼資料，包括檔案名稱、檔案的建立時間、上次修改和存取檔案的時間以及檔案大小等。如需收集檔案庫存的相關資訊，請參閱 [使用檔案與 Windows 登錄檔清查](inventory-file-and-registry.md)。  
類型：字串  
必要：否

**networkConfig**  
(選用) 收集網路組態的中繼資料。  
類型：字串  
必要：否

**billingInfo**  
(選用) 收集與 AMI 帳單代碼相關聯的平台詳細資訊中繼資料。  
類型：字串  
必要：否

**windowsUpdates**  
(選用) 收集所有 Windows 更新的中繼資料。  
類型：字串  
必要：否

**instanceDetailedInformation**  
(選用) 收集的執行個體資訊比預設庫存外掛程式 (`aws:instanceInformation`) 提供的更多，包括 CPU 模型、速度和核心數量等。  
類型：字串  
必要：否

**services**  
(選用，僅 Windows 作業系統需要 SSM Agent 2.2.64.0 版或更新版本) 收集服務組態的中繼資料。  
類型：字串  
必要：否

**windowsRegistry**  
(選用，僅 Windows 作業系統需要 SSM Agent 2.2.64.0 版或更新版本) 收集 Windows 登錄機碼和值。而且，您還能選擇機碼路徑，並以遞迴方式收集所有機碼和值。此外，您也可以收集指定路徑的特定登錄機碼及其值。庫存將收集機碼路徑、名稱、類型與值。如需收集 Windows 登錄檔庫存的詳細資訊，請參閱 [使用檔案與 Windows 登錄檔清查](inventory-file-and-registry.md)。  
類型：字串  
必要：否

**windowsRoles**  
(選用，僅 Windows 作業系統需要 SSM Agent 2.2.64.0 版或更新版本) 收集適用於 Microsoft Windows 角色組態的中繼資料。  
類型：字串  
必要：否

**customInventory**  
(選用) 收集自訂庫存資料。如需自訂庫存的詳細資訊，請參閱[使用自訂庫存](inventory-custom.md)。  
類型：字串  
必要：否

**customInventoryDirectory**  
(選用) 從指定的目錄中收集自訂庫存資料。如需自訂庫存的詳細資訊，請參閱[使用自訂庫存](inventory-custom.md)。  
類型：字串  
必要：否

## `aws:updateAgent`
<a name="aws-updateagent"></a>

更新 EC2Config 服務到最新版本或指定 EC2Config 服務的舊版本。這個外掛程式只能在 Microsoft Windows Server 作業系統上執行。如需有關 EC2Config 服務的詳細資訊，請參閱《Amazon EC2 使用者指南》**中的 [Configuring a Windows Instance using the EC2Config service (legacy)](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2config-service.html)。

### 語法
<a name="updateagent-syntax"></a>

#### 結構描述 2.2
<a name="updateagent-syntax-2.2"></a>

------
#### [ YAML ]

```
---
schemaVersion: '2.2'
description: aws:updateAgent
mainSteps:
- action: aws:updateAgent
  name: updateAgent
  inputs:
    agentName: Ec2Config
    source: https://s3.{Region}.amazonaws.com/aws-ssm-{Region}/manifest.json
```

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

```
{
  "schemaVersion": "2.2",
  "description": "aws:updateAgent",
  "mainSteps": [
    {
      "action": "aws:updateAgent",
      "name": "updateAgent",
      "inputs": {
        "agentName": "Ec2Config",
        "source": "https://s3.{Region}.amazonaws.com/aws-ssm-{Region}/manifest.json"
      }
    }
  ]
}
```

------

#### 結構描述 1.2
<a name="updateagent-syntax-1.2"></a>

------
#### [ YAML ]

```
---
runtimeConfig:
  aws:updateAgent:
    properties:
      agentName: Ec2Config
      source: https://s3.{Region}.amazonaws.com/aws-ssm-{Region}/manifest.json
      allowDowngrade: "{{ allowDowngrade }}"
      targetVersion: "{{ version }}"
```

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

```
{
   "runtimeConfig":{
      "aws:updateAgent":{
         "properties":{
            "agentName":"Ec2Config",
            "source":"https://s3.{Region}.amazonaws.com/aws-ssm-{Region}/manifest.json",
            "allowDowngrade":"{{ allowDowngrade }}",
            "targetVersion":"{{ version }}"
         }
      }
   }
}
```

------

### Properties
<a name="updateagent-properties"></a>

**agentName**  
EC2Config。這是執行 EC2Config 服務的代理名稱。  
類型：字串  
必要：是

**allowDowngrade**  
允許 EC2Config 服務降級到較舊的版本。如果設定為非，該服務只可以升級到較新版本 (預設)。如果設定為是，指定之前的舊版本。  
類型：布林值  
必要：否

**source**  
Systems Manager 複製 EC2Config 版本進行安裝的位置。您無法變更此位置。  
類型：字串  
必要：是

**targetVersion**  
安裝指定版本的 EC2Config 服務。如果未指定，服務會更新到最新版本。  
類型：字串  
必要：否

## `aws:updateSsmAgent`
<a name="aws-updatessmagent"></a>

將 SSM Agent 更新到最新版本或指定舊版本。這個外掛程式可在 Linux 和 Windows Server 作業系統上執行。如需詳細資訊，請參閱[使用 SSM Agent](ssm-agent.md)。

### 語法
<a name="updateSSMagent-syntax"></a>

#### 結構描述 2.2
<a name="updateaSSMgent-syntax-2.2"></a>

------
#### [ YAML ]

```
---
schemaVersion: '2.2'
description: aws:updateSsmAgent
parameters:
  allowDowngrade:
    default: 'false'
    description: "(Optional) Allow the Amazon SSM Agent service to be downgraded to
      an earlier version. If set to false, the service can be upgraded to newer versions
      only (default). If set to true, specify the earlier version."
    type: String
    allowedValues:
    - 'true'
    - 'false'
mainSteps:
- action: aws:updateSsmAgent
  name: updateSSMAgent
  inputs:
    agentName: amazon-ssm-agent
    source: https://s3.{Region}.amazonaws.com/amazon-ssm-{Region}/ssm-agent-manifest.json
    allowDowngrade: "{{ allowDowngrade }}"
```

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

```
{
  "schemaVersion": "2.2",
  "description": "aws:updateSsmAgent",
  "parameters": {
    "allowDowngrade": {
      "default": "false",
      "description": "(Required) Allow the Amazon SSM Agent service to be downgraded to an earlier version. If set to false, the service can be upgraded to newer versions only (default). If set to true, specify the earlier version.",
      "type": "String",
      "allowedValues": [
        "true",
        "false"
      ]
    }
  },
  "mainSteps": [
    {
      "action": "aws:updateSsmAgent",
      "name": "awsupdateSsmAgent",
      "inputs": {
        "agentName": "amazon-ssm-agent",
        "source": "https://s3.{Region}.amazonaws.com/amazon-ssm-{Region}/ssm-agent-manifest.json",
        "allowDowngrade": "{{ allowDowngrade }}"
      }
    }
  ]
}
```

------

#### 結構描述 1.2
<a name="updateaSSMgent-syntax-1.2"></a>

------
#### [ YAML ]

```
---
runtimeConfig:
  aws:updateSsmAgent:
    properties:
    - agentName: amazon-ssm-agent
      source: https://s3.{Region}.amazonaws.com/aws-ssm-{Region}/manifest.json
      allowDowngrade: "{{ allowDowngrade }}"
```

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

```
{
   "runtimeConfig":{
      "aws:updateSsmAgent":{
         "properties":[
            {
               "agentName":"amazon-ssm-agent",
               "source":"https://s3.{Region}.amazonaws.com/aws-ssm-{Region}/manifest.json",
               "allowDowngrade":"{{ allowDowngrade }}"
            }
         ]
      }
   }
}
```

------

### Properties
<a name="updateSSMagent-properties"></a>

**agentName**  
amazon-ssm-agent。這是在執行個體上處理請求和執行命令的 Systems Manager 代理程式名稱。  
類型：字串  
必要：是

**allowDowngrade**  
允許 SSM Agent 降級到較早的版本。如果設定為非，代理程式只可以升級到較新版本 (預設)。如果設定為是，指定之前的舊版本。  
類型：布林值  
必要：是

**source**  
Systems Manager 複製 SSM Agent 版本進行安裝的位置。您無法變更此位置。  
類型：字串  
必要：是

**targetVersion**  
指定安裝 SSM Agent 的版本。如果未指定，代理程式會更新到最新版本。  
類型：字串  
必要：否

# 建立 SSM 文件內容
<a name="documents-creating-content"></a>

如果 AWS Systems Manager 公有文件未執行您想要在 AWS 資源上執行的所有動作，您可以建立自己的 SSM 文件。您也可以使用主控台複製 SSM 文件。複製文件會將現有文件的內容複製到您可以修改的新文件中。建立或複製文件時，文件的內容不得超過 64 KB。此配額也包括在執行階段為輸入參數指定的內容。當您建立新的 `Command` 或 `Policy` 文件時，我們建議您使用結構描述 2.2 或更新版本，以便您可以利用最新的功能，例如文件編輯、自動版本控制、排序等。

## 撰寫 SSM 文件內容
<a name="writing-ssm-doc-content"></a>

若要建立您自己的 SSM 文件內容，請務必瞭解 SSM 文件提供的不同結構描述、功能、外掛程式和語法。我們建議您熟悉下列資源。
+  [撰寫您自己的 AWS Systems Manager 文件](https://aws.amazon.com/blogs//mt/writing-your-own-aws-systems-manager-documents/) 
+  [資料元素和參數](documents-syntax-data-elements-parameters.md) 
+  [結構描述、功能以及範例](documents-schemas-features.md) 
+  [命令文件外掛程式參考](documents-command-ssm-plugin-reference.md) 
+  [Systems Manager Automation 動作參考](automation-actions.md) 
+  [自動化系統變數](automation-variables.md) 
+  [其他執行手冊範例](automation-document-examples.md) 
+  透過 AWS Toolkit for Visual Studio Code 來[使用 Systems Manager Automation Runbook](https://docs.aws.amazon.com/toolkit-for-vscode/latest/userguide/systems-manager-automation-docs.html)
+  [Automation 執行手冊的視覺化設計體驗](automation-visual-designer.md) 
+  [在執行手冊中使用指令碼](automation-document-script-considerations.md) 

AWS 預先定義的 SSM 文件可能會執行您需要的一些動作。您可以根據文件類型，在自訂 SSM 文件中使用 `aws:runDocument`、`aws:runCommand` 或 `aws:executeAutomation` 外掛程式來呼叫這些文件。您也可以將這些文件的部分複製到自訂 SSM 文件中，然後編輯內容以符合您的需求。

**提示**  
建立 SSM 文件內容時，您可能會在測試時數次變更內容並更新 SSM 文件。下列命令會以您的最新內容更新 SSM 文件，並將文件的預設版本更新為文件的最新版本。  
Linux 和 Windows 命令使用 `jq` 命令列工具來篩選 JSON 回應資料。

```
latestDocVersion=$(aws ssm update-document \
    --content file://path/to/file/documentContent.json \
    --name "ExampleDocument" \
    --document-format JSON \
    --document-version '$LATEST' \
    | jq -r '.DocumentDescription.LatestVersion')

aws ssm update-document-default-version \
    --name "ExampleDocument" \
    --document-version $latestDocVersion
```

```
latestDocVersion=$(aws ssm update-document ^
    --content file://C:\path\to\file\documentContent.json ^
    --name "ExampleDocument" ^
    --document-format JSON ^
    --document-version "$LATEST" ^
    | jq -r '.DocumentDescription.LatestVersion')

aws ssm update-document-default-version ^
    --name "ExampleDocument" ^
    --document-version $latestDocVersion
```

```
$content = Get-Content -Path "C:\path\to\file\documentContent.json" | Out-String
$latestDocVersion = Update-SSMDocument `
    -Content $content `
    -Name "ExampleDocument" `
    -DocumentFormat "JSON" `
    -DocumentVersion '$LATEST' `
    | Select-Object -ExpandProperty LatestVersion

Update-SSMDocumentDefaultVersion `
    -Name "ExampleDocument" `
    -DocumentVersion $latestDocVersion
```

### SSM 文件的安全最佳實務
<a name="ssm-document-security-practices"></a>

建立 SSM 文件時，請遵循這些安全最佳實務，以協助防止命令注入，確保安全處理參數：
+ 針對將在命令或指令碼中使用的字串參數，使用環境變數插補。將具有 `ENV_VAR` 值的 `interpolationType` 屬性新增至字串參數：

  ```
  {
      "command": {
          "type": "String",
          "description": "Command to execute",
          "interpolationType": "ENV_VAR"
      }
  }
  ```

  您可以透過指定在插補傳遞的值中不接受雙引號，進一步提高 SSM 文件的安全性：

  ```
  {
      "command": {
          "type": "String",
          "description": "Command to execute",
          "interpolationType": "ENV_VAR",
              "allowedPattern": "^[^"]*$"
      }
  }
  ```
+ 使用 Python、Ruby 或 Node.js 等編譯語言時，請使用適當的環境變數語法來參考參數：

  ```
  # Python example
  import os
  command = os.environ['SSM_Message']
  ```
+ 為了回溯相容於舊版 SSM Agent (3.3.2746.0 版之前)，請包含環境變數的備用邏輯：

  ```
  if [ -z "${SSM_command+x}" ]; then
      export SSM_command="{{command}}"
  fi
  ```
+ 將環境變數插補與 `allowedPattern` 結合，以進行額外的輸入驗證。在下列範例中，`allowedPattern` 值 `^[^"]*$` 會特別防止字串值中的雙引號：

  ```
  {
      "command": {
          "type": "String",
          "interpolationType": "ENV_VAR",
          "allowedPattern": "^[a-zA-Z0-9_-]+$"
      }
  }
  ```
+ 實作 SSM 文件之前，請驗證下列安全性考量：
  + 接受使用者輸入的所有字串參數會適時使用環境變數插補。
  + 盡可能使用 `allowedPattern` 實作輸入驗證。
  + 文件包含適用於參數處理的適當錯誤處理。
  + 對於使用舊版 SSM Agent 的環境，會維持回溯相容性。

如需有關 Systems Manager 存取 AWS 的服務擁有資源以及如何設定資料周邊政策的資訊，請參閱 [中的資料周邊 AWS Systems Manager](data-perimeters.md)。

## 複製 SSM 文件
<a name="cloning-ssm-document"></a>

您可以使用 Systems Manager 文件主控台來複製 AWS Systems Manager 文件，以建立 SSM 文件。複製 SSM 文件會將現有文件的內容複製到您可以修改的新文件中。您無法複製大於 64 KB 的文件。

**若要複製 SSM 文件**

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

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

1. 在搜尋方塊中，輸入您要複製的文件的名稱。

1. 選擇您要翻製的文件名稱，然後選擇 **Actions** (動作) 下拉式選單中的 **Clone document** (複製文件)。

1. 視需要修改文件，然後選擇 **Create document** (建立文件) 以儲存文件。

撰寫 SSM 文件內容之後，您可以使用下列其中一種方法來建立 SSM 文件。

**Topics**
+ [撰寫 SSM 文件內容](#writing-ssm-doc-content)
+ [複製 SSM 文件](#cloning-ssm-document)
+ [建立複合文件](#documents-creating-composite)

## 建立複合文件
<a name="documents-creating-composite"></a>

*composite* AWS Systems Manager (SSM) 文件是一種自訂文件，可透過執行一或多個次要 SSM 文件來執行一系列動作。複合文件提升了 *infrastructure as code*，讓您能夠為常見任務建立一組標準的 SSM 文件，例如自舉軟體或網域加入執行個體。然後，您可以在相同的 AWS 帳戶 中跨 共用這些文件 AWS 區域 ，以減少 SSM 文件維護並確保一致性。

例如，您可以建立複合的文件來執行下列動作：

1. 安裝允許清單中的所有修補程式。

1. 安裝防毒軟體

1. 從 GitHub 下載指令碼並執行指令碼。

在這個範例中，自訂 SSM 文件中包含下列外掛程式以執行下列動作：

1. 用於執行 `AWS-RunPatchBaseline` 文件的 `aws:runDocument` 外掛程式，可安裝所有允許列出的修補程式。

1. 用於執行 `AWS-InstallApplication` 文件的 `aws:runDocument` 外掛程式，可安裝防毒軟體。

1. 用於從 GitHub 下載並執行指令碼的 `aws:downloadContent` 外掛程式。

複合和次要文件可以存放在 Systems Manager、GitHub (公有和私有儲存庫) 或 Amazon S3。您可以用 JSON 或 YAML 格式建立複合文件和次要文件。

**注意**  
複合文件的執行深度最多只能為三個文件。這表示複合文件可以呼叫一個子文件，以及該子文件可以再呼叫一個文件。

若要建立複合文件，需要在自訂 SSM 文件中新增 [`aws:runDocument`](documents-command-ssm-plugin-reference.md#aws-rundocument) 外掛程式，並指定所需的輸入。下列的範例是個建立複合的文件來執行下列動作：

1. 執行 [`aws:downloadContent`](documents-command-ssm-plugin-reference.md#aws-downloadContent) 外掛程式，將 SSM 文件從 GitHub 公有儲存庫下載到名為 bootstrap 的本機目錄。此 SSM 文件稱為 StateManagerBootstrap.yml (YAML 文件)。

1. 執行 `aws:runDocument` 外掛程式，以執行 StateManagerBootstrap.yml 文件。無需指定參數。

1. 執行 `aws:runDocument` 外掛程式，以執行 `AWS-ConfigureDocker pre-defined` SSM 文件。指定的參數在執行個體上安裝 Docker。

```
{
  "schemaVersion": "2.2",
  "description": "My composite document for bootstrapping software and installing Docker.",
  "parameters": {
  },
  "mainSteps": [
    {
      "action": "aws:downloadContent",
      "name": "downloadContent",
      "inputs": {
        "sourceType": "GitHub",
        "sourceInfo": "{\"owner\":\"TestUser1\",\"repository\":\"TestPublic\", \"path\":\"documents/bootstrap/StateManagerBootstrap.yml\"}",
        "destinationPath": "bootstrap"
      }
    },
    {
      "action": "aws:runDocument",
      "name": "runDocument",
      "inputs": {
        "documentType": "LocalPath",
        "documentPath": "bootstrap",
        "documentParameters": "{}"
      }
    },
    {
      "action": "aws:runDocument",
      "name": "configureDocker",
      "inputs": {
        "documentType": "SSMDocument",
        "documentPath": "AWS-ConfigureDocker",
        "documentParameters": "{\"action\":\"Install\"}"
      }
    }
  ]
}
```

**詳細資訊**  
+ 如需使用 Run Command 呼叫指令碼時重新開機伺服器和執行個體的資訊，請參閱 [執行命令時處理重新啟動](send-commands-reboot.md)。
+ 如需有關您能夠新增至自訂 SSM 文件的外掛程式的詳細資訊，請參閱 [命令文件外掛程式參考](documents-command-ssm-plugin-reference.md)。
+ 如果您只想簡單從遠端位置 (無須建立複合文件) 執行文件的詳細資訊，請參閱 [從遠端位置執行 文件](documents-running-remote-github-s3.md)。

# 使用文件
<a name="documents-using"></a>

本節包含有關如何使用及處理 SSM 文件的資訊。

**Topics**
+ [比較 SSM 文件版本](comparing-versions.md)
+ [建立 SSM 文件](create-ssm-console.md)
+ [刪除自訂 SSM 文件](deleting-documents.md)
+ [從遠端位置執行 文件](documents-running-remote-github-s3.md)
+ [共用 SSM 文件](documents-ssm-sharing.md)
+ [搜尋 SSM 文件](ssm-documents-searching.md)

# 比較 SSM 文件版本
<a name="comparing-versions"></a>

您可以在 Systems Manager 文件主控台中比較 AWS Systems Manager (SSM) 文件版本之間的內容差異。比較 SSM 文件的版本時，會反白顯示版本內容之間的差異。

**若要比較 SSM 文件內容 (主控台)**

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. 在文件清單中，選擇您要比較其內容的文件。

1. 在 **Content** (內容) 索引標籤中，選取 **Compare versions** (比較版本)，然後選擇您要與之比較內容的文件版本。

# 建立 SSM 文件
<a name="create-ssm-console"></a>

如 [撰寫 SSM 文件內容](documents-creating-content.md#writing-ssm-doc-content) 中所述，建立自訂 SSM 文件的內容後，您可以使用 Systems Manager 主控台，以您的內容建立 SSM 文件。

**建立 SSM 文件**

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. 選擇 **Create command or session (建立命令或工作階段)**。

1. 輸入文件的描述性名稱。

1. (選用) 針對 **Target type (目標類型)**，指定文件可在其上執行的資源類型。

1. 在 **Document type (文件類型)**清單中，選擇您要建立的文件類型。

1. 刪除 **Content (內容)** 欄位中的括號，然後貼上先前建立的文件。

1. (選用) 展開 **Document tags (文件標籤)** 區段，將一或多個標籤鍵值組套用至文件。

   標籤是您指派給資源的選用性中繼資料。標籤允許您以不同的方式 (例如用途、擁有者或環境) 將資源分類。例如，您可能想要標記文件來識別其執行的任務類型、目標作業系統類型以及其執行所在的環境。在這種情況下，您可以指定以下索引鍵名稱/值對：
   + `Key=TaskType,Value=MyConfigurationUpdate`
   + `Key=OS,Value=AMAZON_LINUX_2`
   + `Key=Environment,Value=Production`

1. 選擇 **Create document (建立文件)** 以儲存文件。

# 刪除自訂 SSM 文件
<a name="deleting-documents"></a>

如果您不想再使用自訂 SSM 文件，則可以使用 AWS Systems Manager 主控台刪除它。

**刪除 SSM 文件**

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. 選取您要刪除的文件。

1. 選取 **Delete** (刪除)。當提示您刪除文件時，請選取 **Delete** (刪除)。

如需使用命令列工具或 SDK 刪除 SSM 文件的範例，請參閱[`DeleteDocument` 搭配 AWS SDK 或 CLI 使用](example_ssm_DeleteDocument_section.md)。

# 從遠端位置執行 文件
<a name="documents-running-remote-github-s3"></a>

您可以使用`AWS-RunDocument`預先定義的 SSM 文件，從遠端位置執行 AWS Systems Manager (SSM) 文件。本文件支援執行在下列位置存放的 SSM 文件：
+ 公有和私有 GitHub 儲存庫 (不支援 GitHub Enterprise)
+ Amazon S3 儲存貯體
+ Systems Manager

雖然您也可以在 中使用 State Manager或 自動化工具來執行遠端文件 AWS Systems Manager，但下列程序僅說明如何在 Systems Manager 主控台中使用 AWS Systems Manager Run Command 來執行遠端 SSM 文件。

**注意**  
`AWS-RunDocument` 只能用來執行命令類型的 SSM 文件，而不能執行其他類型，例如 Automation Runbook。`AWS-RunDocument` 使用 `aws:downloadContent` 外掛程式。如需有關 `aws:downloadContent` 外掛程式的詳細資訊，請參閱 [`aws:downloadContent`](documents-command-ssm-plugin-reference.md#aws-downloadContent)。

**警告**  
`AWS-RunDocument` 可以從各種來源執行文件內容 (SSM 文件、GitHub、S3、URLs)。執行遠端文件時，評估的 IAM 許可是遠端文件`ssm:GetDocument`上的 和 `ssm:SendCommand`上的 `AWS-RunDocument`。如果您有拒絕存取特定 SSM 文件的 IAM 政策，具有`AWS-RunDocument`許可的使用者仍然可以透過將文件內容傳遞為參數來執行這些拒絕的文件，這可能不受相同文件特定 IAM 限制的約束。  
若要正確限制文件執行，請使用下列其中一種方法：  
**允許清單核准來源**：如果您需要使用巢狀文件執行，請使用每種來源類型的適當控制項來限制對核准來源的存取：用於控制 SSM 文件來源`ssm:GetDocument`的 IAM 政策、用於 Amazon S3 來源的 IAM 和 Amazon S3 儲存貯體政策，以及用於公有網際網路來源的網路設定 （例如 VPC 端點或安全群組）。
**限制對 AWS-RunDocument 的存取**：拒絕 `AWS-RunDocument`和任何其他在 IAM 政策中使用`aws:runDocument`外掛程式的文件，以防止巢狀文件執行。 `ssm:SendCommand`
**使用許可界限**：實作 IAM 許可界限來設定使用者的最大許可，防止他們執行未經授權的文件，無論執行方法為何。
如需 IAM 最佳實務和許可界限的詳細資訊，請參閱*AWS Identity and Access Management 《 使用者指南*》中的 [IAM 實體的許可界限](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_boundaries.html)。

**開始之前**  
在您可以開始執行遠端文件之前，請必須完成以下工作。
+ 建立一份 SSM 命令文件，並將它儲存在遠端位置。如需詳細資訊，請參閱[建立 SSM 文件內容](documents-creating-content.md)
+ 如果您打算執行存放在 GitHub 私有儲存庫中的遠端文件，則必須為 GitHub 安全存取權杖建立一個 Systems Manager `SecureString` 參數。您無法透過 SSH 手動傳遞權杖來存取 GitHub 私有儲存庫中的遠端文件。您必須將存取字符做為 Systems Manager `SecureString` 參數傳遞。如需建立 `SecureString` 參數的詳細資訊，請參閱 [在 Systems Manager 中建立 Parameter Store 參數](sysman-paramstore-su-create.md)。

## 執行遠端文件 (主控台)
<a name="documents-running-remote-github-s3-console"></a>

**執行遠端文件**

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

1. 在導覽窗格中，選擇 **Run Command**。

1. 選擇**執行命令**。

1. 在 **Document** (文件) 清單中，請選擇 **`AWS-RunDocument`**。

1. 在 **Command parameters (命令參數)** 中，針對 **Source Type (來源類型)** 選擇選項。
   + 如果選擇 **GitHub**，請指定**來源資訊**，資訊格式如下：

     ```
     {
         "owner": "owner_name",
         "repository": "repository_name",
         "path": "path_to_document",
         "getOptions":"branch:branch_name",
         "tokenInfo": "{{ssm-secure:secure-string-token}}"
     }
     ```

     例如：

     ```
     {
         "owner":"TestUser",
         "repository":"GitHubTestExamples",
         "path":"scripts/python/test-script",
         "getOptions":"branch:exampleBranch",
         "tokenInfo":"{{ssm-secure:my-secure-string-token}}"
     }
     ```
**注意**  
`getOptions` 是可從主要分支以外的分支或從儲存庫中的特定遞交中擷取內容的額外選項。如果您使用主要分支中的最新遞交，則可省略 `getOptions`。只有當 SSM 文件存放於 `master` 以外的分支時，才需要 `branch` 參數。  
若要使用存放庫中特定「遞交」**中的 SSM 文件，請使用 `commitID` 與 `getOptions` 來代替 `branch`。例如：  

     ```
     "getOptions": "commitID:bbc1ddb94...b76d3bEXAMPLE",
     ```
   + 如果您選擇 **S3**，指定 **Source Info (來源資訊)** 的資訊格式如下：

     ```
     {"path":"URL_to_document_in_S3"}
     ```

     例如：

     ```
     {"path":"https://s3.amazonaws.com/amzn-s3-demo-bucket/scripts/ruby/mySSMdoc.json"}
     ```
   + 如果您選擇 **SSMDocument**，指定 **Source Info (來源資訊)** 的資訊格式如下：

     ```
     {"name": "document_name"}
     ```

     例如：

     ```
     {"name": "mySSMdoc"}
     ```

1. 在 **Document Parameters** (文件參數) 欄位中輸入遠端 SSM 文件的參數。例如，如果您執行 `AWS-RunPowerShell` 文件，您可以指定：

   ```
   {"commands": ["date", "echo \"Hello World\""]}
   ```

   如果您執行 `AWS-ConfigureAWSPack` 文件，您可以指定：

   ```
   {
      "action":"Install",
      "name":"AWSPVDriver"
   }
   ```

1. 在 **Targets** (目標) 區段中，透過手動指定標籤、選取執行個體或邊緣裝置，或指定資源群組，選擇您要執行這項操作的受管節點。
**提示**  
如果您預期看到的受管節點未列出，請參閱 [疑難排解受管節點的可用性](fleet-manager-troubleshooting-managed-nodes.md) 以取得疑難排解秘訣。

1. 對於**其他參數**：
   + 在 **Comment** (註解) 中，輸入此命令的相關資訊。
   + 在**逾時 (秒)** 中，指定在命令執行全面失敗之前，系統要等候的秒數。

1. 對於 **Rate control** (速率控制)：
   + 在**並行**中，指定可同時執行命令的受管節點數目或百分比。
**注意**  
如果您透過指定套用至受管節點的標籤或指定 AWS 資源群組來選取目標，而且您不確定目標的受管節點數量，則透過指定百分比來限制可同時執行文件的目標數量。
   + 在 **Error threshold** (錯誤閾值) 中，指定在特定數目或百分比之節點上的命令失敗之後，停止在其他受管節點上執行命令。例如，如果您指定三個錯誤，則 Systems Manager 會在收到第四個錯誤時停止傳送命令。仍在處理命令的受管節點也可能會傳送錯誤。

1. (選用) 針對**輸出選項**，若要將命令輸出儲存至檔案，請選取**將命令輸出寫入至 S3 儲存貯體**方塊。在方塊中輸入儲存貯體和字首 (資料夾) 名稱。
**注意**  
授予能力以將資料寫入至 S3 儲存貯體的 S3 許可，會是指派給執行個體之執行個體設定檔 (適用於 EC2 執行個體) 或 IAM 服務角色 (啟用混合模式的機器) 的許可，而不是執行此任務之 IAM 使用者的許可。如需詳細資訊，請參閱[設定 Systems Manager 所需的執行個體許可](setup-instance-permissions.md)或[建立混合環境的 IAM 服務角色](hybrid-multicloud-service-role.md)。此外，若指定的 S3 儲存貯體位於不同的 AWS 帳戶內，請確保與受管節點相關聯的執行個體設定檔或 IAM 服務角色是否具有寫入該儲存貯體的必要許可。

1. 在**SNS 通知**區段中，如果您要傳送有關命令執行狀態的通知，請選取**啟用 SNS 通知**核取方塊。

   如需為 Run Command 設定 Amazon SNS 通知的詳細資訊，請參閱 [使用 Amazon SNS 通知監控 Systems Manager 狀態變更](monitoring-sns-notifications.md)。

1. 選擇**執行**。

**注意**  
如需使用 Run Command 呼叫指令碼時重新開機伺服器和執行個體的資訊，請參閱 [執行命令時處理重新啟動](send-commands-reboot.md)。

# 共用 SSM 文件
<a name="documents-ssm-sharing"></a>

您可以私下或公開地與相同 中的帳戶共用 AWS Systems Manager (SSM) 文件 AWS 區域。若要私下共用文件，您需要修改文件許可，並根據特定人員的 AWS 帳戶 ID 允許其進行存取。若要公開共用 SSM 文件，請修改文件許可並指定 `All`。文件不能同時公開和私下共用。

**警告**  
只能使用受信任來源的共用 SSM 文件。當您使用任何共用文件，請在使用文件之前仔細檢視文件的內容，讓您了解文件將會如何改變您執行個體的組態。如需共用文件的最佳實務詳細資訊，請參閱 [共用 SSM 文件的最佳實務](#best-practices-shared)。

**限制**  
當您開始使用 SSM 文件時，請注意以下限制。
+ 只有文件擁有者可以分享文件。
+ 您必須停止共用文件，才能刪除文件。如需詳細資訊，請參閱[修改共用 SSM 文件的許可](#modify-permissions-shared)。
+ 您可以共用最多 1000 個文件 AWS 帳戶。您可以在 [支援 中心](https://console.aws.amazon.com/support/home#/case/create?issueType=service-limit-increase)請求提高此限制。對於 **Limit type** (限制類型)，選擇 *EC2 Systems Manager* 並說明請求的原因。
+ 您最多可以公開共用五個 SSM 文件。您可以在 [支援 中心](https://console.aws.amazon.com/support/home#/case/create?issueType=service-limit-increase)請求提高此限制。對於 **Limit type** (限制類型)，選擇 *EC2 Systems Manager* 並說明請求的原因。
+ 文件只能與相同 中的其他帳戶共用 AWS 區域 。不支援跨區域共用。

**重要**  
在 Systems Manager 中，*Amazon 擁有的* SSM 文件是由 Amazon Web Services 本身建立和管理的文件。*Amazon 擁有的*文件的文件名中包含如 `AWS-*` 的字首。文件的擁有者被視為 Amazon，而不是其中的特定使用者帳戶 AWS。這些文件公開供所有人使用。

如需有關 Systems Manager 服務配額的詳細資訊，請參閱 [AWS Systems Manager Service Quotas](https://docs.aws.amazon.com/general/latest/gr/ssm.html#limits_ssm)。

**Topics**
+ [共用 SSM 文件的最佳實務](#best-practices-shared)
+ [封鎖 SSM 文件的公有共用](#block-public-access)
+ [共用 SSM 文件](#ssm-how-to-share)
+ [修改共用 SSM 文件的許可](#modify-permissions-shared)
+ [使用共用的 SSM 文件](#using-shared-documents)

## 共用 SSM 文件的最佳實務
<a name="best-practices-shared"></a>

共享或使用共用文件之前，請檢閱下列指導方針。

**移除敏感的資訊**  
請仔細檢閱您的 AWS Systems Manager (SSM) 文件，並移除任何敏感資訊。例如，確認文件不包含您的 AWS 登入資料。如果您與特定個人共享文件，這些使用者可以檢視文件中的資訊。如果您將文件設定為公開，任何使用者可以檢視文件中的資訊。

**封鎖文件的公有共用**  
檢閱帳戶中所有公開共用的 SSM 文件，並確認是否要繼續共用它們。若要停止公開共用文件，必須依照本主題的[修改共用 SSM 文件的許可](#modify-permissions-shared)章節所述修改文件許可設定。開啟封鎖公開共用設定不會影響目前正在公開共用的任何文件。除非您的使用案例需要公開共用文件，否則建議在 Systems Manager 文件主控台的**偏好設定**區段中開啟 SSM 文件的封鎖公開共用設定。開啟此設定可避免 SSM 文件遭到不必要的存取。封鎖公有共用設定是帳戶層級設定，每個 AWS 區域各有不同。

**使用 IAM 信任政策來限制 Run Command 動作**  
為可存取 文件的使用者建立限制性 AWS Identity and Access Management (IAM) 政策。IAM 政策決定使用者可以在 Amazon Elastic Compute Cloud (Amazon EC2) 主控台或使用 `ListDocuments` AWS Command Line Interface (AWS CLI) 或 呼叫 來查看哪些 SSM 文件 AWS Tools for Windows PowerShell。此政策也限制使用者在 SSM 文件上可執行哪些動作。您可以建立嚴格的政策，讓使用者只能使用特定的文件。如需詳細資訊，請參閱[客戶管理政策範例](security_iam_id-based-policy-examples.md#customer-managed-policies)。

**請小心使用共用的 SSM 文件**  
檢閱每個與您共享的文件內容，特別是公有文件。了解那些將在您的執行個體上執行的指令。文件執行後可能會有意或無意地產生負面影響。如果文件參考外部網路、先檢閱外部來源，然後再使用文件。

**使用文件雜湊來傳送命令**  
當您共用文件，系統會建立一個 SHA-256 雜湊並將其指派給文件。系統還會儲存文件內容的快照。當您使用共用文件來傳送命令，您可以在您的命令中指定雜湊以確保以下條件為真：  
+ 您正在執行正確的 Systems Manager 文件的命令
+ 自從與您共用文件後，文件內容尚未變更。
如果雜湊不符合指定的文件或者如果共用文件的內容被更改過，命令會傳回 `InvalidDocument` 的錯誤例外訊息。雜湊無法從外部位置驗證文件的內容。

**使用插補參數來改善安全性**  
對於 SSM 文件中的 `String` 類型參數，請使用參數和 `interpolationType": "ENV_VAR` 值，透過將參數輸入視為字串常值，而非潛在可執行命令，來提高安全性以防止命令注入攻擊。在此情況下，Agent 會使用參數的值，建立名為 `SSM_parameter-name` 的環境變數。建議您更新所有包含 `String` 類型參數的現有 SSM 文件，以包含 `"interpolationType": "ENV_VAR"`。如需詳細資訊，請參閱[撰寫 SSM 文件內容](documents-creating-content.md#writing-ssm-doc-content)。

## 封鎖 SSM 文件的公有共用
<a name="block-public-access"></a>

開始之前，請檢閱 AWS 帳戶 中所有公開共用的 SSM 文件，並確認是否要繼續共用它們。若要停止公開共用 SSM 文件，必須依照本主題的[修改共用 SSM 文件的許可](#modify-permissions-shared)章節所述修改文件許可設定。開啟封鎖公開共用設定不會影響目前正在公開共用的任何 SSM 文件。啟用封鎖公開共用設定後，您將無法公開共用任何其他 SSM 文件。

除非您的使用案例需要公開共用文件，否則建議開啟 SSM 文件的封鎖公開共用設定。開啟此設定可避免 SSM 文件遭到不必要的存取。封鎖公開共用設定是帳戶層級設定，每個設定可能有所不同 AWS 區域。完成下列任務，為目前未共用的 SSM 文件封鎖公開共用。

### 封鎖公有共用 (主控台)
<a name="block-public-access-console"></a>

**若要封鎖 SSM 文件的公有共用**

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

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

1. 選擇 **Preferences** (偏好設定)，然後在 **Block public sharing** (封鎖公有共用) 區段中選擇 **Edit** (編輯)。

1. 選取 **Block public sharing** (封鎖公有共用) 核取方塊，再選擇 **Save** (儲存)。

### 封鎖公有共用 (命令列)
<a name="block-public-access-cli"></a>

在本機 AWS Tools for Windows PowerShell 電腦上開啟 AWS Command Line Interface (AWS CLI) 或 ，並執行下列命令來封鎖 SSM 文件的公開共用。

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

```
aws ssm update-service-setting  \
    --setting-id /ssm/documents/console/public-sharing-permission \
    --setting-value Disable \
    --region 'The AWS 區域 you want to block public sharing in'
```

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

```
aws ssm update-service-setting ^
    --setting-id /ssm/documents/console/public-sharing-permission ^
    --setting-value Disable ^
    --region "The AWS 區域 you want to block public sharing in"
```

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

```
Update-SSMServiceSetting `
    -SettingId /ssm/documents/console/public-sharing-permission `
    -SettingValue Disable `
    –Region The AWS 區域 you want to block public sharing in
```

------

使用以下命令來確認設定值已更新。

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

```
aws ssm get-service-setting   \
    --setting-id /ssm/documents/console/public-sharing-permission \
    --region The AWS 區域 you blocked public sharing in
```

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

```
aws ssm get-service-setting  ^
    --setting-id /ssm/documents/console/public-sharing-permission ^
    --region "The AWS 區域 you blocked public sharing in"
```

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

```
Get-SSMServiceSetting `
    -SettingId /ssm/documents/console/public-sharing-permission `
    -Region The AWS 區域 you blocked public sharing in
```

------

### 限制存取以封鎖與 IAM 的公有共用
<a name="block-public-access-changes-iam"></a>

您可以建立 AWS Identity and Access Management (IAM) 政策，限制使用者修改封鎖公開共用設定。這可防止使用者允許 SSM 文件的不必要存取。

以下是防止使用者更新封鎖公有共用設定的 IAM 政策範例。若要使用此範例，您必須用您自己的帳戶 ID 取代範例 Amazon Web Services 帳戶 ID。

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

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Effect": "Deny",
            "Action": "ssm:UpdateServiceSetting",
            "Resource": "arn:aws:ssm:*:444455556666:servicesetting/ssm/documents/console/public-sharing-permission"
        }
    ]
}
```

------

## 共用 SSM 文件
<a name="ssm-how-to-share"></a>

您可以使用 Systems Manager 主控台共用 AWS Systems Manager (SSM) 文件。從主控台共用文件時，只能共用文件的預設版本。您也可以透過使用 (AWS CLI) 或 AWS SDK 呼叫 `ModifyDocumentPermission` API AWS Command Line Interface 操作 AWS Tools for Windows PowerShell，以程式設計方式共用 SSM 文件。在共用文件之前，先取得您要與其共用的人員的 AWS 帳戶 ID。當您要共享文件時，您可以指定這些帳戶 ID。

### 分享文件 (主控台)
<a name="share-using-console"></a>

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

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

1. 在文件清單中，選擇要共享的文件，然後選擇 **View details (查看詳細資訊)**。在 **Permissions** (許可) 索引標籤中，驗證您是文件的擁有者。只有文件擁有者可以分享文件。

1. 選擇**編輯**。

1. 若要公開共享命令，選擇 **Public (公有)**，然後選擇 **Save (儲存)**。若要私下共用命令，選擇 **Private** (私有)，輸入 AWS 帳戶 ID，選擇 **Add permission** (新增許可)，然後選擇 **Save** (儲存)。

### 分享文件 (命令列)
<a name="share-using-cli"></a>

下列程序需要您 AWS 區域 為命令列工作階段指定 。

1. 在本機 AWS Tools for Windows PowerShell 電腦上開啟 AWS CLI 或 ，並執行下列命令來指定您的登入資料。

   在下列命令中，用您自己的資訊取代*區域*。如需支援的 *region* 值的清單，請參閱《Amazon Web Services 一般參考》**中 [Systems Manager 服務端點](https://docs.aws.amazon.com/general/latest/gr/ssm.html#ssm_region)一節的**區域**資料欄。

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

   ```
   aws config
   
   AWS Access Key ID: [your key]
   AWS Secret Access Key: [your key]
   Default region name: region
   Default output format [None]:
   ```

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

   ```
   aws config
   
   AWS Access Key ID: [your key]
   AWS Secret Access Key: [your key]
   Default region name: region
   Default output format [None]:
   ```

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

   ```
   Set-AWSCredentials –AccessKey your key –SecretKey your key
   Set-DefaultAWSRegion -Region region
   ```

------

1. 使用下列命令列出所有可供您使用的 SSM 文件。清單中包含您建立和與您共享的文件。

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

   ```
   aws ssm list-documents
   ```

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

   ```
   aws ssm list-documents
   ```

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

   ```
   Get-SSMDocumentList
   ```

------

1. 使用下列命令來取得特定的文件：

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

   ```
   aws ssm get-document \
       --name document name
   ```

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

   ```
   aws ssm get-document ^
       --name document name
   ```

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

   ```
   Get-SSMDocument `
       –Name document name
   ```

------

1. 請使用下列命令取得文件的說明。

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

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

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

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

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

   ```
   Get-SSMDocumentDescription `
       –Name document name
   ```

------

1. 使用下列的指令來查看文件的許可權限：

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

   ```
   aws ssm describe-document-permission \
       --name document name \
       --permission-type Share
   ```

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

   ```
   aws ssm describe-document-permission ^
       --name document name ^
       --permission-type Share
   ```

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

   ```
   Get-SSMDocumentPermission `
       –Name document name `
       -PermissionType Share
   ```

------

1. 使用下列的指令來修改文件的許可權限並共享文件。您必須文件的擁有者才能夠編輯許可權限。對於與特定 AWS 帳戶 ID 共用的文件，也可以使用 `--shared-document-version` 參數指定要共用的文件版本。如果您未指定版本，則會共用文件的 `Default` 版本。如果您與 `all` 公開共用文件，則預設為共用指定文件的所有版本。下列範例命令會根據該人員的 AWS 帳戶 ID，私下與特定個人共用文件。

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

   ```
   aws ssm modify-document-permission \
       --name document name \
       --permission-type Share \
       --account-ids-to-add AWS 帳戶 ID
   ```

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

   ```
   aws ssm modify-document-permission ^
       --name document name ^
       --permission-type Share ^
       --account-ids-to-add AWS 帳戶 ID
   ```

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

   ```
   Edit-SSMDocumentPermission `
       –Name document name `
       -PermissionType Share `
       -AccountIdsToAdd AWS 帳戶 ID
   ```

------

1. 使用下列命令來公開共享的文件：
**注意**  
如果您與 `all` 公開共用文件，則預設為共用指定文件的所有版本。

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

   ```
   aws ssm modify-document-permission \
       --name document name \
       --permission-type Share \
       --account-ids-to-add 'all'
   ```

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

   ```
   aws ssm modify-document-permission ^
       --name document name ^
       --permission-type Share ^
       --account-ids-to-add "all"
   ```

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

   ```
   Edit-SSMDocumentPermission `
       -Name document name `
       -PermissionType Share `
       -AccountIdsToAdd ('all')
   ```

------

## 修改共用 SSM 文件的許可
<a name="modify-permissions-shared"></a>

如果您共用命令，使用者可以檢視和使用該命令，直到您移除對 AWS Systems Manager (SSM) 文件的存取權或刪除 SSM 文件為止。不過，您無法刪除正在共享的文件。您必須先停止共享，然後才能將其刪除止。

### 停止分享文件 (主控台)
<a name="unshare-using-console"></a>

**停止共享文件**

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

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

1. 在文件清單中，選擇要停止共用的文件，然後選擇**詳細資訊**。在**許可**區段中，確認您是文件擁有者。只有文件擁有者可以停止共享文件。

1. 選擇**編輯**。

1. 選擇 **X** 刪除不應再存取命令的 AWS 帳戶 ID，然後選擇**儲存**。

### 停止分享文件 (命令列)
<a name="unshare-using-cli"></a>

在本機 AWS Tools for Windows PowerShell 電腦上開啟 AWS CLI 或 ，並執行下列命令來停止共用命令。

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

```
aws ssm modify-document-permission \
    --name document name \
    --permission-type Share \
    --account-ids-to-remove 'AWS 帳戶 ID'
```

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

```
aws ssm modify-document-permission ^
    --name document name ^
    --permission-type Share ^
    --account-ids-to-remove "AWS 帳戶 ID"
```

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

```
Edit-SSMDocumentPermission `
    -Name document name `
    -PermissionType Share `
    –AccountIdsToRemove AWS 帳戶 ID
```

------

## 使用共用的 SSM 文件
<a name="using-shared-documents"></a>

當您共用 AWS Systems Manager (SSM) 文件時，系統會產生 Amazon Resource Name (ARN)，並將其指派給 命令。如果您從 Systems Manager 主控台選取和執行共用文件，則不會看到 ARN。但是，如果您想要使用 Systems Manager 主控台以外的其他方法執行共用的 SSM 文件，則必須為 `DocumentName` 請求參數指定文件的完整 ARN。當您執行命令列出文件時，系統會顯示 SSM 文件的完整 ARN。

**注意**  
您不需要為 AWS 公有文件 （以 開頭的文件`AWS-*`) 或您擁有的文件指定 ARNs。

### 使用共用的 SSM 文件 (命令列)
<a name="using-shared-documents-cli"></a>

 **列出所有公有 SSM 文件** 

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

```
aws ssm list-documents \
    --filters Key=Owner,Values=Public
```

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

```
aws ssm list-documents ^
    --filters Key=Owner,Values=Public
```

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

```
$filter = New-Object Amazon.SimpleSystemsManagement.Model.DocumentKeyValuesFilter
$filter.Key = "Owner"
$filter.Values = "Public"

Get-SSMDocumentList `
    -Filters @($filter)
```

------

 **列出已與您共用的私有 SSM 文件** 

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

```
aws ssm list-documents \
    --filters Key=Owner,Values=Private
```

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

```
aws ssm list-documents ^
    --filters Key=Owner,Values=Private
```

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

```
$filter = New-Object Amazon.SimpleSystemsManagement.Model.DocumentKeyValuesFilter
$filter.Key = "Owner"
$filter.Values = "Private"

Get-SSMDocumentList `
    -Filters @($filter)
```

------

 **列出可供您使用的所有 SSM 文件** 

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

```
aws ssm list-documents
```

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

```
aws ssm list-documents
```

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

```
Get-SSMDocumentList
```

------

 **取得已與您共用的 SSM 文件的相關資訊** 

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

```
aws ssm describe-document \
    --name arn:aws:ssm:us-east-2:12345678912:document/documentName
```

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

```
aws ssm describe-document ^
    --name arn:aws:ssm:us-east-2:12345678912:document/documentName
```

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

```
Get-SSMDocumentDescription `
    –Name arn:aws:ssm:us-east-2:12345678912:document/documentName
```

------

 **執行共用的 SSM 文件** 

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

```
aws ssm send-command \
    --document-name arn:aws:ssm:us-east-2:12345678912:document/documentName \
    --instance-ids ID
```

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

```
aws ssm send-command ^
    --document-name arn:aws:ssm:us-east-2:12345678912:document/documentName ^
    --instance-ids ID
```

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

```
Send-SSMCommand `
    –DocumentName arn:aws:ssm:us-east-2:12345678912:document/documentName `
    –InstanceIds ID
```

------

# 搜尋 SSM 文件
<a name="ssm-documents-searching"></a>

您可以使用任意文字搜尋或以篩選條件為基礎的搜尋，在 AWS Systems Manager (SSM) 文件存放區中搜尋 SSM 文件。您可以收藏文件，以協助您尋找常用的 SSM 文件。下列各節說明如何使用這些功能。

## 使用任意文字搜尋
<a name="ssm-documents-searching-free-text"></a>

Systems Manager **文件**頁面中的搜尋方塊支援任意文字搜尋。任意文字搜尋會根據每個 SSM 文件中的文件名稱來比較搜尋詞語或您輸入的詞語。如果您輸入單個搜尋詞語，例如 **ansible**，則 Systems Manager 會傳回含有此詞語的所有 SSM 文件。如果您輸入多個搜尋詞語，則 Systems Manager 會使用 `OR` 陳述式進行搜尋。例如，如果您指定 **ansible** 和 **linux**，然後搜尋會傳回其名稱中含有*任何一個*關鍵字的所有文件。

如果您輸入任意文字搜尋詞語，並選擇搜尋選項，例如 **平台類型**，則搜尋會使用 `AND` 陳述式，並傳回名稱中包含關鍵字和指定平台類型的所有文件。

**注意**  
請注意下列有關任意文字搜尋的詳細資訊。  
任意文字搜尋*不*區分大小寫。
搜尋詞語要求最少三個字元，最多 20 個字元。
任意文字搜尋最多可接受五個搜尋詞語。
如果您在搜尋詞語之間輸入空格，系統會在搜尋時包含空格。
您可以將任意文字搜尋與其他搜尋選項 (例如**文件類型**或**平台類型**) 結合在一起。
**文件名稱字首**篩選條件和任意文字搜尋不能一起使用。它們相互排斥。

**若要搜尋 SSM 文件**

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

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

1. 在搜尋方塊中輸入您的搜尋詞語，然後按 Enter 鍵。

### 使用 執行任意文字文件搜尋 AWS CLI
<a name="ssm-documents-searching-free-text-cli"></a>

**若要使用 CLI 執行任意文字文件搜尋**

1. 如果您尚未安裝並設定 AWS Command Line Interface (AWS CLI)，請安裝並設定 。

   如需相關資訊，請參閱[安裝或更新最新版本的 AWS CLI](https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html)。

1. 若要使用單一詞語執行任意文字文件搜尋，請執行以下命令。在此命令中，用您自己的資訊取代 *search\$1term*。

   ```
   aws ssm list-documents --filters Key="SearchKeyword",Values="search_term"
   ```

   範例如下。

   ```
   aws ssm list-documents --filters Key="SearchKeyword",Values="aws-asg" --region us-east-2
   ```

   若要使用多個詞語進行搜尋 (建立 `AND` 陳述式)，執行下列命令。在此命令中，用您自己的資訊取代 *search\$1term\$11* 和 *search\$1term\$12*。

   ```
   aws ssm list-documents --filters Key="SearchKeyword",Values="search_term_1","search_term_2","search_term_3" --region us-east-2
   ```

   範例如下。

   ```
   aws ssm list-documents --filters Key="SearchKeyword",Values="aws-asg","aws-ec2","restart" --region us-east-2
   ```

## 使用篩選條件
<a name="ssm-documents-searching-filters"></a>

Systems Manager **文件**頁面會在您選擇搜尋方塊時自動顯示下列篩選條件。
+ 文件名稱字首
+ 平台類型
+ 文件類型
+ 標籤鍵

![\[SSM 文件頁面上的篩選條件選項。\]](http://docs.aws.amazon.com/zh_tw/systems-manager/latest/userguide/images/ssm-documents-filters-1.png)


您可以使用單一篩選條件來搜尋 SSM 文件。如果您想要傳回更具體的 SSM 文件集，可以套用多個篩選條件。以下是使用**平台類型**與**文件名稱字首**篩選條件的搜尋範例。

![\[在 SSM 文件頁面上套用多個篩選條件選項。\]](http://docs.aws.amazon.com/zh_tw/systems-manager/latest/userguide/images/ssm-documents-filters-2.png)


如果您套用多個篩選條件，Systems Manager 會根據您選擇的篩選條件建立不同的搜尋陳述式：
+ 如果您多次套用*相同*篩選條件，例如**文件名稱字首**，Systems Manager 會使用 `OR` 陳述式進行搜尋。例如，如果您指定的一個篩選條件為**文件名稱字首**=**AWS**，第二個篩選條件為**文件名稱字首**=**Lambda**，則搜尋會傳回字首為 "`AWS`" 的所有文件以及字首為 "`Lambda`" 的所有文件。
+ 如果套用*不同的*篩選條件，例如 **Document name prefix** (文件名稱字首) 和 **Platform types** (平台類型)，則 Systems Manager 會使用 `AND` 陳述式進行搜尋。例如，如果指定 **Document name prefix** (文件名稱字首) = **AWS** 篩選條件、**Platform types** (平台類型) = **Linux** 篩選條件，則搜尋會傳回特定於 Linux 平台且字首為「`AWS`」的所有文件。

**注意**  
使用篩選條件的搜尋會區分大小寫。

## 將文件新增至收藏
<a name="favorite-documents"></a>

為了協助您尋找常用的 SSM 文件，請將文件新增至收藏。每個 AWS 帳戶 和 每個文件類型最多可以收藏 20 個文件 AWS 區域。您可以從文件 AWS 管理主控台選擇、修改及檢視收藏。下列程序說明如何選擇、修改和檢視收藏。

**收藏 SSM 文件**

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

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

1. 選擇要收藏的文件名稱旁的星形圖示。

**從收藏移除 SSM 文件**

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

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

1. 取消選擇要移出收藏的文件名稱旁的星形圖示。

**從文件檢視您的最愛 AWS 管理主控台**

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

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

1. 選取**收藏**索引標籤。

# 對參數處理問題進行疑難排解
<a name="parameter-troubleshooting"></a>

## 常見的參數處理問題
<a name="common-parameter-issues"></a>

**執行期間無法使用的環境變數**  
**問題：**由於找不到環境變數 (`SSM_parameter-name`)，命令失敗。  
**可能原因：**  
+ SSM Agent 版本不支援環境變數插補
+ `interpolationType` 未設定為 `ENV_VAR`
+ 參數名稱不符合預期的環境變數名稱
**解決方案**：  
+ 驗證 SSM Agent 版本是否為 3.3.2746.0 或更新版本
+ 新增舊版 Agent 的備用邏輯：

  ```
  if [ -z "${SSM_parameterName+x}" ]; then
      export SSM_parameterName="{{parameterName}}"
  fi
  ```

**參數值包含特殊字元**  
**問題：**當參數值包含空格、引號或其他特殊字元時，命令失敗。  
**解決方案**：  
+ 引用環境變數時使用適當的引號：

  ```
  # Correct
  echo "$SSM_parameter-name"
  
  # Incorrect
  echo $SSM_parameter-name
  ```
+ 使用 `allowedPattern` 新增輸入驗證以限制特殊字元

**跨平台的不一致行為**  
**問題：**參數處理在 Linux 和 Windows Server 系統上的運作方式不同。  
**解決方案**：  
+ 使用平台特定的環境變數語法：

  ```
  # PowerShell
  $env:SSM_parameter-name
  
  # Bash
  $SSM_parameter-name
  ```
+ 在您的文件中使用平台特定的先決條件檢查

**參數值未正確逸出**  
**問題：**儘管使用了環境變數插補，仍存在命令注入漏洞。  
**解決方案**：  
+ 命令中包含參數值時，一律使用適當的逸出：

  ```
  # Correct
  mysql_command="mysql -u \"$SSM_username\" -p\"$SSM_password\""
  
  # Incorrect
  mysql_command="mysql -u $SSM_username -p$SSM_password"
  ```

## 參數驗證技巧
<a name="parameter-validation"></a>

使用以下技巧來驗證參數處理：

1. 測試環境變數可用性：

   ```
   #!/bin/bash
   # Print all SSM_ environment variables
   env | grep ^SSM_
   
   # Test specific parameter
   if [ -n "$SSM_parameter" ]; then
       echo "Parameter is available"
   else
       echo "Parameter is not available"
   fi
   ```

1. 驗證參數模式：

   ```
   parameters:
     myParameter:
       type: String
       allowedPattern: "^[a-zA-Z0-9_-]+$"
       description: "Test this pattern with sample inputs"
   ```

1. 包含錯誤處理：

   ```
   if [[ ! "$SSM_parameter" =~ ^[a-zA-Z0-9_-]+$ ]]; then
       echo "Parameter validation failed"
       exit 1
   fi
   ```

# AWS Systems Manager Maintenance Windows
<a name="maintenance-windows"></a>

Maintenance Windows是 中的工具 AWS Systems Manager，可協助您定義何時對節點執行潛在破壞性動作的排程，例如修補作業系統、更新驅動程式，或安裝軟體或修補程式。

**注意**  
State Manager 和 Maintenance Windows 可以在受管節點上執行某些類似的更新。您選擇哪一項，取決於您是否需要在指定的期間內自動化系統合規，或執行高優先順序、時間敏感的任務。  
如需詳細資訊，請參閱[在 State Manager 與 Maintenance Windows 之間進行選擇](state-manager-vs-maintenance-windows.md)。

使用 Maintenance Windows，您可以在許多其他 AWS 資源類型上排程動作，例如 Amazon Simple Storage Service (Amazon S3) 儲存貯體、Amazon Simple Queue Service (Amazon SQS) 佇列、 AWS Key Management Service (AWS KMS) 金鑰等。

如需您可以在維護時段目標中包含的支援資源類型完整清單，請參閱*AWS Resource Groups 《 使用者指南*》中的[可與 AWS Resource Groups 和標籤編輯器搭配使用的資源](https://docs.aws.amazon.com/ARG/latest/userguide/supported-resources.html#supported-resources-console)。若要開始使用 Maintenance Windows，請開啟 [Systems Manager 主控台](https://console.aws.amazon.com//systems-manager/maintenance-windows)。在導覽窗格中，選擇 **Maintenance Windows**。

每個維護時段都有排程、最長持續時間、一組已註冊目標 （受管節點或其他處理 AWS 的資源），以及一組已註冊任務。當您建立或更新維護時段時，可以將標籤新增到您的維護時段。(標籤為索引鍵，可幫助識別和排序組織內的資源。) 您也可以指定不得在某日期之前或之後執行維護時段，亦可指定維護時段排程所依據的國際時區。

如需維護時段的各種排程相關選項彼此之間有何關聯的說明，請參閱 [維護時段排程與作用期間選項](maintenance-windows-schedule-options.md)。

如需使用 `--schedule` 選項的詳細資訊，請參閱[參考：Systems Manager 的 Cron 和 Rate 運算式](reference-cron-and-rate-expressions.md)。

**受支援任務類型**  
透過維護時段，您可以執行四種類型的任務：
+ Run Command (Systems Manager 中的工具) 中的命令

  如需 Run Command 的相關資訊，請參閱 [AWS Systems Manager Run Command](run-command.md)。
+ Automation (Systems Manager 中的工具) 中的工作流程

  如需自動化工作流程的相關詳細資訊，請參閱 [AWS Systems Manager 自動化](systems-manager-automation.md)。
+ 中的 函數 AWS Lambda

  如需有關 Lambda 函數的資訊，請參閱《AWS Lambda 開發人員指南》**中的 [Lambda 入門](https://docs.aws.amazon.com/lambda/latest/dg/getting-started.html)。
+ 中的任務 AWS Step Functions
**注意**  
維護時段任務僅支援 Step Functions 標準狀態機器工作流程。這些任務不支援快速狀態機器工作流程。如需有關狀態機器工作流程類型的資訊，請參閱《AWS Step Functions 開發人員指南》**中的[標準與快速工作流程](https://docs.aws.amazon.com/step-functions/latest/dg/concepts-standard-vs-express.html)。

  如需 Step Functions 的詳細資訊，請參閱《*[AWS Step Functions 開發人員指南](https://docs.aws.amazon.com/step-functions/latest/dg/)*》。

這表示您可以使用維護時段對所選目標執行類似下列任務。
+ 安裝或更新應用程式。
+ 套用修補程式。
+ 安裝或更新 SSM Agent
+ 藉由使用 Systems Manager Run Command 任務執行 PowerShell 命令和 Linux shell 指令碼。
+ 透過使用 Systems Manager Automation 任務以建置 Amazon Machine Images (AMIs)、啟動軟體和設定節點。
+ 執行叫用其他動作的 AWS Lambda 函數，例如掃描節點以取得修補程式更新。
+ 執行 AWS Step Functions 狀態機器來執行任務，例如從 Elastic Load Balancing 環境移除節點、修補節點，然後將節點新增回 Elastic Load Balancing 環境。
+ 透過指定 AWS 資源群組做為目標，將離線的節點設為目標。

**注意**  
必須為維護時段 Run Command 類型任務指定一或多個目標。視任務而定，其他維護時段任務類型 （自動化 AWS Lambda和 AWS Step Functions) 的目標為選用。如需有關執行未指定目標之任務的詳細資訊，請參閱 [註冊不含目標的維護時段任務](maintenance-windows-targetless-tasks.md)。

**支援 EventBridge**  
此 Systems Manager 工具作為 Amazon EventBridge 規則中的*事件*類型受到支援。如需詳細資訊，請參閱 [使用 Amazon EventBridge 監控 Systems Manager](monitoring-eventbridge-events.md) 及 [參考：Systems Manager 的 Amazon EventBridge 事件模式和類型](reference-eventbridge-events.md)。

**Topics**
+ [設定 Maintenance Windows](setting-up-maintenance-windows.md)
+ [使用主控台建立和管理維護時段](sysman-maintenance-working.md)
+ [教學課程](maintenance-windows-tutorials.md)
+ [註冊維護時段任務時使用虛擬參數](maintenance-window-tasks-pseudo-parameters.md)
+ [維護時段排程與作用期間選項](maintenance-windows-schedule-options.md)
+ [註冊不含目標的維護時段任務](maintenance-windows-targetless-tasks.md)
+ [對維護時段進行故障診斷](troubleshooting-maintenance-windows.md)

# 設定 Maintenance Windows
<a name="setting-up-maintenance-windows"></a>

您 AWS 帳戶中的使用者必須先取得必要的許可，才能使用 Maintenance Windows (AWS Systems Manager 中的工具) 來建立和排程維護時段任務。此外，您必須建立維護時段的 IAM 服務角色，以及要附加至其中的 IAM 政策。

**開始之前**  
除了在本節中設定的許可，IAM 實體 (將與維護時段搭配使用的使用者、角色或群組) 也應具有了一般維護時段許可。您可以透過將 IAM 政策 `AmazonSSMFullAccess` 指派給實體來授予這些許可，或透過指派自訂 IAM 政策來授予這些許可，而自訂政策能為 Systems Manager 提供較小存取許可集 (許可應涵蓋維護時段任務)。

**Topics**
+ [使用主控台控制對維護時段的存取權](configuring-maintenance-window-permissions-console.md)
+ [使用 控制維護時段的存取 AWS CLI](configuring-maintenance-window-permissions-cli.md)

# 使用主控台控制對維護時段的存取權
<a name="configuring-maintenance-window-permissions-console"></a>

下列程序說明如何使用 AWS Systems Manager 主控台建立維護時段所需的許可和角色。

**Topics**
+ [任務 1：使用主控台為維護時段服務角色建立自訂政策](#create-custom-policy-console)
+ [任務 2：使用主控台為維護時段建立自訂服務角色](#create-custom-role-console)
+ [任務 3：使用主控台向指定使用者授予註冊維護時段任務的許可](#allow-maintenance-window-access-console)
+ [任務 4：使用主控台防止指定的使用者註冊維護時段任務](#deny-maintenance-window-access-console)

## 任務 1：使用主控台為維護時段服務角色建立自訂政策
<a name="create-custom-policy-console"></a>

維護時段任務需要 IAM 角色提供在目標資源上執行所需的許可。許可透過連接到角色的 IAM 政策提供。您執行的任務類型及其他的操作要求決定了此政策的內容。我們提供您可以根據需求調整的基本政策。根據維護時段執行的任務及任務類型，您可能不需要此政策中的所有許可，而您可能需要包含其他的許可。您可以將此政策附加至稍後在 [任務 2：使用主控台為維護時段建立自訂服務角色](#create-custom-role-console) 建立的角色。

**使用主控台建立自訂政策**

1. 在 [https://console.aws.amazon.com/iam/](https://console.aws.amazon.com/iam/) 中開啟 IAM 主控台。

1. 在導覽窗格中，選擇 **Policies (政策)**，然後選擇 **Create policy (建立政策)**。

1. 在**政策編輯器**區段中，選擇 **JSON**。

1. 將預設內容取代為以下內容：

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

****  

   ```
   {
       "Version":"2012-10-17",		 	 	 
       "Statement": [
           {
               "Effect": "Allow",
               "Action": [
                   "ssm:SendCommand",
                   "ssm:CancelCommand",
                   "ssm:ListCommands",
                   "ssm:ListCommandInvocations",
                   "ssm:GetCommandInvocation",
                   "ssm:GetAutomationExecution",
                   "ssm:StartAutomationExecution",
                   "ssm:ListTagsForResource",
                   "ssm:DescribeInstanceInformation",
                   "ssm:GetParameters"
               ],
               "Resource": "*"
           },
           {
               "Effect": "Allow",
               "Action": [
                   "states:DescribeExecution",
                   "states:StartExecution"
               ],
               "Resource": [
                   "arn:aws:states:*:*:execution:*:*",
                   "arn:aws:states:*:*:stateMachine:*"
               ]
           },
           {
               "Effect": "Allow",
               "Action": [
                   "lambda:InvokeFunction"
               ],
               "Resource": [
                   "arn:aws:lambda:*:*:function:*"
               ]
           },
           {
               "Effect": "Allow",
               "Action": [
                   "resource-groups:ListGroups",
                   "resource-groups:ListGroupResources"
               ],
               "Resource": [
                   "*"
               ]
           },
           {
               "Effect": "Allow",
               "Action": [
                   "tag:GetResources"
               ],
               "Resource": [
                   "*"
               ]
           },
           {
               "Effect": "Allow",
               "Action": "iam:PassRole",
               "Resource": "arn:aws:iam::111122223333:role/maintenance-window-role-name",
               "Condition": {
                   "StringEquals": {
                       "iam:PassedToService": [
                           "ssm.amazonaws.com"
                       ]
                   }
               }
           }
       ]
   }
   ```

------

1. 根據您在帳户中執行的維護任務及其需要來修改 JSON 內容。您所做的變更專為您的操作而規劃。

   例如：
   + 您可以為特定功能及狀態機器提供 Amazon Resource Names (ARNs)，而不是使用萬用字圓 (\$1) 限定詞。
   + 如果您不打算執行 AWS Step Functions 任務，您可以移除`states`許可 和 ARNs)。
   + 如果您不打算執行 AWS Lambda 任務，您可以移除`lambda`許可和 ARNs。
   + 如果您不打算執行自動化任務，您可以移除 `ssm:GetAutomationExecution` 及 `ssm:StartAutomationExecution` 許可。
   + 新增執行任務可能需要的其他許可。例如，有些自動化動作搭配 AWS CloudFormation 堆疊運作。因此，`cloudformation:CreateStack`、`cloudformation:DescribeStacks` 以及 `cloudformation:DeleteStack` 許可是必要的。

     另一個例子：Automation Runbook `AWS-CopySnapshot` 需建立 Amazon Elastic Block Store (Amazon EBS) 快照的權限。因此，服務角色需要 `ec2:CreateSnapshot` 許可。

     如需有關 Automation 執行手冊所需的角色權限的資訊，請參閱 [AWS Systems Manager Automation Runbook Reference](https://docs.aws.amazon.com/systems-manager-automation-runbooks/latest/userguide/automation-runbook-reference.html) 中的執行手冊描述。

1. 完成政策修訂後，選擇**下一步**。

1. 在**政策名稱**中輸入名稱，該名稱將政策標識為連接至所建立之服務角色的政策。例如：**my-maintenance-window-role-policy**。

1. (選用) 在**新增標籤**區段中，新增一個或多個標籤鍵值對來組織、追蹤或控制對此政策的存取。

1. 選擇**建立政策**。

   記下為政策指定的名稱。您可以在接下來的程序 [任務 2：使用主控台為維護時段建立自訂服務角色](#create-custom-role-console) 加以引用。

## 任務 2：使用主控台為維護時段建立自訂服務角色
<a name="create-custom-role-console"></a>

在先前任務中建立的政策會連接至您在此任務中建立的維護時段服務角色。使用者註冊維護時段任務時，他們將此 IAM 角色指定為任務組態的一部分。此角色的權限可讓 Systems Manager 代您在維護時段執行任務。

**重要**  
先前，Systems Manager 主控台可讓您選擇要`AWSServiceRoleForAmazonSSM`用作任務維護角色的 AWS 受管 IAM 服務連結角色。不再建議將此角色及其關聯政策 `AmazonSSMServiceRolePolicy`，用於維護時段任務。如果您現在將此角色用於維護時段任務，我們建議您停止使用。相反地，請建立您自己的 IAM 角色，以便在維護時段任務執行 AWS 服務 時啟用 Systems Manager 與其他 之間的通訊。

請使用下列步驟來為 Maintenance Windows 建立自訂服務角色，讓 Systems Manager 能代表您執行 Maintenance Windows 任務。您需要將在前一任務中建立的政策連接至所建立的自訂服務角色。

**使用主控台為維護時段建立自訂服務角色**

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

1. 在導覽窗格中，選擇**角色**，然後選擇**建立角色**。

1. 對於 **Select trusted entity** (選擇信任的實體)，請執行以下選項：

   1. 針對**信任的實體類型**，請選擇 **AWS 服務**。

   1. 對於**使用案例**，選擇 **Systems Manager**

   1. 選擇 **Systems Manager**。

      下圖反白顯示了 Systems Manager 選項的位置。  
![\[Systems Manager 是使用案例的選項之一。\]](http://docs.aws.amazon.com/zh_tw/systems-manager/latest/userguide/images/iam_use_cases_for_MWs.png)

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

1. 在**許可政策**區域的搜尋方塊中，輸入在 [任務 1：使用主控台為維護時段服務角色建立自訂政策](#create-custom-policy-console) 中建立的政策名稱，選取其名稱旁邊的方塊，然後選擇**下一步**。

1. 在 **Role name** (角色名稱) 中，輸入識別此角色為 Maintenance Windows 角色的名稱。例如：**my-maintenance-window-role**。

1. (選用) 變更預設的角色描述以反映此角色的用途。例如：**Performs maintenance window tasks on your behalf**。

1. 對於**步驟 1：選取信任的實體**，確認下列政策顯示在**信任的政策**方塊中。

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

****  

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

------

1. 對於**步驟 2：新增許可**，確認您在 [任務 1：使用主控台為維護時段服務角色建立自訂政策](#create-custom-policy-console) 中建立的政策存在。

1. (選用) 在**步驟 3：新增標籤**中，新增一個或多個標籤鍵值對來組織、追蹤或控制對此角色的存取。

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

1. 選擇剛建立之 IAM 角色的名稱。

1. 複製或記下角色名稱及**摘要**區的 **ARN** 值。您帳户的使用者在建立維護時段時指定此訊息。

## 任務 3：使用主控台向指定使用者授予註冊維護時段任務的許可
<a name="allow-maintenance-window-access-console"></a>

為使用者提供存取維護時段自訂服務角色的許可，可讓他們將其用於維護時段任務。這是對您已經授予他們將 Systems Manager API 命令用於 Maintenance Windows 工具的許可的補充。此 IAM 角色傳遞了執行維護時段任務所需的許可。因此，如果無法傳遞這些 IAM 許可，使用者就無法使用您的自訂服務角色向維護時段註冊任務。

在向維護時段註冊任務時，需要指定服務角色來執行實際的任務操作。這是服務代您執行任務時所擔任的角色。在此之前，若要註冊任務本身，請將 IAM `PassRole` 政策指派給 IAM 實體 (例如使用者或群組)。這樣便讓 IAM 實體可以指定執行任務時應使用的角色，而指定角色是向維護時段註冊這些任務的其中一步。如需相關資訊，請參閱《IAM 使用者指南》**中的 [Grant a user permissions to pass a role to an AWS 服務](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_use_passrole.html)。

**設定許可以允許使用者註冊維護時段任務**

如果 IAM 實體 (使用者、角色或群組) 設定為具有管理員許可，則該 IAM 使用者或角色可以存取維護時段。對於沒有管理員許可的 IAM 實體，管理員必須將以下許可授予給 IAM 實體。以下是在維護時段中註冊任務所需的最低許可：
+ `AmazonSSMFullAccess` 受管政策或提供相當許可的政策。
+ 以下是 `iam:PassRole` 和 `iam:ListRoles` 許可。

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

****  

  ```
  {
      "Version":"2012-10-17",		 	 	 
      "Statement": [
          {
              "Effect": "Allow",
              "Action": "iam:PassRole",
              "Resource": "arn:aws:iam::111122223333:role/my-maintenance-window-role"
          },
          {
              "Effect": "Allow",
              "Action": "iam:ListRoles",
              "Resource": "arn:aws:iam::111122223333:role/"
          },
          {
              "Effect": "Allow",
              "Action": "iam:ListRoles",
              "Resource": "arn:aws:iam::111122223333:role/aws-service-role/ssm.amazonaws.com/"
          }
      ]
  }
  ```

------

  *my-maintenance-window-role* 代表您先前建立之自訂維護時段服務角色的名稱。

  *account-id* 代表您的 AWS 帳戶 ID。新增此資源 `arn:aws:iam::account-id:role/` 的許可，可讓使用者在建立維護時段任務時，檢視主控台中的客戶角色，並從中選擇客戶角色。新增 `arn:aws:iam::account-id:role/aws-service-role/ssm.amazonaws.com/` 的許可，可讓使用者在建立維護時段任務時，在主控台中選擇 Systems Manager 服務連結的角色。

  若要提供存取權，請新增權限至您的使用者、群組或角色：
  + 中的使用者和群組 AWS IAM Identity Center：

    建立權限合集。請按照《*AWS IAM Identity Center 使用者指南*》中的[建立權限合集](https://docs.aws.amazon.com//singlesignon/latest/userguide/howtocreatepermissionset.html)說明進行操作。
  + 透過身分提供者在 IAM 中管理的使用者：

    建立聯合身分的角色。遵循《*IAM 使用者指南*》的[為第三方身分提供者 (聯合) 建立角色](https://docs.aws.amazon.com//IAM/latest/UserGuide/id_roles_create_for-idp.html)中的指示。
  + IAM 使用者：
    + 建立您的使用者可擔任的角色。請按照《*IAM 使用者指南*》的[為 IAM 使用者建立角色](https://docs.aws.amazon.com//IAM/latest/UserGuide/id_roles_create_for-user.html)中的指示。
    + (不建議) 將政策直接附加至使用者，或將使用者新增至使用者群組。請遵循《*IAM 使用者指南*》的[新增許可到使用者 (主控台)](https://docs.aws.amazon.com//IAM/latest/UserGuide/id_users_change-permissions.html#users_change_permissions-add-console) 中的指示。

**使用主控台為可以註冊維護時段任務的群組設定許可**

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

1. 在導覽窗格中，選擇 **User groups** (使用者群組)。

1. 在群組清單中，選取要為其指派 `iam:PassRole` 許可的群組的名稱，或先建立新的群組 (如有必要) 

1. 在 **Permissions** (許可) 索引標籤上，選擇 **Add permissions, Create inline policy** (新增許可、建立內嵌政策)。

1. 在**政策編輯器**區域中，選擇 **JSON** 並使用列內容取代方塊中的預設內容。

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

****  

   ```
   {
       "Version":"2012-10-17",		 	 	 
       "Statement": [
           {
               "Effect": "Allow",
               "Action": "iam:PassRole",
               "Resource": "arn:aws:iam::111122223333:role/my-maintenance-window-role"
           },
           {
               "Effect": "Allow",
               "Action": "iam:ListRoles",
               "Resource": "arn:aws:iam::111122223333:role/"
           },
           {
               "Effect": "Allow",
               "Action": "iam:ListRoles",
               "Resource": "arn:aws:iam::111122223333:role/aws-service-role/ssm.amazonaws.com/"
           }
       ]
   }
   ```

------

   *my-maintenance-window-role* 代表您先前建立之自訂維護時段角色的名稱。

   *account-id* 代表您的 AWS 帳戶 ID。新增此資源 `arn:aws:iam::account-id:role/` 的許可，可讓使用者在建立維護時段任務時，檢視主控台中的客戶角色，並從中選擇客戶角色。新增 `arn:aws:iam::account-id:role/aws-service-role/ssm.amazonaws.com/` 的許可，可讓使用者在建立維護時段任務時，在主控台中選擇 Systems Manager 服務連結的角色。

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

1. 在**檢閱並建立**頁面上，在**政策名稱**方塊中輸入名稱以識別此 `PassRole` 政策 (例如 **my-group-iam-passrole-policy**)，然後選擇**建立政策**。

## 任務 4：使用主控台防止指定的使用者註冊維護時段任務
<a name="deny-maintenance-window-access-console"></a>

您可以拒絕 AWS 帳戶 您不想向維護時段註冊任務之 中使用者的`ssm:RegisterTaskWithMaintenanceWindow`許可。這針對不應註冊維護時段任務的使用者提供了額外的保護層。

**使用主控台為無法註冊維護時段任務的群組設定許可**

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

1. 在導覽窗格中，選擇 **User groups** (使用者群組)。

1. 在群組清單中，選取要為其拒絕 `ssm:RegisterTaskWithMaintenanceWindow` 許可的群組名稱，或先建立新的群組 (如有必要)。

1. 在 **Permissions** (許可) 索引標籤上，選擇 **Add permissions, Create inline policy** (新增許可、建立內嵌政策)。

1. 在**政策編輯器**區域中，選擇 **JSON**，然後使用下列內容取代方塊中的預設內容。

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

****  

   ```
   {
       "Version":"2012-10-17",		 	 	 
       "Statement": [
           {
               "Effect": "Deny",
               "Action": "ssm:RegisterTaskWithMaintenanceWindow",
               "Resource": "*"
           }
       ]
   }
   ```

------

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

1. 在**檢閱和建立**頁面上，在**政策名稱**中輸入名稱以識別此政策 (例如 **my-groups-deny-mw-tasks-policy**)，然後選擇**建立政策**。

# 使用 控制維護時段的存取 AWS CLI
<a name="configuring-maintenance-window-permissions-cli"></a>

下列程序說明如何使用 AWS Command Line Interface (AWS CLI) 為 中的Maintenance Windows工具 建立所需的許可和角色 AWS Systems Manager。

**Topics**
+ [任務 1：建立 JSON 格式的信任政策和客戶管理政策檔案](#create-custom-policy-json-files-cli)
+ [任務 2：使用 建立和驗證維護時段的自訂服務角色 AWS CLI](#create-custom-role-cli)
+ [任務 3：授予指定使用者使用 註冊維護時段任務的許可 AWS CLI](#allow-maintenance-window-access-cli)
+ [任務 4：防止指定的使用者使用 註冊維護時段任務 AWS CLI](#deny-maintenance-window-access-cli)

## 任務 1：建立 JSON 格式的信任政策和客戶管理政策檔案
<a name="create-custom-policy-json-files-cli"></a>

維護時段任務需要 IAM 角色提供在目標資源上執行所需的許可。許可透過連接到角色的 IAM 政策提供。您執行的任務類型及其他的操作要求決定了此政策的內容。我們提供您可以根據需求調整的基本政策。根據維護時段執行的任務及任務類型，您可能不需要此政策中的所有許可，而您可能需要包含其他的許可。

在此任務中，您在一組 JSON 檔案中指定自訂維護時段角色所需的許可。您可以將此政策附加至稍後在 [任務 2：使用 建立和驗證維護時段的自訂服務角色 AWS CLI](#create-custom-role-cli) 建立的角色。

**建立信任政策和客戶管理政策檔案**

1. 將下列信任政策複製並貼入一個文字檔。使用以下名稱和副檔名儲存此檔案：**mw-role-trust-policy.json**。

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

****  

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

------

1. 複製下列 JSON 政策並將其貼到另一個文字檔案中。在您建立第一個檔案的相同目錄中，使用下列名稱和副檔名儲存此檔案：**mw-role-custom-policy.json**。

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

****  

   ```
   {
       "Version":"2012-10-17",		 	 	 
       "Statement": [
           {
               "Effect": "Allow",
               "Action": [
                   "ssm:SendCommand",
                   "ssm:CancelCommand",
                   "ssm:ListCommands",
                   "ssm:ListCommandInvocations",
                   "ssm:GetCommandInvocation",
                   "ssm:GetAutomationExecution",
                   "ssm:StartAutomationExecution",
                   "ssm:ListTagsForResource",
                   "ssm:GetParameters"
               ],
               "Resource": "*"
           },
           {
               "Effect": "Allow",
               "Action": [
                   "states:DescribeExecution",
                   "states:StartExecution"
               ],
               "Resource": [
                   "arn:aws:states:*:*:execution:*:*",
                   "arn:aws:states:*:*:stateMachine:*"
               ]
           },
           {
               "Effect": "Allow",
               "Action": [
                   "lambda:InvokeFunction"
               ],
               "Resource": [
                   "arn:aws:lambda:*:*:function:*"
               ]
           },
           {
               "Effect": "Allow",
               "Action": [
                   "resource-groups:ListGroups",
                   "resource-groups:ListGroupResources"
               ],
               "Resource": [
                   "*"
               ]
           },
           {
               "Effect": "Allow",
               "Action": [
                   "tag:GetResources"
               ],
               "Resource": [
                   "*"
               ]
           },
           {
               "Effect": "Allow",
               "Action": "iam:PassRole",
               "Resource": "arn:aws:iam::111122223333:role/maintenance-window-role-name",
               "Condition": {
                   "StringEquals": {
                       "iam:PassedToService": [
                           "ssm.amazonaws.com"
                       ]
                   }
               }
           }
       ]
   }
   ```

------

1. 根據您在帳户中執行的維護任務需求來修改 `mw-role-custom-policy.json` 的內容。您所做的變更專為您的操作而規劃。

   例如：
   + 您可以為特定功能及狀態機器提供 Amazon Resource Names (ARNs)，而不是使用萬用字圓 (\$1) 限定詞。
   + 如果您不打算執行 AWS Step Functions 任務，您可以移除`states`許可 和 (ARNs)。
   + 如果您不打算執行 AWS Lambda 任務，您可以移除`lambda`許可和 ARNs。
   + 如果您不打算執行自動化任務，您可以移除 `ssm:GetAutomationExecution` 及 `ssm:StartAutomationExecution` 許可。
   + 新增執行任務可能需要的其他許可。例如，有些自動化動作搭配 AWS CloudFormation 堆疊運作。因此，`cloudformation:CreateStack`、`cloudformation:DescribeStacks` 以及 `cloudformation:DeleteStack` 許可是必要的。

     另一個例子：Automation Runbook `AWS-CopySnapshot` 需建立 Amazon Elastic Block Store (Amazon EBS) 快照的權限。因此，服務角色需要 `ec2:CreateSnapshot` 許可。

     如需有關 Automation 執行手冊所需的角色權限的資訊，請參閱 [AWS Systems Manager Automation Runbook Reference](https://docs.aws.amazon.com/systems-manager-automation-runbooks/latest/userguide/automation-runbook-reference.html) 中的執行手冊描述。

   進行任何所需變更後，再次儲存檔案。

## 任務 2：使用 建立和驗證維護時段的自訂服務角色 AWS CLI
<a name="create-custom-role-cli"></a>

在先前任務中建立的政策會連接至您在此任務中建立的維護時段服務角色。使用者註冊維護時段任務時，他們將此 IAM 角色指定為任務組態的一部分。此角色的權限可讓 Systems Manager 代您在維護時段執行任務。

**重要**  
先前，Systems Manager 主控台可讓您選擇要`AWSServiceRoleForAmazonSSM`用作任務維護角色的 AWS 受管 IAM 服務連結角色。不再建議將此角色及其關聯政策 `AmazonSSMServiceRolePolicy`，用於維護時段任務。如果您現在將此角色用於維護時段任務，我們建議您停止使用。相反地，請建立您自己的 IAM 角色，以便在維護時段任務執行 AWS 服務 時啟用 Systems Manager 與其他 之間的通訊。

在此任務中，您需執行 CLI 命令來建立維護時段服務角色，並從您建立的 JSON 檔案新增政策內容。

**使用 建立維護時段的自訂服務角色 AWS CLI**

1. 開啟 AWS CLI ，並在您放置 `mw-role-custom-policy.json` 和 的目錄中執行下列命令`mw-role-trust-policy.json`。該命令會建立名為 `my-maintenance-window-role` 的維護時段服務角色，並將*信任政策*連接至該角色。

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

   ```
   aws iam create-role \
       --role-name "my-maintenance-window-role" \
       --assume-role-policy-document file://mw-role-trust-policy.json
   ```

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

   ```
   aws iam create-role ^
       --role-name "my-maintenance-window-role" ^
       --assume-role-policy-document file://mw-role-trust-policy.json
   ```

------

   系統會傳回與以下相似的資訊。

   ```
   {
       "Role": {
           "AssumeRolePolicyDocument": {
               "Version": "2012-10-17", 		 	 	 		 	 	 
               "Statement": [
                   {
                       "Action": "sts:AssumeRole",
                       "Effect": "Allow",
                       "Principal": {
                           "Service": "ssm.amazonaws.com"
                       }
                   }
               ]
           },
           "RoleId": "AROAIIZKPBKS2LEXAMPLE",
           "CreateDate": "2024-08-19T03:40:17.373Z",
           "RoleName": "my-maintenance-window-role",
           "Path": "/",
           "Arn": "arn:aws:iam::123456789012:role/my-maintenance-window-role"
       }
   }
   ```
**注意**  
記下 `RoleName` 與 `Arn` 值。它們可以包含在下一個命令中。

1. 執行下列命令，將*客戶管理政策*連接至該角色。使用自己的 AWS 帳戶 ID 取代 *account-id* 預留位置

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

   ```
   aws iam attach-role-policy \
       --role-name "my-maintenance-window-role" \
       --policy-arn "arn:aws:iam::account-id:policy/mw-role-custom-policy.json"
   ```

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

   ```
   aws iam attach-role-policy ^
       --role-name "my-maintenance-window-role" ^
       --policy-arn "arn:aws:iam::account-id:policy/mw-role-custom-policy.json"
   ```

------

1. 執行下列命令，確認角色已建立，並且已連接信任政策。

   ```
   aws iam get-role --role-name my-maintenance-window-role
   ```

   此命令會傳回與以下內容相似的資訊：

   ```
   {
       "Role": {
           "Path": "/",
           "RoleName": "my-maintenance-window-role",
           "RoleId": "AROA123456789EXAMPLE",
           "Arn": "arn:aws:iam::123456789012:role/my-maintenance-window-role",
           "CreateDate": "2024-08-19T14:13:32+00:00",
           "AssumeRolePolicyDocument": {
               "Version": "2012-10-17", 		 	 	 		 	 	 
               "Statement": [
                   {
                       "Effect": "Allow",
                       "Principal": {
                           "Service": "ssm.amazonaws.com"
                       },
                       "Action": "sts:AssumeRole"
                   }
               ]
           },
           "MaxSessionDuration": 3600,
           "RoleLastUsed": {
               "LastUsedDate": "2024-08-19T14:30:44+00:00",
               "Region": "us-east-2"
           }
       }
   }
   ```

1. 執行下列命令，確認客戶管理政策已連接至角色。

   ```
   aws iam list-attached-role-policies --role-name my-maintenance-window-role
   ```

   此命令會傳回與以下內容相似的資訊：

   ```
   {
       "AttachedPolicies": [
           {
               "PolicyName": "mw-role-custom-policy",
               "PolicyArn": "arn:aws:iam::123456789012:policy/mw-role-custom-policy"
           }
       ]
   }
   ```

## 任務 3：授予指定使用者使用 註冊維護時段任務的許可 AWS CLI
<a name="allow-maintenance-window-access-cli"></a>

為使用者提供存取維護時段自訂服務角色的許可，可讓他們將其用於維護時段任務。這是對您已經授予他們將 Systems Manager API 命令用於 Maintenance Windows 工具的許可的補充。此 IAM 角色傳遞了執行維護時段任務所需的許可。因此，如果無法傳遞這些 IAM 許可，使用者就無法使用您的自訂服務角色向維護時段註冊任務。

在向維護時段註冊任務時，需要指定服務角色來執行實際的任務操作。這是服務代您執行任務時所擔任的角色。在此之前，若要註冊任務本身，請將 IAM `PassRole` 政策指派給 IAM 實體 (例如使用者或群組)。這樣便讓 IAM 實體可以指定執行任務時應使用的角色，而指定角色是向維護時段註冊這些任務的其中一步。如需相關資訊，請參閱《IAM 使用者指南》**中的 [Grant a user permissions to pass a role to an AWS 服務](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_use_passrole.html)。

**為允許使用者使用 註冊維護時段任務的使用者設定許可 AWS CLI**

1. 將下列 AWS Identity and Access Management (IAM) 政策複製並貼到文字編輯器中，並使用下列名稱和副檔名儲存：`mw-passrole-policy.json`。

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

****  

   ```
   {
       "Version":"2012-10-17",		 	 	 
       "Statement": [
           {
               "Effect": "Allow",
               "Action": "iam:PassRole",
               "Resource": "arn:aws:iam::111122223333:role/my-maintenance-window-role"
           },
           {
               "Effect": "Allow",
               "Action": "iam:ListRoles",
               "Resource": "arn:aws:iam::111122223333:role/"
           },
           {
               "Effect": "Allow",
               "Action": "iam:ListRoles",
               "Resource": "arn:aws:iam::111122223333:role/aws-service-role/ssm.amazonaws.com/"
           }
       ]
   }
   ```

------

   使用您先前建立之自訂維護時段角色的名稱取代 *my-maintenance-window-role*。

   將 *account-id* 取代為 AWS 帳戶的 ID。新增此資源 `arn:aws:iam::account-id:role/` 的許可，可讓群組中的使用者在建立維護時段任務時，檢視主控台中的客戶角色，並從中選擇客戶角色。新增此 `arn:aws:iam::account-id:role/aws-service-role/ssm.amazonaws.com/` 許可，可讓群組中的使用者在建立維護時段任務時，在主控台中選擇 Systems Manager 服務連結的角色。

1. 開啟 AWS CLI。

1. 根據您是否將許可指派給 IAM 實體 (使用者或群組)，執行下列其中一個命令。
   + **對於 IAM 實體：**

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

     ```
     aws iam put-user-policy \
         --user-name "user-name" \
         --policy-name "policy-name" \
         --policy-document file://path-to-document
     ```

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

     ```
     aws iam put-user-policy ^
         --user-name "user-name" ^
         --policy-name "policy-name" ^
         --policy-document file://path-to-document
     ```

------

     對於 *user-name*，指定要將任務指派給維護時段的使用者。對於 *policy-name*，指定您要用於識別該政策的名稱，例如 **my-iam-passrole-policy**。對於 *path-to-document*，指定您儲存在步驟 1 的檔案路徑。例如：`file://C:\Temp\mw-passrole-policy.json`
**注意**  
若要授予使用者使用 Systems Manager 主控台為維護時段註冊任務的存取權，您還必須將 `AmazonSSMFullAccess` 政策指派給使用者 (或 IAM 政策，該政策為涵蓋維護時段任務的 Systems Manager 提供較小的存取許可集)。執行以下命令，將 `AmazonSSMFullAccess` 政策指派給使用者。  

     ```
     aws iam attach-user-policy \
         --policy-arn "arn:aws:iam::aws:policy/AmazonSSMFullAccess" \
         --user-name "user-name"
     ```

     ```
     aws iam attach-user-policy ^
         --policy-arn "arn:aws:iam::aws:policy/AmazonSSMFullAccess" ^
         --user-name "user-name"
     ```
   + **對於 IAM 群組：**

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

     ```
     aws iam put-group-policy \
         --group-name "group-name" \
         --policy-name "policy-name" \
         --policy-document file://path-to-document
     ```

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

     ```
     aws iam put-group-policy ^
         --group-name "group-name" ^
         --policy-name "policy-name" ^
         --policy-document file://path-to-document
     ```

------

     對於 *group-name*，指定其成員會將任務指派給維護時段的群組。對於 *policy-name*，指定您要用於識別該政策的名稱，例如 **my-iam-passrole-policy**。對於 *path-to-document*，指定您儲存在步驟 1 的檔案路徑。例如：`file://C:\Temp\mw-passrole-policy.json`
**注意**  
若要授與群組成員使用 Systems Manager 主控台為維護時段註冊任務的存取權限，您還必須將 `AmazonSSMFullAccess` 政策指派給群組。執行以下命令，將此政策指派到您的群組。  

     ```
     aws iam attach-group-policy \
         --policy-arn "arn:aws:iam::aws:policy/AmazonSSMFullAccess" \
         --group-name "group-name"
     ```

     ```
     aws iam attach-group-policy ^
         --policy-arn "arn:aws:iam::aws:policy/AmazonSSMFullAccess" ^
         --group-name "group-name"
     ```

1. 執行以下命令，確認已經將政策指派到群組。

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

   ```
   aws iam list-group-policies \
       --group-name "group-name"
   ```

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

   ```
   aws iam list-group-policies ^
       --group-name "group-name"
   ```

------

## 任務 4：防止指定的使用者使用 註冊維護時段任務 AWS CLI
<a name="deny-maintenance-window-access-cli"></a>

您可以拒絕 AWS 帳戶 您不想向維護時段註冊任務之 中使用者的`ssm:RegisterTaskWithMaintenanceWindow`許可。這針對不應註冊維護時段任務的使用者提供了額外的保護層。

無論您是根據個別使用者還是群組來拒絕 `ssm:RegisterTaskWithMaintenanceWindow` 許可，請使用下列其中一個處理程序，來阻止使用者向維護時段註冊任務。

**為不允許使用 註冊維護時段任務的使用者設定許可 AWS CLI**

1. 下列 IAM 政策複製並貼到文字編輯器，並以下名稱和副檔名儲存：**deny-mw-tasks-policy.json**。

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

****  

   ```
   {
       "Version":"2012-10-17",		 	 	 
       "Statement": [
           {
               "Effect": "Deny",
               "Action": "ssm:RegisterTaskWithMaintenanceWindow",
               "Resource": "*"
           }
       ]
   }
   ```

------

1. 開啟 AWS CLI。

1. 根據您是否將許可指派給 IAM 實體 (使用者或群組)，執行下列其中一個命令。
   + **對於使用者：**

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

     ```
     aws iam put-user-policy \
         --user-name "user-name" \
         --policy-name "policy-name" \
         --policy-document file://path-to-document
     ```

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

     ```
     aws iam put-user-policy ^
         --user-name "user-name" ^
         --policy-name "policy-name" ^
         --policy-document file://path-to-document
     ```

------

     對於 *user-name*，指定要防止其將任務指派給維護時段的使用者。對於 *policy-name*，指定您要用於識別該政策的名稱，例如 **my-deny-mw-tasks-policy**。對於 *path-to-document*，指定您儲存在步驟 1 的檔案路徑。例如：`file://C:\Temp\deny-mw-tasks-policy.json`
   + **對於群組：**

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

     ```
     aws iam put-group-policy \
         --group-name "group-name" \
         --policy-name "policy-name" \
         --policy-document file://path-to-document
     ```

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

     ```
     aws iam put-group-policy ^
         --group-name "group-name" ^
         --policy-name "policy-name" ^
         --policy-document file://path-to-document
     ```

------

     對於 *group-name*，指定要防止其成員將任務指派給維護時段的群組。對於 *policy-name*，指定您要用於識別該政策的名稱，例如 **my-deny-mw-tasks-policy**。對於 *path-to-document*，指定您儲存在步驟 1 的檔案路徑。例如：`file://C:\Temp\deny-mw-tasks-policy.json`

1. 執行以下命令，確認已經將政策指派到群組。

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

   ```
   aws iam list-group-policies \
       --group-name "group-name"
   ```

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

   ```
   aws iam list-group-policies ^
       --group-name "group-name"
   ```

------

# 使用主控台建立和管理維護時段
<a name="sysman-maintenance-working"></a>

本節說明如何使用 AWS Systems Manager 主控台建立、設定、更新和刪除維護時段。本節也提供管理維護時段的目標和任務的資訊。

**重要**  
我們建議您一開始先在測試環境中建立和設定維護時段。

**開始之前**  
在建立維護時段之前，您必須設定對 的存取權Maintenance Windows，這是 中的工具 AWS Systems Manager。如需詳細資訊，請參閱[設定 Maintenance Windows](setting-up-maintenance-windows.md)。

**Topics**
+ [使用主控台建立維護時段](sysman-maintenance-create-mw.md)
+ [使用主控台將目標指派至維護時段](sysman-maintenance-assign-targets.md)
+ [使用主控台將任務指派至維護時段](sysman-maintenance-assign-tasks.md)
+ [使用主控台停用或啟用維護時段](sysman-maintenance-disable.md)
+ [使用主控台更新或刪除維護時段資源](sysman-maintenance-update.md)

# 使用主控台建立維護時段
<a name="sysman-maintenance-create-mw"></a>

在此程序中，您會在 Maintenance Windows ( AWS Systems Manager中的工具) 中建立維護時段。您可以指定其基本選項，例如名稱、排程和持續時間。在後續步驟中，您可以選擇要更新的目標或資源，以及在維護時段執行時執行的任務。

**注意**  
如需維護時段的各種排程相關選項彼此之間有何關聯的說明，請參閱 [維護時段排程與作用期間選項](maintenance-windows-schedule-options.md)。  
如需使用 `--schedule` 選項的詳細資訊，請參閱[參考：Systems Manager 的 Cron 和 Rate 運算式](reference-cron-and-rate-expressions.md)。

**使用主控台建立維護時段**

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

1. 在導覽窗格中，選擇 **Maintenance Windows**。

1. 選擇**建立維護時段**。

1. 對於 **Name** (名稱)，輸入描述名稱，以協助您識別此維護時段。

1. (選用) 在 **Description** (描述) 中，輸入描述來確定如何使用此維護時段。

1. (選用) 如果您想允許維護時段任務在受管節點上執行 (即使尚未將這些節點註冊為目標)，請選擇 **Allow unregistered targets** (允許未註冊的目標)。

   如果您選擇此選項，即可在向維護時段註冊任務時選擇未註冊的節點 (依據節點 ID)。

   如果您未選擇此選項，則必須在向維護時段註冊任務時選擇先前註冊過的目標。

1. 使用三個排程選項的其中一個，來為維護時段指定排程。

   如需有關建立 Cron/Rate 運算式的詳細資訊，請參閱[參考：Systems Manager 的 Cron 和 Rate 運算式](reference-cron-and-rate-expressions.md)。

1. 針對 **Duration (持續時間)**，輸入維護時段將執行的時數。您指定的值會根據維護時段的開始時間，決定維護時段的特定結束時間。在產生的結束時間減去您在下一個步驟中為 **Stop initiating tasks (停止啟動任務)** 指定的小時數過後，將不允許啟動任何維護時段任務。

   例如，如果維護時段從下午 3 點開始，持續時間為三小時，而 **Stop initiating tasks (停止啟動任務)** 的值為一小時，則在下午 5 點之後無法啟動任何維護時段任務。

1. 針對 **Stop initiating tasks (停止初始任務)**，輸入在維護時段執行結束之前，系統應該停止排程新任務的時數。

1. (選用) 對於 **Window start date** (時段開始日期)，依照 ISO-8601 Extended 格式，指定您希望開始啟用維護時段的日期和時間。這可讓您延遲啟用維護時段，直到指定的未來日期為止。
**注意**  
您無法指定過去的開始日期和時間。

1. (選用) 對於 **Window end date** (時段結束日期)，依照 ISO-8601 Extended 格式，指定您希望停用維護時段的日期和時間。這可讓您設定不再執行維護時段的未來日期和時間點。

1. (選用) 對於**排程時區**，依照網際網路號碼分配局 (IANA) 格式，指定排程的維護時段執行時所依據的時區。例如："America/Los\$1Angeles"、"etc/UTC" 或 "Asia/Seoul"。

   如需有關有效格式的詳細資訊，請參閱 IANA 網站上的[時區資料庫有效格式](https://www.iana.org/time-zones)。

1. (選用) 對於 **Schedule offset** (排程偏移)，請輸入在執行維護時段之前，在 Cron 或 Rate 表達式所指定的日期和時間之後等待的天數。您可以指定一至六天。
**注意**  
僅當您透過手動輸入 Cron 或 Rate 表達式指定排程時，此選項才可用。

1. (選用) 在 **Manage tags (管理標籤)** 區域，將一或多個標籤金鑰名稱/值對套用到維護時段。

   標籤是您指派給資源的選用性中繼資料。標籤允許您以不同的方式 (例如用途、擁有者或環境) 將資源分類。例如，您可能想要標記維護時段來識別其執行的任務類型、目標類型以及其執行所在的環境。在這種情況下，您可以指定以下索引鍵名稱/值對：
   + `Key=TaskType,Value=AgentUpdate`
   + `Key=OS,Value=Windows`
   + `Key=Environment,Value=Production`

1. 選擇**建立維護時段**。系統會帶您回到維護時段頁面。您剛建立的維護時段為 **Enabled (已啟用)** 狀態。

# 使用主控台將目標指派至維護時段
<a name="sysman-maintenance-assign-targets"></a>

在此程序中，您會向維護時段註冊目標。換言之，您會指定維護時段要對哪些資源執行動作。

**注意**  
如果單一維護時段任務已向多個目標註冊，則其任務叫用會依序發生，而非平行發生。如果您的任務必須同時在多個目標上執行，請個別註冊每個目標的任務，並為每個任務指派相同的優先順序層級。

**使用主控台將目標指派至維護時段**

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

1. 在導覽窗格中，選擇 **Maintenance Windows**。

1. 在維護時段清單中，選擇您要新增目標的維護時段。

1. 選擇 **Actions (動作)**，然後選擇 **Register targets (註冊目標)**。

1. (選用) 在 **Target Name (目標名稱)** 中，輸入目標的名稱。

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

1. (選用) 對於 **Owner information** (擁有者資訊)，指定要在此維護時段為這些目標執行任務時引發的任何 Amazon EventBridge 事件中包含的資訊。

   如需使用 EventBridge 監控 Systems Manager 事件的相關資訊，請參閱 [使用 Amazon EventBridge 監控 Systems Manager](monitoring-eventbridge-events.md)。

1. 在 **Targets (目標)** 區域，選擇下表中所述的其中一個選項。    
[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/systems-manager/latest/userguide/sysman-maintenance-assign-targets.html)

1. 選擇 **Register target (註冊目標)**。

如果您想要將多個目標指派到這個維護時段，選擇 **Targets (目標)** 標籤，然後選擇 **Register target (註冊目標)**。使用此選項，您可以選擇不同設定目標的方法。例如，如果您之前透過節點 ID 來將節點作為目標，您可以透過指定受管節點中套用的標籤，或從資源群組中選擇資源類型來註冊新目標並將節點作為目標。

# 使用主控台將任務指派至維護時段
<a name="sysman-maintenance-assign-tasks"></a>

在此程序中，您會將任務新增到維護時段。任務是在維護時段執行時所執行的動作。

您可將下列四種類型的任務新增到維護時段：
+ AWS Systems Manager Run Command 命令
+ Systems Manager Automation 工作流程
+ AWS Step Functions 任務
+ AWS Lambda 函數
**重要**  
適用於 Maintenance Windows 的 IAM 政策需要您為 Lambda 函數 (或別名) 名稱新增 `SSM` 字首。在您繼續註冊此類任務之前，請在 中更新其名稱 AWS Lambda 以包含 `SSM`。例如，如果 Lambda 函數名稱為 `MyLambdaFunction`，請變更為 `SSMMyLambdaFunction`。

**指派任務至維護時段**

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

1. 在導覽窗格中，選擇 **Maintenance Windows**。

1. 在維護時段清單中，選擇維護時段。

1. 選擇 **Actions** (動作)，然後選擇您想要向維護時段註冊的任務類型選項：
   + **Register Run command task (註冊執行命令任務)**
   + **Register Automation task (註冊自動化任務)**
   + **Register Lambda task (註冊 Lambda 任務)**
   + **Register Step Functions task (註冊步驟函數任務)**
**注意**  
維護時段任務僅支援 Step Functions 標準狀態機器工作流程。這些任務不支援快速狀態機器工作流程。如需有關狀態機器工作流程類型的資訊，請參閱《AWS Step Functions 開發人員指南》**中的[標準與快速工作流程](https://docs.aws.amazon.com/step-functions/latest/dg/concepts-standard-vs-express.html)。

1. (選用) 對於 **Name** (名稱)，請輸入任務的名稱。

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

1. 對於 **New task invocation cutoff** (新任務叫用截止)，如果您不想在到達維護時段截止時間後啟動任何新的任務叫用，則請選擇 **Enabled** (已啟用)。

   當此選項*未*啟用時，任務會在到達截止時間後繼續執行，並啟動新的任務叫用，直到完成為止。
**注意**  
當您啟用此選項時，未完成的任務狀態為 `TIMED_OUT`。

1. 在此步驟中，選擇所選任務類型的索引標籤。

------
#### [ Run Command ]

   1. 在 **Command 文件**清單中，選擇定義要執行任務的 Systems Manager Command 文件 (SSM 文件)。

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

   1. 對於 **Task priority (任務優先順序)**，請指定此任務的優先順序。零 (`0`) 是最高的優先順序。維護時段內的任務都是以優先順序來排程；相同優先順序的任務會平行排程。

------
#### [ Automation ]

   1.  在 **Automation 文件**清單中，選擇定義要執行任務的 Automation 執行手冊。

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

   1. 對於 **Task priority (任務優先順序)**，請指定此任務的優先順序。零 (`0`) 是最高的優先順序。維護時段內的任務都是以優先順序來排程；相同優先順序的任務會平行排程。

------
#### [ Lambda ]

   1. 在 **Lambda 參數**區域中，從清單中選擇 Lambda 函數。

   1. (選用) 提供您想包含之 **Payload** (承載)、**Client Context** (用戶端內容) 或 **Qualifier** (限定詞) 的任何內容。
**注意**  
在某些情況下，您可以使用*虛擬參數*作為 `Payload` 值的一部分。維護時段任務執行時，其會傳遞正確的值 (而不是虛擬參數預留位置)。如需相關資訊，請參閱[註冊維護時段任務時使用虛擬參數](maintenance-window-tasks-pseudo-parameters.md)。

   1. 對於 **Task priority (任務優先順序)**，請指定此任務的優先順序。零 (`0`) 是最高的優先順序。維護時段內的任務都是以優先順序來排程；相同優先順序的任務會平行排程。

------
#### [ Step Functions ]

   1. 在 **Step Functions 參數**區域中，從清單中選擇狀態機器。

   1. (選用) 提供狀態機器執行的名稱以及您想包含之 **Input** (輸入) 的任何內容。
**注意**  
在某些情況下，您可以使用*虛擬參數*作為 `Input` 值的一部分。維護時段任務執行時，其會傳遞正確的值 (而不是虛擬參數預留位置)。如需相關資訊，請參閱[註冊維護時段任務時使用虛擬參數](maintenance-window-tasks-pseudo-parameters.md)。

   1. 對於 **Task priority (任務優先順序)**，請指定此任務的優先順序。零 (`0`) 是最高的優先順序。維護時段內的任務都是以優先順序來排程；相同優先順序的任務會平行排程。

------

1. 在 **Targets** (目標) 區域中，選擇以下其中一項：
   + **Selecting registered target groups** (選取已註冊的目標群組)：選取您已在目前維護時段註冊的一或多個維護時段目標。
   + **Selecting unregistered targets** (選取未註冊的目標)：逐一選擇可用的資源作為任務的目標。

     如果您預期看到的受管節點未列出，請參閱 [疑難排解受管節點的可用性](fleet-manager-troubleshooting-managed-nodes.md) 以取得疑難排解秘訣。
   + **Task target not required** (不需要任務目標)：任務的目標可能已經針對除 Run Command 類型以外的所有任務在其他函數中指定。

     為維護時段 Run Command 類型任務指定一或多個目標。視任務而定，其他維護時段任務類型 （自動化 AWS Lambda和 AWS Step Functions) 的目標為選用。如需有關執行未指定目標之任務的詳細資訊，請參閱 [註冊不含目標的維護時段任務](maintenance-windows-targetless-tasks.md)。
**注意**  
在許多情況下，您不需要明確指定自動化任務的目標。例如，假設您正在建立 Automation 類型任務來使用 `AWS-UpdateLinuxAmi` Runbook 更新 Linux 的 Amazon Machine Image (AMI)。當任務執行時，AMI 已更新為可用的最新版本 Linux 發行版本套件和 Amazon 軟體。從 AMI 建立的新執行個體已經安裝這些更新。因為在 Runbook 的輸入參數中指定了要更新的 AMI ID，所以不需要在維護時段任務中再次指定目標。

1. *僅限 Automation 任務：*

   在 **Input parameters** (輸入參數) 區域中，為執行任務所需的任何必要或選用參數提供值。
**注意**  
在某些情況下，您可以針對特定輸入參數值使用*虛擬參數*。維護時段任務執行時，其會傳遞正確的值 (而不是虛擬參數預留位置)。如需相關資訊，請參閱[註冊維護時段任務時使用虛擬參數](maintenance-window-tasks-pseudo-parameters.md)。

1. 對於**速率控制**：
   + 在**並行**中，指定可同時執行命令的受管節點數目或百分比。
**注意**  
如果您透過指定套用至受管節點的標籤或指定 AWS 資源群組來選取目標，而且不確定目標的受管節點數量，則透過指定百分比來限制可同時執行文件的目標數量。
   + 在 **Error threshold** (錯誤閾值) 中，指定在特定數目或百分比之節點上的命令失敗之後，停止在其他受管節點上執行命令。例如，如果您指定三個錯誤，則 Systems Manager 會在收到第四個錯誤時停止傳送命令。仍在處理命令的受管節點也可能會傳送錯誤。

1. (選用) 對於 **IAM 服務角色**，請選擇一個角色，以便為 Systems Manager 提供執行維護時段任務時承擔的許可。

   如果您未指定服務角色 ARN，則 Systems Manager 會使用帳戶中的服務連結角色。此角色未列在下拉式功能表中。如果帳戶中不存在適當的 Systems Manager 服務連結角色，則會在成功註冊任務時建立該角色。
**注意**  
為了改善安全狀態，強烈建議您建立自訂政策和自訂服務角色，以便執行維護時段任務。您可以制定政策，僅提供特定維護時段任務所需的許可。如需詳細資訊，請參閱[設定 Maintenance Windows](setting-up-maintenance-windows.md)。

1. *僅限 Run Command 任務：*

   (選用) 對於 **Output options** (輸出選項)，執行下列動作：
   + 選取 **Enable writing to S3** (啟用寫入 S3) 核取方塊，將命令輸出儲存成檔案。在方塊中輸入儲存貯體和字首 (資料夾) 名稱。
   + 選取 **CloudWatch output** (CloudWatch 輸出) 核取方塊，將完整的輸出寫入 Amazon CloudWatch Logs。輸入 CloudWatch Logs 日誌群組的名稱。
**注意**  
授予能力以將資料寫入至 S3 儲存貯體或 CloudWatch Logs 的許可，是指派給節點的執行個體設定檔的許可 (而不是執行此任務的 IAM 使用者的許可)。如需詳細資訊，請參閱[設定 Systems Manager 所需的執行個體許可](setup-instance-permissions.md)。此外，如果指定的 S3 儲存貯體或日誌群組位於不同的 中 AWS 帳戶，請確認與節點相關聯的執行個體描述檔具有寫入該儲存貯體的必要許可。

1. *僅限 Run Command 任務：*

   在**SNS 通知**區段中，如果您要傳送有關命令執行狀態的通知，請選取**啟用 SNS 通知**核取方塊。

   如需為 Run Command 設定 Amazon SNS 通知的詳細資訊，請參閱 [使用 Amazon SNS 通知監控 Systems Manager 狀態變更](monitoring-sns-notifications.md)。

1. *僅限 Run Command 任務：*

   在 **Parameters** (參數) 區域中，指定文件的參數。
**注意**  
在某些情況下，您可以針對特定輸入參數值使用*虛擬參數*。維護時段任務執行時，其會傳遞正確的值 (而不是虛擬參數預留位置)。如需相關資訊，請參閱[註冊維護時段任務時使用虛擬參數](maintenance-window-tasks-pseudo-parameters.md)。

1. *僅限 Run Command 和 Automation 任務：*

   (選用) 在 **CloudWatch 警示**區域中，在**警示名稱**欄位中選擇要套用至任務來進行監控的 CloudWatch 警示。

   如果警示啟用，則會停止任務。
**注意**  
若要將 CloudWatch 警示附加至您的任務，執行任務的 IAM 主體必須具備 `iam:createServiceLinkedRole` 動作的許可。如需有關 CloudWatch 警示的詳細資訊，請參閱[使用 Amazon CloudWatch 警示](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/AlarmThatSendsEmail.html)。

1. 根據任務類型，選擇下列其中一項：
   + **Register Run command task (註冊執行命令任務)**
   + **Register Automation task (註冊自動化任務)**
   + **Register Lambda task (註冊 Lambda 任務)**
   + **Register Step Functions task (註冊步驟函數任務)**

# 使用主控台停用或啟用維護時段
<a name="sysman-maintenance-disable"></a>

您可以在 Maintenance Windows ( AWS Systems Manager中的工具) 中停用或啟用維護時段。您可以一次選擇一個維護時段，以停用或啟用維護時段。您也可以選取多個或所有維護時段以全部啟用或停用。

本節說明如何使用 Systems Manager 主控台來啟用或停用維護時段。如需如何使用 AWS Command Line Interface (AWS CLI) 執行此操作的範例，請參閱 [教學課程：使用 更新維護時段 AWS CLI](maintenance-windows-cli-tutorials-update.md)。

**Topics**
+ [使用主控台停用維護時段](#sysman-maintenance-disable-mw)
+ [使用主控台啟用維護時段](#sysman-maintenance-enable-mw)

## 使用主控台停用維護時段
<a name="sysman-maintenance-disable-mw"></a>

您可以透過停用維護時段暫停一項任務一段指定的期間，而且您在之後仍然可以再次啟用此維護時段。

**停用維護時段**

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

1. 在導覽窗格中，選擇 **Maintenance Windows**。

1. 使用您要停用之維護時段旁邊的核取方塊；您可以為一或多個維護時段這麼做。

1. 在**動作**選單上，選擇**停用維護時段**。系統會提示您確認您的動作。

## 使用主控台啟用維護時段
<a name="sysman-maintenance-enable-mw"></a>

您可以透過啟用維護時段來繼續一項任務。

**注意**  
如果維護時段使用速率排程，且開始日期目前設定為過去的日期和時間，則會使用目前的日期和時間作為維護時段的開始日期。您可以在啟用維護時段前後變更其開始日期。如需相關資訊，請參閱[使用主控台更新或刪除維護時段資源](sysman-maintenance-update.md)。

**啟用維護時段**

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

1. 在導覽窗格中，選擇 **Maintenance Windows**。

1. 選取要啟用的維護時段旁的核取方塊。

1. 選擇**動作，啟用維護時段**。系統會提示您確認您的動作。

# 使用主控台更新或刪除維護時段資源
<a name="sysman-maintenance-update"></a>

您可以在 Maintenance Windows ( AWS Systems Manager中的工具) 中更新或刪除維護時段。您也可以更新或刪除維護時段的目標或任務。如果您編輯維護時段的詳細資訊，即可變更排程、目標和任務。您也可以指定時段的名稱和說明、目標和任務，這可協助您更了解他們的用途，並可讓您更輕鬆地管理您佇列的時段。

本節說明如何使用 Systems Manager 主控台來更新或刪除維護時段、目標和任務。如需有關如何使用 AWS Command Line Interface (AWS CLI) 完成此操作的詳細資訊，請參閱 [教學課程：使用 更新維護時段 AWS CLI](maintenance-windows-cli-tutorials-update.md)。

**Topics**
+ [使用主控台更新或刪除維護時段](#sysman-maintenance-update-mw)
+ [使用主控台更新或取消註冊維護時段目標](#sysman-maintenance-update-target)
+ [使用主控台更新或取消註冊維護時段任務](#sysman-maintenance-update-tasks)

## 使用主控台更新或刪除維護時段
<a name="sysman-maintenance-update-mw"></a>

您可以更新維護時段來變更其名稱、描述和排程，以及維護時段是否應允許未註冊的目標。

**更新或刪除維護時段**

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

1. 在導覽窗格中，選擇 **Maintenance Windows**。

1. 選取您要更新或刪除之維護時段旁邊的按鈕，然後執行以下其中一項：
   + 選擇 **刪除**。系統會提示您確認您的動作。
   + 選擇**編輯**。在 **Edit maintenance window** (編輯維護時段) 頁面上，變更您想更改的值和選項，然後選擇 **Save changes** (儲存變更)。

     如需您可以選擇的組態的相關資訊，請參閱 [使用主控台建立維護時段](sysman-maintenance-create-mw.md)。

## 使用主控台更新或取消註冊維護時段目標
<a name="sysman-maintenance-update-target"></a>

您可以更新或取消註冊維護時段的目標。如果您選擇更新維護時段目標，您可以指定新的目標名稱、說明和擁有者。您也可以選擇不同的目標。

**更新或刪除維護時段的目標**

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

1. 在導覽窗格中，選擇 **Maintenance Windows**。

1. 選擇要更新之維護時段的名稱、選擇 **Targets** (目標) 索引標籤，然後執行以下其中一項：
   + 若要更新目標，請選取要更新目標旁邊的按鈕，然後選擇 **Edit** (編輯)。
   + 若要取消註冊目標，請選取要取消註冊目標旁邊的按鈕，然後選擇 **Deregister targets** (取消註冊目標)。在 **Deregister maintenance windows target** (取消註冊維護時段目標) 對話方塊中，選擇 **Deregister** (取消註冊)。

## 使用主控台更新或取消註冊維護時段任務
<a name="sysman-maintenance-update-tasks"></a>

您可以更新或取消註冊維護時段的任務。如果您選擇更新，您可以指定新的任務名稱、說明和擁有者。對於 Run Command 和 Automation 任務，您可以為任務選擇不同的 SSM 文件。不過您無法編輯任務，以變更其類型。例如，如果您建立自動化任務，您不能編輯該任務，並將其變更為 Run Command 任務。

**使用主控台更新或刪除維護時段的任務**

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

1. 在導覽窗格中，選擇 **Maintenance Windows**。

1. 選擇您要更新的維護時段名稱。

1. 選擇 **Tasks** (任務) 索引標籤，然後選取要更新任務旁邊的按鈕。

1. 執行以下任意一項：
   + 若要取消註冊任務，請選擇 **Deregister task** (取消註冊任務)。
   + 若要編輯任務，請選擇 **Edit** (編輯)。變更您想更改的值和選項，然後選擇 **Edit task** (編輯任務)。

# 教學課程
<a name="maintenance-windows-tutorials"></a>

本節中的教學課程說明如何在使用維護時段時執行常見任務。

**完成事前準備**  
嘗試這些教學之前，請完成以下事前準備。
+ **在本機電腦上設定 AWS CLI** – 您必須先在本機電腦上安裝和設定 CLI，才能執行 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)。
+ **驗證維護時段角色和許可** – 您帳戶中的 AWS 管理員必須授予您使用 CLI 管理維護時段時所需的 AWS Identity and Access Management (IAM) 的許可。如需相關資訊，請參閱[設定 Maintenance Windows](setting-up-maintenance-windows.md)。
+ **建立或設定與 Systems Manager 相容的執行個體** – 要完成教學課程，您需要至少一個 Amazon Elastic Compute Cloud (Amazon EC2) 執行個體，該執行個體要設定為可與 Systems Manager 搭配使用。這表示 SSM Agent 會安裝在此執行個體，且 Systems Manager 的 IAM 執行個體設定檔會連接到此執行個體。

  我們建議透過預先安裝的代理程式從 AWS 管理的 Amazon Machine Image (AMI) 來啟動執行個體。如需更多詳細資訊，請參閱 [尋找預先安裝了 SSM Agent的 AMIs](ami-preinstalled-agent.md)。

  如需在執行個體安裝 SSM Agent 的詳細資訊，請參閱下列主題：
  + [在 Windows Server EC2 執行個體上手動安裝和解除安裝 SSM Agent](manually-install-ssm-agent-windows.md)
  + [在 Linux EC2 執行個體上手動安裝和解除安裝 SSM Agent](manually-install-ssm-agent-linux.md)

  如需有關為執行個體設定 Systems Manager IAM 許可的詳細資訊，請參閱[設定 Systems Manager 所需的執行個體許可](setup-instance-permissions.md)。
+ **建立所需的其他資源** – Run Command (Systems Manager 的工具) 包含許多任務，您只需建立先決條件主題中列出的資源。因此，我們提供簡單的 Run Command 任務，供您在第一次演練教學過程中使用。如本主題之前所述，您還需要已設定為可與 Systems Manager 搭配使用的 EC2 執行個體。在設定該執行個體後，您可以註冊簡單的 Run Command 任務。

  Systems Manager Maintenance Windows 工具支援執行下列四種任務：
  + Run Command 命令
  + Systems Manager Automation 工作流程
  + AWS Lambda 函式
  + AWS Step Functions 任務

  一般來說，如果您想要執行的維護時段任務需要其他資源，則應先建立這些資源。例如，如果您想要執行 AWS Lambda 函數的維護時段，請在開始前先建立 Lambda 函數；對於 Run Command 任務，請建立您可以將命令輸出儲存到其中的 S3 儲存貯體 (如果您計劃這麼做)，以此類推。

**Topics**
+ [教學課程：使用 建立和管理維護時段 AWS CLI](maintenance-window-tutorial-cli.md)
+ [教學課程：使用主控台建立修補維護時段](maintenance-window-tutorial-patching.md)

# 教學課程：使用 建立和管理維護時段 AWS CLI
<a name="maintenance-window-tutorial-cli"></a>

這個區段包括的教學，可協助您了解如何使用 AWS Command Line Interface (AWS CLI) 來執行下列動作：
+ 建立和設定維護時段
+ 檢視維護時段的資訊
+ 檢視維護時段任務和任務執行的相關資訊
+ 更新維護時段
+ 刪除維護時段

**追蹤資源 ID**  
當您完成這些 AWS CLI 教學課程中的任務時，請追蹤您執行的命令所產生的資源 IDs。您可以使用這些 ID 做為後續命令的輸入。例如，在建立維護時段時，系統會以下列格式將維護時段的 ID 提供給您：

```
{
   "WindowId":"mw-0c50858d01EXAMPLE"
}
```

請記下以下系統產生的 ID，因為此區段的教學會用到這些資訊：
+ `WindowId`
+ `WindowTargetId`
+ `WindowTaskId`
+ `WindowExecutionId`
+ `TaskExecutionId`
+ `InvocationId`
+ `ExecutionId`

您也需要計劃在此教學課程中使用之 EC2 執行個體的 ID。例如：`i-02573cafcfEXAMPLE`

**Topics**
+ [教學課程：使用 建立和設定維護時段 AWS CLI](maintenance-windows-cli-tutorials-create.md)
+ [教學課程：使用 檢視維護時段的相關資訊 AWS CLI](maintenance-windows-cli-tutorials-describe.md)
+ [教學課程：使用 檢視任務和任務執行的相關資訊 AWS CLI](mw-cli-tutorial-task-info.md)
+ [教學課程：使用 更新維護時段 AWS CLI](maintenance-windows-cli-tutorials-update.md)
+ [教學課程：使用 刪除維護時段 AWS CLI](mw-cli-tutorial-delete-mw.md)

# 教學課程：使用 建立和設定維護時段 AWS CLI
<a name="maintenance-windows-cli-tutorials-create"></a>

本教學課程示範如何使用 AWS Command Line Interface (AWS CLI) 來建立和設定維護時段、其目標及其任務。此教學的主要過程包含幾個簡單的步驟。建立一個維護時段、識別單一目標，並為要執行的維護時段設定簡單的任務。我們會在過程中提供您可用來嘗試更複雜案例的資訊。

當您按照此教學課程中的步驟，使用自己的選項和 ID 來取代斜體*紅色*文字。例如，使用您所建立之資源 ID 取代維護時段 ID *mw-0c50858d01EXAMPLE* 和執行個體 ID *i-02573cafcfEXAMPLE*。

**Topics**
+ [步驟 1：使用 建立維護時段 AWS CLI](mw-cli-tutorial-create-mw.md)
+ [步驟 2：使用 向維護時段註冊目標節點 AWS CLI](mw-cli-tutorial-targets.md)
+ [步驟 3：使用 向維護時段註冊任務 AWS CLI](mw-cli-tutorial-tasks.md)

# 步驟 1：使用 建立維護時段 AWS CLI
<a name="mw-cli-tutorial-create-mw"></a>

在此步驟中，您會建立維護時段並指定其基本選項，例如名稱、排程和持續時間。在後續步驟中，您可以選擇其更新的執行個體和其執行的任務。

在我們的範例中，您將建立每 5 分鐘執行一次的維護時段。一般而言，您無法如此頻繁地執行維護時段。不過，這個速率可讓您快速取得教學結果。我們也將示範如何在任務已成功執行之後變更為較低的頻率速率。

**注意**  
如需維護時段的各種排程相關選項彼此之間有何關聯的說明，請參閱 [維護時段排程與作用期間選項](maintenance-windows-schedule-options.md)。  
如需使用 `--schedule` 選項的詳細資訊，請參閱[參考：Systems Manager 的 Cron 和 Rate 運算式](reference-cron-and-rate-expressions.md)。

**使用 建立維護時段 AWS CLI**

1. 開啟 AWS Command Line Interface (AWS CLI) 並在本機電腦上執行下列命令，以建立執行下列動作的維護時段：
   + 每 5 分鐘執行一次，持續時間長達兩個小時 (視需要)。
   + 避免讓新任務在維護時段操作結束的 1 小時內啟動。
   + 允許沒有關聯的目標可讓您尚未註冊 (您未向維護時段註冊的執行個體)。
   + 自訂標籤的使用，表示其建立者想要在教學中使用它。

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

   ```
   aws ssm create-maintenance-window \
       --name "My-First-Maintenance-Window" \
       --schedule "rate(5 minutes)" \
       --duration 2 \
       --cutoff 1 \
       --allow-unassociated-targets \
       --tags "Key=Purpose,Value=Tutorial"
   ```

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

   ```
   aws ssm create-maintenance-window ^
       --name "My-First-Maintenance-Window" ^
       --schedule "rate(5 minutes)" ^
       --duration 2 ^
       --cutoff 1 ^
       --allow-unassociated-targets ^
       --tags "Key"="Purpose","Value"="Tutorial"
   ```

------

   系統會傳回與以下相似的資訊。

   ```
   {
      "WindowId":"mw-0c50858d01EXAMPLE"
   }
   ```

1. 立即執行以下命令來檢視相關詳細資訊，以及您帳戶中已存在的任何其他維護時段。

   ```
   aws ssm describe-maintenance-windows
   ```

   系統會傳回與以下相似的資訊。

   ```
   {
      "WindowIdentities":[
         {
               "WindowId": "mw-0c50858d01EXAMPLE",
               "Name": "My-First-Maintenance-Window",
               "Enabled": true,
               "Duration": 2,
               "Cutoff": 1,
               "NextExecutionTime": "2019-05-11T16:46:16.991Z"
         }
      ]
   }
   ```

繼續進行[步驟 2：使用 向維護時段註冊目標節點 AWS CLI](mw-cli-tutorial-targets.md)。

# 步驟 2：使用 向維護時段註冊目標節點 AWS CLI
<a name="mw-cli-tutorial-targets"></a>

在此步驟中，您會使用新的維護時段來註冊目標。在這個情況下，您會指定維護時段執行時要更新哪個節點。

如需使用節點 ID 一次註冊多個節點的範例、使用標籤來識別多個節點的範例，與將資源群組指定為目標的範例，請參閱 [範例：向維護時段註冊目標](mw-cli-tutorial-targets-examples.md)。

**注意**  
您應已建立此步驟中要使用的 Amazon Elastic Compute Cloud (Amazon EC2) 執行個體，如 [Maintenance Windows 教學課程事前準備](maintenance-windows-tutorials.md)所述。

**使用 向維護時段註冊目標節點 AWS CLI**

1. 在本機機器上執行以下命令。將每個*範例資源預留位置*取代為您自己的資訊。

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

   ```
   aws ssm register-target-with-maintenance-window \
       --window-id "mw-0c50858d01EXAMPLE" \
       --resource-type "INSTANCE" \
       --target "Key=InstanceIds,Values=i-02573cafcfEXAMPLE"
   ```

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

   ```
   aws ssm register-target-with-maintenance-window ^
       --window-id "mw-0c50858d01EXAMPLE" ^
       --resource-type "INSTANCE" ^
       --target "Key=InstanceIds,Values=i-02573cafcfEXAMPLE"
   ```

------

   系統會傳回與以下相似的資訊。

   ```
   {
      "WindowTargetId":"e32eecb2-646c-4f4b-8ed1-205fbEXAMPLE"
   }
   ```

1. 立即在您的本機機器上執行以下命令，來檢視有關維護時段目標的詳細資訊。

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

   ```
   aws ssm describe-maintenance-window-targets \
       --window-id "mw-0c50858d01EXAMPLE"
   ```

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

   ```
   aws ssm describe-maintenance-window-targets ^
       --window-id "mw-0c50858d01EXAMPLE"
   ```

------

   系統會傳回與以下相似的資訊。

   ```
   {
       "Targets": [
           {
               "WindowId": "mw-0c50858d01EXAMPLE",
               "WindowTargetId": "e32eecb2-646c-4f4b-8ed1-205fbEXAMPLE",
               "ResourceType": "INSTANCE",
               "Targets": [
                   {
                       "Key": "InstanceIds",
                       "Values": [
                           "i-02573cafcfEXAMPLE"
                       ]
                   }
               ]
           }
       ]
   }
   ```

繼續進行[步驟 3：使用 向維護時段註冊任務 AWS CLI](mw-cli-tutorial-tasks.md)。

# 範例：向維護時段註冊目標
<a name="mw-cli-tutorial-targets-examples"></a>

您可以使用其節點 ID 將單一節點註冊為目標，如 [步驟 2：使用 向維護時段註冊目標節點 AWS CLI](mw-cli-tutorial-targets.md) 中所示範。您也可以使用此頁面上的命令格式來將一或多個節點註冊為目標。

一般而言，有兩種方法可以識別您想要做為維護時段目標的節點：指定個別的節點，並使用資源標籤。資源標籤方法提供多個選項，如範例 2-3 所示。

您也可以將一或多個資源群組指定為維護時段的目標。資源群組可以包含節點和許多其他類型的支援 AWS 資源。接下來的範例 4 和 5 會示範如何將資源群組新增到維護時段目標。

**注意**  
如果單一維護時段任務已向多個目標註冊，則其任務叫用會依序發生，而非平行發生。如果您的任務必須同時在多個目標上執行，請個別註冊每個目標的任務，並為每個任務指派相同的優先順序層級。

如需建立和管理資源群組的詳細資訊，請參閱《*AWS Resource Groups 使用者指南*》中的[什麼是資源群組？](https://docs.aws.amazon.com/ARG/latest/userguide/resource-groups.html)和 *AWS 新聞部落格*中的 [AWS的資源群組和標記](https://aws.amazon.com/blogs/aws/resource-groups-and-tagging/)。

如需有關 中Maintenance Windows工具 配額的資訊 AWS Systems Manager，除了下列範例中指定的配額之外，請參閱《》中的 [Systems Manager 服務配額](https://docs.aws.amazon.com/general/latest/gr/ssm.html#limits_ssm)*Amazon Web Services 一般參考*。

## 範例 1：使用節點 ID 註冊多個目標
<a name="mw-target-example-1"></a>

在本機機器上執行下列命令，以使用其節點 ID 將多個節點註冊為目標。將每個*範例資源預留位置*取代為您自己的資訊。

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

```
aws ssm register-target-with-maintenance-window \
    --window-id "mw-0c50858d01EXAMPLE" \
    --resource-type "INSTANCE" \
    --target "Key=InstanceIds,Values=i-02573cafcfEXAMPLE,i-0471e04240EXAMPLE,i-07782c72faEXAMPLE"
```

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

```
aws ssm register-target-with-maintenance-window ^
    --window-id "mw-0c50858d01EXAMPLE ^
    --resource-type "INSTANCE" ^
    --target "Key=InstanceIds,Values=i-02573cafcfEXAMPLE,i-0471e04240EXAMPLE,i-07782c72faEXAMPLE
```

------

**建議使用**：在第一次使用任何維護時段註冊唯一一組的節點時非常有用，但它們「不會」**共用常見的節點標籤。

**配額：**您可以為每個維護時段目標指定總計最多 50 個節點。

## 範例 2：使用節點中套用的資源標籤來註冊目標
<a name="mw-target-example-2"></a>

在本機機器上執行下列命令來註冊節點，這些執行個體皆已包含您已指派之索引鍵值對的標籤。將每個*範例資源預留位置*取代為您自己的資訊。

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

```
aws ssm register-target-with-maintenance-window \
    --window-id "mw-0c50858d01EXAMPLE" \
    --resource-type "INSTANCE" \
    --target "Key=tag:Region,Values=East"
```

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

```
aws ssm register-target-with-maintenance-window ^
    --window-id "mw-0c50858d01EXAMPLE" ^
    --resource-type "INSTANCE" ^
    --target "Key=tag:Region,Values=East"
```

------

**建議使用**：在第一次使用任何維護時段註冊唯一一組的節點時非常有用，但它們「會」**共用常見的節點標籤。

**配額：**您可以為每個目標指定總計最多五個鍵值組。如果您指定了多個鍵值對，則節點必須加上您指定的*所有*標籤鍵和值，才會包含在目標群組中。

**注意**  
您可以使用標籤金鑰 `Patch Group` 或 `PatchGroup` 為一組節點加上標籤，並將共用的金鑰值 (例如 `my-patch-group`) 指派給節點。(如果您已在 [EC2 執行個體中繼資料中允許標籤](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Using_Tags.html#allow-access-to-tags-in-IMDS)，則必須使用 `PatchGroup`，不留空格。) Patch Manager (Systems Manager 中的工具) 會評估節點上的 `Patch Group` 或 `PatchGroup` 金鑰，以協助判斷要對其套用哪些修補基準。如果您的任務會執行 `AWS-RunPatchBaseline` SSM 文件 (或舊版 `AWS-ApplyPatchBaseline` SSM 文件)，則您可以指定向維護時段註冊目標時的相同 `Patch Group` 或 `PatchGroup` 金鑰/值對。例如：`--target "Key=tag:PatchGroup,Values=my-patch-group`。這樣可允許您使用維護時段為一組節點更新修補程式 (已與相同修補基準建立關聯)。如需詳細資訊，請參閱[修補程式群組](patch-manager-patch-groups.md)。

## 範例 3：使用一組標籤索引鍵來註冊目標 (不含標籤值)
<a name="mw-target-example-3"></a>

在本機機器上執行以下命令來註冊執行個體，這些節點皆已獲指派一或多個標籤索引鍵，無論其索引鍵值為何。將每個*範例資源預留位置*取代為您自己的資訊。

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

```
aws ssm register-target-with-maintenance-window \
    --window-id "mw-0c50858d01EXAMPLE" \
    --resource-type "INSTANCE" \
    --target "Key=tag-key,Values=Name,Instance-Type,CostCenter"
```

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

```
aws ssm register-target-with-maintenance-window ^
    --window-id "mw-0c50858d01EXAMPLE" ^
    --resource-type "INSTANCE" ^
    --target "Key=tag-key,Values=Name,Instance-Type,CostCenter"
```

------

**建議使用**：當您想要透過指定多個標籤*索引鍵* (不含其值)，而不只是一個標籤索引鍵或標籤索引鍵值對，來鎖定節點時很有用。

**配額：**您可以為每個目標指定總計最多五個標籤鍵。如果您指定多個標籤鍵，則節點必須加上您指定的*所有*標籤鍵，才會包含在目標群組中。

## 範例 4：使用資源群組名稱註冊目標
<a name="mw-target-example-4"></a>

在本機機器上執行以下命令來註冊指定的資源群組，無論其中包含的資源類型為何。將 *mw-0c50858d01EXAMPLE* 取代為您自己的資訊。如果您指派給維護時段的任務沒有對在此資源群組中包含的資源類型執行動作，系統可能會報告錯誤。儘管發生這些錯誤，找到支援資源類型的任務會持續執行。

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

```
aws ssm register-target-with-maintenance-window \
    --window-id "mw-0c50858d01EXAMPLE" \
    --resource-type "RESOURCE_GROUP" \
    --target "Key=resource-groups:Name,Values=MyResourceGroup"
```

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

```
aws ssm register-target-with-maintenance-window ^
    --window-id "mw-0c50858d01EXAMPLE" ^
    --resource-type "RESOURCE_GROUP" ^
    --target "Key=resource-groups:Name,Values=MyResourceGroup"
```

------

**建議使用**：當您想要快速將資源群組指定為目標，而不評估維護時段是否將其所有資源類型視為目標時，或當您知道資源群組僅包含您的任務對其執行動作的資源類型時很有用。

**配額：**您可以僅將一個資源群組指定為目標。

## 範例 5：在資源群組中篩選資源類型來註冊目標
<a name="mw-target-example-5"></a>

在本機機器上執行以下命令來僅註冊特定資源類型，這些資源類型屬於您指定的資源群組。將 *mw-0c50858d01EXAMPLE* 取代為您自己的資訊。在使用此選項的情況下，即使您為屬於資源群組的資源類型新增任務，如果您還沒有將資源類型明確新增到篩選條件，此任務就不會執行。

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

```
aws ssm register-target-with-maintenance-window \
    --window-id "mw-0c50858d01EXAMPLE" \
    --resource-type "RESOURCE_GROUP" \
    --target "Key=resource-groups:Name,Values=MyResourceGroup" \
    "Key=resource-groups:ResourceTypeFilters,Values=AWS::EC2::Instance,AWS::ECS::Cluster"
```

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

```
aws ssm register-target-with-maintenance-window ^
    --window-id "mw-0c50858d01EXAMPLE" ^
    --resource-type "RESOURCE_GROUP" ^
    --target "Key=resource-groups:Name,Values=MyResourceGroup" ^
    "Key=resource-groups:ResourceTypeFilters,Values=AWS::EC2::Instance,AWS::ECS::Cluster"
```

------

**建議用途**：當您想要嚴格控制維護時段可以執行動作 AWS 的資源類型，或當資源群組包含大量資源類型，而且您想要避免維護時段日誌中不必要的錯誤報告時，請使用此功能。

**配額：**您可以僅將一個資源群組指定為目標。

# 步驟 3：使用 向維護時段註冊任務 AWS CLI
<a name="mw-cli-tutorial-tasks"></a>

在教學課程的此步驟中，您會註冊在 AWS Systems Manager Run Command Linux 的 Amazon Elastic Compute Cloud (Amazon EC2) 執行個體上執行 `df`命令的任務。此標準 Linux 命令的結果會顯示有多少可用空間，以及執行個體磁碟檔案系統上使用多少空間。

-或-

如果您以 Windows Server 的 Amazon EC2 執行個體為目標 (而不是 Linux)，請在下列命令中以 **ipconfig** 取代 **df**。此命令中的輸出會列出在目標執行個體上適用於轉接器的 IP 地址、子網路遮罩以及預設閘道的詳細資訊。

當您準備好註冊其他任務類型，或使用更多可用 Systems Manager Run Command 選項時，請參閱 [範例：向維護時段註冊任務](mw-cli-register-tasks-examples.md)。目前，我們提供所有四個任務類型的詳細資訊，以及其中一些最重要的選項，以協助您規劃更廣泛的真實世界案例。

**向維護時段註冊任務**

1. 在本機機器上執行以下命令。將每個*範例資源預留位置*取代為您自己的資訊。從本機 Windows 機器執行的版本包含逸出字元 (「/」)，您在透過命令列工具執行命令時會需要這些字元。

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

   ```
   aws ssm register-task-with-maintenance-window \
       --window-id mw-0c50858d01EXAMPLE \
       --task-arn "AWS-RunShellScript" \
       --max-concurrency 1 --max-errors 1 \
       --priority 10 \
       --targets "Key=InstanceIds,Values=i-0471e04240EXAMPLE" \
       --task-type "RUN_COMMAND" \
       --task-invocation-parameters '{"RunCommand":{"Parameters":{"commands":["df"]}}}'
   ```

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

   ```
   aws ssm register-task-with-maintenance-window ^
       --window-id mw-0c50858d01EXAMPLE ^
       --task-arn "AWS-RunShellScript" ^
       --max-concurrency 1 --max-errors 1 ^
       --priority 10 ^
       --targets "Key=InstanceIds,Values=i-02573cafcfEXAMPLE" ^
       --task-type "RUN_COMMAND" ^
       --task-invocation-parameters={\"RunCommand\":{\"Parameters\":{\"commands\":[\"df\"]}}}
   ```

------

   系統會傳回與以下相似的資訊：

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

1. 立即執行以下命令來檢視與您建立之維護時段任務相關的詳細資訊。

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

   ```
   aws ssm describe-maintenance-window-tasks \
       --window-id mw-0c50858d01EXAMPLE
   ```

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

   ```
   aws ssm describe-maintenance-window-tasks ^
       --window-id mw-0c50858d01EXAMPLE
   ```

------

1. 系統會傳回與以下相似的資訊。

   ```
   {
       "Tasks": [
           {
               "WindowId": "mw-0c50858d01EXAMPLE",
               "WindowTaskId": "4f7ca192-7e9a-40fe-9192-5cb15EXAMPLE",
               "TaskArn": "AWS-RunShellScript",
               "Type": "RUN_COMMAND",
               "Targets": [
                   {
                       "Key": "InstanceIds",
                       "Values": [
                           "i-02573cafcfEXAMPLE"
                       ]
                   }
               ],
               "TaskParameters": {},
               "Priority": 10,
               "ServiceRoleArn": "arn:aws:iam::123456789012:role/MyMaintenanceWindowServiceRole",
               "MaxConcurrency": "1",
               "MaxErrors": "1"
           }
       ]
   }
   ```

1. 根據您在 [步驟 1：使用 建立維護時段 AWS CLI](mw-cli-tutorial-create-mw.md) 指定的排程，等到任務的執行時間。例如，如果您已指定 **--schedule "rate(5 minutes)"**，請等待五分鐘。然後執行以下命令，來檢視與此任務發生的任何執行所相關的資訊。

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

   ```
   aws ssm describe-maintenance-window-executions \
       --window-id mw-0c50858d01EXAMPLE
   ```

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

   ```
   aws ssm describe-maintenance-window-executions ^
       --window-id mw-0c50858d01EXAMPLE
   ```

------

   系統會傳回與以下相似的資訊。

   ```
   {
       "WindowExecutions": [
           {
               "WindowId": "mw-0c50858d01EXAMPLE",
               "WindowExecutionId": "14bea65d-5ccc-462d-a2f3-e99c8EXAMPLE",
               "Status": "SUCCESS",
               "StartTime": 1557593493.096,
               "EndTime": 1557593498.611
           }
       ]
   }
   ```

**提示**  
任務順利執行後，您可以降低維護時段執行的速率。例如，執行以下命令來將頻率降低為一週一次。將 *mw-0c50858d01EXAMPLE* 取代為您自己的資訊。  

```
aws ssm update-maintenance-window \
    --window-id mw-0c50858d01EXAMPLE \
    --schedule "rate(7 days)"
```

```
aws ssm update-maintenance-window ^
    --window-id mw-0c50858d01EXAMPLE ^
    --schedule "rate(7 days)"
```
如需管理維護時段排程的詳細資訊，請參閱[參考：Systems Manager 的 Cron 和 Rate 運算式](reference-cron-and-rate-expressions.md)和[維護時段排程與作用期間選項](maintenance-windows-schedule-options.md)。  
如需使用 AWS Command Line Interface (AWS CLI) 修改維護時段的詳細資訊，請參閱 [教學課程：使用 更新維護時段 AWS CLI](maintenance-windows-cli-tutorials-update.md)。

如需練習執行 AWS CLI 命令以檢視維護時段任務及其執行的詳細資訊，請繼續 [教學課程：使用 檢視任務和任務執行的相關資訊 AWS CLI](mw-cli-tutorial-task-info.md)。

**存取教學課程命令輸出**  
超出本教學課程的範圍，您可以使用 AWS CLI 檢視與維護時段任務執行相關聯的Run Command命令*輸出*。

不過，您可以使用 檢視此資料 AWS CLI。(您也可以在 Systems Manager 主控台中或在 Amazon Simple Storage Service (Amazon S3) 儲存貯體中存放的日誌檔檢視輸出 (如果您已將維護時段設定為在前述日誌檔中存放命令輸出)。) 您會發現在 Linux EC2 執行個體上的 **df** 命令輸出與以下內容類似。

```
Filesystem 1K-blocks Used Available Use% Mounted on

devtmpfs 485716 0 485716 0% /dev

tmpfs 503624 0 503624 0% /dev/shm

tmpfs 503624 328 503296 1% /run

tmpfs 503624 0 503624 0% /sys/fs/cgroup

/dev/xvda1 8376300 1464160 6912140 18% /
```

在 Windows Server EC2 執行個體的 **ipconfig** 命令輸出與以下內容類似：

```
Windows IP Configuration


Ethernet adapter Ethernet 2:

   Connection-specific DNS Suffix  . : example.com
   IPv4 Address. . . . . . . . . . . : 10.24.34.0/23
   Subnet Mask . . . . . . . . . . . : 255.255.255.255
   Default Gateway . . . . . . . . . : 0.0.0.0

Ethernet adapter Ethernet:

   Media State . . . . . . . . . . . : Media disconnected
   Connection-specific DNS Suffix  . : abc1.wa.example.net

Wireless LAN adapter Local Area Connection* 1:

   Media State . . . . . . . . . . . : Media disconnected
   Connection-specific DNS Suffix  . :

Wireless LAN adapter Wi-Fi:

   Connection-specific DNS Suffix  . :
   Link-local IPv6 Address . . . . . : fe80::100b:c234:66d6:d24f%4
   IPv4 Address. . . . . . . . . . . : 192.0.2.0
   Subnet Mask . . . . . . . . . . . : 255.255.255.0
   Default Gateway . . . . . . . . . : 192.0.2.0

Ethernet adapter Bluetooth Network Connection:

   Media State . . . . . . . . . . . : Media disconnected
   Connection-specific DNS Suffix  . :
```

# 範例：向維護時段註冊任務
<a name="mw-cli-register-tasks-examples"></a>

您可以使用 AWS Command Line Interface (AWS CLI) Run Command透過維護時段在 中的工具 中註冊任務 AWS Systems Manager，如[使用維護時段註冊任務](mw-cli-tutorial-tasks.md)所示。您也可以註冊 Systems Manager Automation 工作流程、 AWS Lambda 函數和 AWS Step Functions 任務的任務，如本主題稍後所示。

**注意**  
為維護時段 Run Command 類型任務指定一或多個目標。視任務而定，其他維護時段任務類型 （自動化 AWS Lambda和 AWS Step Functions) 的目標為選用。如需有關執行未指定目標之任務的詳細資訊，請參閱 [註冊不含目標的維護時段任務](maintenance-windows-targetless-tasks.md)。

在本主題中，我們提供使用 AWS Command Line Interface (AWS CLI) 命令`register-task-with-maintenance-window`向維護時段註冊四種支援任務類型的每一個範例。此範例僅用於示範，但您可以進行修改來建立可運作的任務註冊命令。

**使用 --cli-input-json 選項**  
為了更有效地管理您的任務選項，您可以使用命令選項 `--cli-input-json`，內含 JSON 檔案中參考的選項值。

若要使用我們在以下範例中提供的範本 JSON 檔案內容，請在您的本機機器上執行下列動作：

1. 建立包含 `MyRunCommandTask.json`、`MyAutomationTask.json` 這類名稱或您偏好的另一個名稱來建立檔案。

1. 將我們的 JSON 範本內容複製到此檔案中。

1. 將檔案內容修改為任務註冊適用的內容，然後儲存檔案。

1. 在您存放該檔案的相同目錄中執行下列命令。替換 *MyFile.json* 的檔案名稱。

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

   ```
   aws ssm register-task-with-maintenance-window \
       --cli-input-json file://MyFile.json
   ```

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

   ```
   aws ssm register-task-with-maintenance-window ^
       --cli-input-json file://MyFile.json
   ```

------

**維護時段任務中的虛擬參數**  
在某些範例中，我們使用*虛擬參數*做為將 ID 資訊傳遞到任務的方法。例如，`{{TARGET_ID}}` 和 `{{RESOURCE_ID}}` 可以用來將 AWS 資源的 ID 傳遞給 Automation、Lambda 和 Step Functions 任務。如需 `--task-invocation-parameters` 內容中虛擬參數的詳細資訊，請參閱[註冊維護時段任務時使用虛擬參數](maintenance-window-tasks-pseudo-parameters.md)。

**詳細資訊**  
+ [register-task-with-maintenance-windows 命令的參數選項](mw-cli-task-options.md).
+ 《AWS CLI 命令參考》**中的 [https://docs.aws.amazon.com/cli/latest/reference/ssm/register-task-with-maintenance-window.html](https://docs.aws.amazon.com/cli/latest/reference/ssm/register-task-with-maintenance-window.html) 一節
+ *AWS Systems Manager API 參考*中的 [https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_RegisterTaskWithMaintenanceWindow.html](https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_RegisterTaskWithMaintenanceWindow.html)

## 任務註冊範例
<a name="task-examples"></a>

下列各節提供範例 AWS CLI 命令，用於註冊支援的任務類型，以及可與 `--cli-input-json`選項搭配使用的 JSON 範例。

### 註冊 Systems Manager Run Command 任務
<a name="register-tasks-tutorial-run-command"></a>

以下範例示範如何使用 AWS CLI向維護時段註冊 Systems Manager Run Command 任務。

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

```
aws ssm register-task-with-maintenance-window \
    --window-id mw-0c50858d01EXAMPLE \
    --task-arn "AWS-RunShellScript" \
    --max-concurrency 1 --max-errors 1 --priority 10 \
    --targets "Key=InstanceIds,Values=i-02573cafcfEXAMPLE" \
    --task-type "RUN_COMMAND" \
    --task-invocation-parameters '{"RunCommand":{"Parameters":{"commands":["df"]}}}'
```

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

```
aws ssm register-task-with-maintenance-window ^
    --window-id mw-0c50858d01EXAMPLE ^
    --task-arn "AWS-RunShellScript" ^
    --max-concurrency 1 --max-errors 1 --priority 10 ^
    --targets "Key=InstanceIds,Values=i-02573cafcfEXAMPLE" ^
    --task-type "RUN_COMMAND" ^
    --task-invocation-parameters "{\"RunCommand\":{\"Parameters\":{\"commands\":[\"df\"]}}}"
```

------

**要與 `--cli-input-json` 檔案選項搭配使用的 JSON 內容：**

```
{
    "TaskType": "RUN_COMMAND",
    "WindowId": "mw-0c50858d01EXAMPLE",
    "Description": "My Run Command task to update SSM Agent on an instance",
    "MaxConcurrency": "1",
    "MaxErrors": "1",
    "Name": "My-Run-Command-Task",
    "Priority": 10,
    "Targets": [
        {
            "Key": "WindowTargetIds",
            "Values": [
                "e32eecb2-646c-4f4b-8ed1-205fbEXAMPLE"
            ]
        }
    ],
    "TaskArn": "AWS-UpdateSSMAgent",
    "TaskInvocationParameters": {
        "RunCommand": {
            "Comment": "A TaskInvocationParameters test comment",
            "NotificationConfig": {
                "NotificationArn": "arn:aws:sns:region:123456789012:my-sns-topic-name",
                "NotificationEvents": [
                    "All"
                ],
                "NotificationType": "Invocation"
            },
            "OutputS3BucketName": "amzn-s3-demo-bucket",
            "OutputS3KeyPrefix": "S3-PREFIX",
            "TimeoutSeconds": 3600
        }
    }
}
```

### 註冊 Systems Manager Automation 任務
<a name="register-tasks-tutorial-automation"></a>

以下範例示範如何使用 AWS CLI向維護時段註冊 Systems Manager Automation 任務：

**AWS CLI 命令：**

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

```
aws ssm register-task-with-maintenance-window \
    --window-id "mw-0c50858d01EXAMPLE" \
    --task-arn "AWS-RestartEC2Instance" \
    --service-role-arn arn:aws:iam::123456789012:role/MyMaintenanceWindowServiceRole \
    --task-type AUTOMATION \
    --task-invocation-parameters "Automation={DocumentVersion=5,Parameters={InstanceId='{{RESOURCE_ID}}'}}" \
    --priority 0 --name "My-Restart-EC2-Instances-Automation-Task" \
    --description "Automation task to restart EC2 instances"
```

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

```
aws ssm register-task-with-maintenance-window ^
    --window-id "mw-0c50858d01EXAMPLE" ^
    --task-arn "AWS-RestartEC2Instance" ^
    --service-role-arn arn:aws:iam::123456789012:role/MyMaintenanceWindowServiceRole ^
    --task-type AUTOMATION ^
    --task-invocation-parameters "Automation={DocumentVersion=5,Parameters={InstanceId='{{TARGET_ID}}'}}" ^
    --priority 0 --name "My-Restart-EC2-Instances-Automation-Task" ^
    --description "Automation task to restart EC2 instances"
```

------

**要與 `--cli-input-json` 檔案選項搭配使用的 JSON 內容：**

```
{
    "WindowId": "mw-0c50858d01EXAMPLE",
        "TaskArn": "AWS-PatchInstanceWithRollback",
    "TaskType": "AUTOMATION","TaskInvocationParameters": {
        "Automation": {
            "DocumentVersion": "1",
            "Parameters": {
                "instanceId": [
                    "{{RESOURCE_ID}}"
                ]
            }
        }
    }
}
```

### 註冊 AWS Lambda 任務
<a name="register-tasks-tutorial-lambda"></a>

以下範例示範如何使用 AWS CLI向維護時段註冊 Lambda 函數任務。

對於這些範例，建立 Lambda 函數的使用者會將其命名為 `SSMrestart-my-instances` 並建立名為 `instanceId` 和 `targetType` 的兩個參數。

**重要**  
適用於 Maintenance Windows 的 IAM 政策需要您為 Lambda 函數 (或別名) 名稱新增 `SSM` 字首。在您繼續註冊此類任務之前，請在 中更新其名稱 AWS Lambda 以包含 `SSM`。例如，如果 Lambda 函數名稱為 `MyLambdaFunction`，請變更為 `SSMMyLambdaFunction`。

**AWS CLI 命令：**

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

**重要**  
如果您使用的是 第 2 版 AWS CLI，且 Lambda 承載不是 base64 編碼，則必須在下列命令`--cli-binary-format raw-in-base64-out`中包含 選項。`cli_binary_format` 選項僅在版本 2 中可用。如需有關此 AWS CLI `config`和其他檔案設定的資訊，請參閱*AWS Command Line Interface 《 使用者指南*》中的[支援`config`的檔案設定](https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-files.html#cli-configure-files-settings)。

```
aws ssm register-task-with-maintenance-window \
    --window-id "mw-0c50858d01EXAMPLE" \
    --targets "Key=WindowTargetIds,Values=e32eecb2-646c-4f4b-8ed1-205fbEXAMPLE" \
    --priority 2 --max-concurrency 10 --max-errors 5 --name "My-Lambda-Example" \
    --description "A description for my LAMBDA example task" --task-type "LAMBDA" \
    --task-arn "arn:aws:lambda:region:123456789012:function:serverlessrepo-SSMrestart-my-instances-C4JF9EXAMPLE" \
    --task-invocation-parameters '{"Lambda":{"Payload":"{\"InstanceId\":\"{{RESOURCE_ID}}\",\"targetType\":\"{{TARGET_TYPE}}\"}","Qualifier": "$LATEST"}}'
```

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

**重要**  
如果您使用的是 第 2 版 AWS CLI，且 Lambda 承載不是 base64 編碼，則必須在下列命令`--cli-binary-format raw-in-base64-out`中包含 選項。`cli_binary_format` 選項僅在版本 2 中可用。如需有關此 AWS CLI `config`和其他檔案設定的資訊，請參閱*AWS Command Line Interface 《 使用者指南*》中的[支援`config`的檔案設定](https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-files.html#cli-configure-files-settings)。

```
aws ssm register-task-with-maintenance-window `
    --window-id "mw-0c50858d01EXAMPLE" `
    --targets "Key=WindowTargetIds,Values=e32eecb2-646c-4f4b-8ed1-205fbEXAMPLE" `
    --priority 2 --max-concurrency 10 --max-errors 5 --name "My-Lambda-Example" `
    --description "A description for my LAMBDA example task" --task-type "LAMBDA" `
    --task-arn "arn:aws:lambda:region:123456789012:function:serverlessrepo-SSMrestart-my-instances-C4JF9EXAMPLE" `
    --task-invocation-parameters '{\"Lambda\":{\"Payload\":\"{\\\"InstanceId\\\":\\\"{{RESOURCE_ID}}\\\",\\\"targetType\\\":\\\"{{TARGET_TYPE}}\\\"}\",\"Qualifier\": \"$LATEST\"}}'
```

------

**要與 `--cli-input-json` 檔案選項搭配使用的 JSON 內容：**

```
{
    "WindowId": "mw-0c50858d01EXAMPLE",
    "Targets": [
        {
            "Key": "WindowTargetIds",
            "Values": [
                "e32eecb2-646c-4f4b-8ed1-205fbEXAMPLE"
            ]
        }
    ],
    "TaskArn": "SSM_RestartMyInstances",
    "TaskType": "LAMBDA",
    "MaxConcurrency": "10",
    "MaxErrors": "10",
    "TaskInvocationParameters": {
        "Lambda": {
            "ClientContext": "ew0KICAi--truncated--0KIEXAMPLE",
            "Payload": "{ \"instanceId\": \"{{RESOURCE_ID}}\", \"targetType\": \"{{TARGET_TYPE}}\" }",
            "Qualifier": "$LATEST"
        }
    },
    "Name": "My-Lambda-Task",
    "Description": "A description for my LAMBDA task",
    "Priority": 5
}
```

### 註冊 Step Functions 任務
<a name="register-tasks-tutorial-step-functions"></a>

以下範例示範如何使用 AWS CLI向維護時段註冊 Step Functions 狀態機器任務。

**注意**  
維護時段任務僅支援 Step Functions 標準狀態機器工作流程。這些任務不支援快速狀態機器工作流程。如需有關狀態機器工作流程類型的資訊，請參閱《AWS Step Functions 開發人員指南》**中的[標準與快速工作流程](https://docs.aws.amazon.com/step-functions/latest/dg/concepts-standard-vs-express.html)。

對於這些範例，建立步驟函數狀態機器的使用者會使用名為 `instanceId` 的參數建立名為 `SSMMyStateMachine` 的狀態機器。

**重要**  
的 AWS Identity and Access Management (IAM) 政策Maintenance Windows需要您在 Step Functions 狀態機器名稱前面加上 `SSM`。在繼續註冊這類任務前，您必須在 AWS Step Functions 中將其名稱更新為包含 `SSM`。例如，如果狀態機器名稱為 `MyStateMachine`，請變更為 `SSMMyStateMachine`。

**AWS CLI 命令：**

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

```
aws ssm register-task-with-maintenance-window \
    --window-id "mw-0c50858d01EXAMPLE" \
    --targets "Key=WindowTargetIds,Values=e32eecb2-646c-4f4b-8ed1-205fbEXAMPLE" \
    --task-arn arn:aws:states:region:123456789012:stateMachine:SSMMyStateMachine-MggiqEXAMPLE \
    --task-type STEP_FUNCTIONS \
    --task-invocation-parameters '{"StepFunctions":{"Input":"{\"InstanceId\":\"{{RESOURCE_ID}}\"}", "Name":"{{INVOCATION_ID}}"}}' \
    --priority 0 --max-concurrency 10 --max-errors 5 \
    --name "My-Step-Functions-Task" --description "A description for my Step Functions task"
```

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

```
aws ssm register-task-with-maintenance-window `
    --window-id "mw-0c50858d01EXAMPLE" `
    --targets "Key=WindowTargetIds,Values=e32eecb2-646c-4f4b-8ed1-205fbEXAMPLE" `
    --task-arn arn:aws:states:region:123456789012:stateMachine:SSMMyStateMachine-MggiqEXAMPLE `
    --task-type STEP_FUNCTIONS `
    --task-invocation-parameters '{\"StepFunctions\":{\"Input\":\"{\\\"InstanceId\\\":\\\"{{RESOURCE_ID}}\\\"}\", \"Name\":\"{{INVOCATION_ID}}\"}}' `
    --priority 0 --max-concurrency 10 --max-errors 5 `
    --name "My-Step-Functions-Task" --description "A description for my Step Functions task"
```

------

**要與 `--cli-input-json` 檔案選項搭配使用的 JSON 內容：**

```
{
    "WindowId": "mw-0c50858d01EXAMPLE",
    "Targets": [
        {
            "Key": "WindowTargetIds",
            "Values": [
                "e32eecb2-646c-4f4b-8ed1-205fbEXAMPLE"
            ]
        }
    ],
    "TaskArn": "SSM_MyStateMachine",
    "TaskType": "STEP_FUNCTIONS",
    "MaxConcurrency": "10",
    "MaxErrors": "10",
    "TaskInvocationParameters": {
        "StepFunctions": {
            "Input": "{ \"instanceId\": \"{{TARGET_ID}}\" }",
            "Name": "{{INVOCATION_ID}}"
        }
    },
    "Name": "My-Step-Functions-Task",
    "Description": "A description for my Step Functions task",
    "Priority": 5
}
```

# register-task-with-maintenance-windows 命令的參數選項
<a name="mw-cli-task-options"></a>

**register-task-with-maintenance-window** 命令會提供多種選項，可供您根據需求來設定任務。有些是必要的，有些是選用的，有些僅適用於單一維護時段任務類型。

本主題提供部分這些選項的相關資訊，以協助您使用此教學區段中的範本。如需其他命令選項的相關資訊，請參閱《*AWS CLI 命令參考*》中的 **[https://docs.aws.amazon.com/cli/latest/reference/ssm/register-task-with-maintenance-window.html](https://docs.aws.amazon.com/cli/latest/reference/ssm/register-task-with-maintenance-window.html)**。

**命令選項：`--task-arn`**  
選項 `--task-arn` 可用來指定執行任務的資源。您指定的值取決於註冊的任務類型，如下表所述。


**維護時段任務的 TaskArn 格式**  

| 維護時段任務類型 | TaskArn 值 | 
| --- | --- | 
|  **`RUN_COMMAND`** 與 **`AUTOMATION`**  |  `TaskArn` 是 SSM 文件名稱或 Amazon Resource Name (ARN)。例如： `AWS-RunBatchShellScript`  -或- `arn:aws:ssm:region:111122223333:document/My-Document`.  | 
|  **`LAMBDA`**  |  `TaskArn` 是函數名稱或 ARN。例如： `SSMMy-Lambda-Function` -或- `arn:aws:lambda:region:111122223333:function:SSMMyLambdaFunction`.  適用於 Maintenance Windows 的 IAM 政策需要您為 Lambda 函數 (或別名) 名稱新增 `SSM` 字首。在您繼續註冊此類任務之前，請在 中更新其名稱 AWS Lambda 以包含 `SSM`。例如，如果 Lambda 函數名稱為 `MyLambdaFunction`，請變更為 `SSMMyLambdaFunction`。   | 
|  **`STEP_FUNCTIONS`**  |  `TaskArn` 是狀態機器的 ARN。例如： `arn:aws:states:us-east-2:111122223333:stateMachine:SSMMyStateMachine`.  維護時段的 IAM 政策需要您為 Step Functions 狀態機器名稱加上 `SSM` 字首。註冊這類任務前，您必須在 AWS Step Functions 中將其名稱更新為包含 `SSM`。例如，如果狀態機器名稱為 `MyStateMachine`，請變更為 `SSMMyStateMachine`。   | 

**命令選項：`--service-role-arn`**  
 AWS Systems Manager 要在執行維護時段任務時擔任的角色。

如需詳細資訊，請參閱[設定 Maintenance Windows](setting-up-maintenance-windows.md)

**命令選項：`--task-invocation-parameters`**  
`--task-invocation-parameters` 選項可用來指定四種任務類型特有的參數。下表描述四種任務類型支援的參數。

**注意**  
如需在 `--task-invocation-parameters` 內容中使用虛擬參數的資訊，例如 \$1\$1TARGET\$1ID\$1\$1，請參閱 [註冊維護時段任務時使用虛擬參數](maintenance-window-tasks-pseudo-parameters.md)。

維護時段任務的任務叫用參數選項


| 維護時段任務類型 | 可用參數  | 範例 | 
| --- | --- | --- | 
|  **`RUN_COMMAND`**  |  `Comment` `DocumentHash` `DocumentHashType` `NotificationConfig` `OutputS3BucketName` `OutPutS3KeyPrefix` `Parameters` `ServiceRoleArn` `TimeoutSeconds`  |  <pre>"TaskInvocationParameters": {<br />        "RunCommand": {<br />            "Comment": "My Run Command task comment",<br />            "DocumentHash": "6554ed3d--truncated--5EXAMPLE",<br />            "DocumentHashType": "Sha256",<br />            "NotificationConfig": {<br />                "NotificationArn": "arn:aws:sns:region:123456789012:my-sns-topic-name",<br />                "NotificationEvents": [<br />                    "FAILURE"<br />                ],<br />                "NotificationType": "Invocation"<br />            },<br />            "OutputS3BucketName": "amzn-s3-demo-bucket",<br />            "OutputS3KeyPrefix": "S3-PREFIX",<br />            "Parameters": {<br />                "commands": [<br />                    "Get-ChildItem$env: temp-Recurse|Remove-Item-Recurse-force"<br />                ]<br />            },<br />            "ServiceRoleArn": "arn:aws:iam::123456789012:role/MyMaintenanceWindowServiceRole",<br />            "TimeoutSeconds": 3600<br />        }<br />    }</pre>  | 
|  **`AUTOMATION`**  |  `DocumentVersion` `Parameters`  |  <pre>"TaskInvocationParameters": {<br />        "Automation": {<br />            "DocumentVersion": "3",<br />            "Parameters": {<br />                "instanceid": [<br />                    "{{TARGET_ID}}"<br />                ]<br />            }<br />        }<br />    }</pre>  | 
|  **`LAMBDA`**  |  `ClientContext` `Payload` `Qualifier`  |  <pre>"TaskInvocationParameters": {<br />        "Lambda": {<br />            "ClientContext": "ew0KICAi--truncated--0KIEXAMPLE",<br />            "Payload": "{ \"targetId\": \"{{TARGET_ID}}\", \"targetType\": \"{{TARGET_TYPE}}\" }",<br />            "Qualifier": "$LATEST"<br />        }<br />    }</pre>  | 
|  **`STEP_FUNCTIONS`**  |  `Input` `Name`  |  <pre>"TaskInvocationParameters": {<br />        "StepFunctions": {<br />            "Input": "{ \"targetId\": \"{{TARGET_ID}}\" }",<br />            "Name": "{{INVOCATION_ID}}"<br />        }<br />    }</pre>  | 

# 教學課程：使用 檢視維護時段的相關資訊 AWS CLI
<a name="maintenance-windows-cli-tutorials-describe"></a>

此教學中包含的命令可協助您更新或取得維護時段、任務、執行和呼叫的相關資訊。此範例是依命令來示範如何使用命令選項來篩選您要查看的類型的詳細資訊。

當您按照此教學課程中的步驟，使用自己的選項和 ID 來取代斜體*紅色*文字。例如，使用您所建立之資源 ID 取代維護時段 ID *mw-0c50858d01EXAMPLE* 和執行個體 ID *i-02573cafcfEXAMPLE*。

如需設定 AWS Command Line Interface (AWS CLI) 的詳細資訊[，請參閱安裝、更新和解除安裝 AWS CLI](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-install.html)和[設定 AWS CLI](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-configure.html)。

**Topics**
+ ['describe-maintenance-windows' 的範例](#mw-cli-tutorials-describe-maintenance-windows)
+ ['describe-maintenance-window-targets' 的範例](#mw-cli-tutorials-describe-maintenance-window-targets)
+ ['describe-maintenance-window-tasks' 的範例](#mw-cli-tutorials-describe-maintenance-window-tasks)
+ ['describe-maintenance-windows-for-target' 的範例](#mw-cli-tutorials-describe-maintenance-windows-for-target)
+ ['describe-maintenance-window-executions' 的範例](#mw-cli-tutorials-describe-maintenance-window-executions)
+ ['describe-maintenance-window-schedule' 的範例](#mw-cli-tutorials-describe-maintenance-window-schedule)

## 'describe-maintenance-windows' 的範例
<a name="mw-cli-tutorials-describe-maintenance-windows"></a>

**列出 中的所有維護時段 AWS 帳戶**  
執行下列命令。

```
aws ssm describe-maintenance-windows
```

系統會傳回與以下相似的資訊。

```
{
   "WindowIdentities":[
      {
         "WindowId":"mw-0c50858d01EXAMPLE",
         "Name":"My-First-Maintenance-Window",
         "Enabled":true,
         "Duration":2,
         "Cutoff":0,
         "NextExecutionTime": "2019-05-18T17:01:01.137Z"        
      },
      {
         "WindowId":"mw-9a8b7c6d5eEXAMPLE",
         "Name":"My-Second-Maintenance-Window",
         "Enabled":true,
         "Duration":4,
         "Cutoff":1,
         "NextExecutionTime": "2019-05-30T03:30:00.137Z"        
      },
   ]
}
```

**列出所有啟用的維護時段**  
執行下列命令。

```
aws ssm describe-maintenance-windows --filters "Key=Enabled,Values=true"
```

系統會傳回與以下相似的資訊。

```
{
   "WindowIdentities":[
      {
         "WindowId":"mw-0c50858d01EXAMPLE",
         "Name":"My-First-Maintenance-Window",
         "Enabled":true,
         "Duration":2,
         "Cutoff":0,
         "NextExecutionTime": "2019-05-18T17:01:01.137Z"        
      },
      {
         "WindowId":"mw-9a8b7c6d5eEXAMPLE",
         "Name":"My-Second-Maintenance-Window",
         "Enabled":true,
         "Duration":4,
         "Cutoff":1,
         "NextExecutionTime": "2019-05-30T03:30:00.137Z"        
      },
   ]
}
```

**列出所有停用的維護時段**  
執行下列命令。

```
aws ssm describe-maintenance-windows --filters "Key=Enabled,Values=false"
```

系統會傳回與以下相似的資訊。

```
{
    "WindowIdentities": [
        {
            "WindowId": "mw-6e5c9d4b7cEXAMPLE",
            "Name": "My-Disabled-Maintenance-Window",
            "Enabled": false,
            "Duration": 2,
            "Cutoff": 1
        }
    ]
}
```

**列出所有含特定字首開頭名稱的維護時段**  
執行下列命令。

```
aws ssm describe-maintenance-windows --filters "Key=Name,Values=My"
```

系統會傳回與以下相似的資訊。

```
{
    "WindowIdentities": [
        {
            "WindowId": "mw-0c50858d01EXAMPLE",
            "Name": "My-First-Maintenance-Window",
            "Enabled": true,
            "Duration": 2,
            "Cutoff": 0,
            "NextExecutionTime": "2019-05-18T17:01:01.137Z"
        },
        {
            "WindowId": "mw-9a8b7c6d5eEXAMPLE",
            "Name": "My-Second-Maintenance-Window",
            "Enabled": true,
            "Duration": 4,
            "Cutoff": 1,
            "NextExecutionTime": "2019-05-30T03:30:00.137Z"
        },
        {
            "WindowId": "mw-6e5c9d4b7cEXAMPLE",
            "Name": "My-Disabled-Maintenance-Window",
            "Enabled": false,
            "Duration": 2,
            "Cutoff": 1
        }
    ]
}
```

## 'describe-maintenance-window-targets' 的範例
<a name="mw-cli-tutorials-describe-maintenance-window-targets"></a>

**顯示符合特定擁有者資訊值的維護時段目標**  
執行下列命令。

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

```
aws ssm describe-maintenance-window-targets \
    --window-id "mw-6e5c9d4b7cEXAMPLE" \
    --filters "Key=OwnerInformation,Values=CostCenter1"
```

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

```
aws ssm describe-maintenance-window-targets ^
    --window-id "mw-6e5c9d4b7cEXAMPLE" ^
    --filters "Key=OwnerInformation,Values=CostCenter1"
```

------

**注意**  
支援的篩選條件索引鍵為 `Type`、`WindowTargetId` 和 `OwnerInformation`。

系統會傳回與以下相似的資訊。

```
{
    "Targets": [
        {
            "WindowId": "mw-0c50858d01EXAMPLE",
            "WindowTargetId": "e32eecb2-646c-4f4b-8ed1-205fbEXAMPLE",
            "ResourceType": "INSTANCE",
            "Targets": [
                {
                    "Key": "tag:Name",
                    "Values": [
                        "Production"
                    ]
                }
            ],
            "OwnerInformation": "CostCenter1",
            "Name": "Target1"
        }
    ]
}
```

## 'describe-maintenance-window-tasks' 的範例
<a name="mw-cli-tutorials-describe-maintenance-window-tasks"></a>

**顯示所有叫用 SSM 命令文件 `AWS-RunPowerShellScript` 的註冊任務**  
執行下列命令。

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

```
aws ssm describe-maintenance-window-tasks \
    --window-id "mw-0c50858d01EXAMPLE" \
    --filters "Key=TaskArn,Values=AWS-RunPowerShellScript"
```

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

```
aws ssm describe-maintenance-window-tasks ^
    --window-id "mw-0c50858d01EXAMPLE" ^
    --filters "Key=TaskArn,Values=AWS-RunPowerShellScript"
```

------

系統會傳回與以下相似的資訊。

```
{
   "Tasks":[
      {
         "ServiceRoleArn": "arn:aws:iam::111122223333:role/MyMaintenanceWindowServiceRole",
         "MaxErrors":"1",
         "TaskArn":"AWS-RunPowerShellScript",
         "MaxConcurrency":"1",
         "WindowTaskId":"4f7ca192-7e9a-40fe-9192-5cb15EXAMPLE",
         "TaskParameters":{
            "commands":{
               "Values":[
                  "driverquery.exe"
               ]
            }
         },
         "Priority":3,
         "Type":"RUN_COMMAND",
         "Targets":[
            {
               "TaskTargetId":"i-02573cafcfEXAMPLE",
               "TaskTargetType":"INSTANCE"
            }
         ]
      },
      {
         "ServiceRoleArn":"arn:aws:iam::111122223333:role/MyMaintenanceWindowServiceRole",
         "MaxErrors":"1",
         "TaskArn":"AWS-RunPowerShellScript",
         "MaxConcurrency":"1",
         "WindowTaskId":"4f7ca192-7e9a-40fe-9192-5cb15EXAMPLE",
         "TaskParameters":{
            "commands":{
               "Values":[
                  "ipconfig"
               ]
            }
         },
         "Priority":1,
         "Type":"RUN_COMMAND",
         "Targets":[
            {
               "TaskTargetId":"i-02573cafcfEXAMPLE",
               "TaskTargetType":"WINDOW_TARGET"
            }
         ]
      }
   ]
}
```

**顯示所有具有優先順序「3」的註冊任務**  
執行下列命令。

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

```
aws ssm describe-maintenance-window-tasks \
    --window-id "mw-9a8b7c6d5eEXAMPLE" \
    --filters "Key=Priority,Values=3"
```

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

```
aws ssm describe-maintenance-window-tasks ^
    --window-id "mw-9a8b7c6d5eEXAMPLE" ^
    --filters "Key=Priority,Values=3"
```

------

系統會傳回與以下相似的資訊。

```
{
   "Tasks":[
      {
         "ServiceRoleArn":"arn:aws:iam::111122223333:role/MyMaintenanceWindowServiceRole",
         "MaxErrors":"1",
         "TaskArn":"AWS-RunPowerShellScript",
         "MaxConcurrency":"1",
         "WindowTaskId":"4f7ca192-7e9a-40fe-9192-5cb15EXAMPLE",
         "TaskParameters":{
            "commands":{
               "Values":[
                  "driverquery.exe"
               ]
            }
         },
         "Priority":3,
         "Type":"RUN_COMMAND",
         "Targets":[
            {
               "TaskTargetId":"i-02573cafcfEXAMPLE",
               "TaskTargetType":"INSTANCE"
            }
         ]
      }
   ]
}
```

**顯示所有具有優先順序 "1"，並使用 Run Command 的註冊任務**  
執行下列命令。

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

```
aws ssm describe-maintenance-window-tasks \
    --window-id "mw-0c50858d01EXAMPLE" \
    --filters "Key=Priority,Values=1" "Key=TaskType,Values=RUN_COMMAND"
```

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

```
aws ssm describe-maintenance-window-tasks ^
    --window-id "mw-0c50858d01EXAMPLE" ^
    --filters "Key=Priority,Values=1" "Key=TaskType,Values=RUN_COMMAND"
```

------

系統會傳回與以下相似的資訊。

```
{
    "Tasks": [
        {
            "WindowId": "mw-0c50858d01EXAMPLE",
            "WindowTaskId": "4f7ca192-7e9a-40fe-9192-5cb15EXAMPLE",
            "TaskArn": "AWS-RunShellScript",
            "Type": "RUN_COMMAND",
            "Targets": [
                {
                    "Key": "InstanceIds",
                    "Values": [
                        "i-02573cafcfEXAMPLE"
                    ]
                }
            ],
            "TaskParameters": {},
            "Priority": 1,
            "ServiceRoleArn": "arn:aws:iam::111122223333:role/MyMaintenanceWindowServiceRole",
            "MaxConcurrency": "1",
            "MaxErrors": "1"
        },
        {
            "WindowId": "mw-0c50858d01EXAMPLE",
            "WindowTaskId": "8a5c4629-31b0-4edd-8aea-33698EXAMPLE",
            "TaskArn": "AWS-UpdateSSMAgent",
            "Type": "RUN_COMMAND",
            "Targets": [
                {
                    "Key": "InstanceIds",
                    "Values": [
                        "i-0471e04240EXAMPLE"
                    ]
                }
            ],
            "TaskParameters": {},
            "Priority": 1,
            "ServiceRoleArn": "arn:aws:iam::111122223333:role/MyMaintenanceWindowServiceRole",
            "MaxConcurrency": "1",
            "MaxErrors": "1",
            "Name": "My-Run-Command-Task",
            "Description": "My Run Command task to update SSM Agent on an instance"
        }
    ]
}
```

## 'describe-maintenance-windows-for-target' 的範例
<a name="mw-cli-tutorials-describe-maintenance-windows-for-target"></a>

**列出維護時段目標或任務 (與特定節點相關) 的資訊**  
執行下列命令。

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

```
aws ssm describe-maintenance-windows-for-target \
    --resource-type INSTANCE \
    --targets "Key=InstanceIds,Values=i-02573cafcfEXAMPLE" \
    --max-results 10
```

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

```
aws ssm describe-maintenance-windows-for-target ^
    --resource-type INSTANCE ^
    --targets "Key=InstanceIds,Values=i-02573cafcfEXAMPLE" ^
    --max-results 10
```

------

系統會傳回與以下相似的資訊。

```
{
    "WindowIdentities": [
        {
            "WindowId": "mw-0c50858d01EXAMPLE",
            "Name": "My-First-Maintenance-Window"
        },
        {
            "WindowId": "mw-9a8b7c6d5eEXAMPLE",
            "Name": "My-Second-Maintenance-Window"
        }
    ]
}
```

## 'describe-maintenance-window-executions' 的範例
<a name="mw-cli-tutorials-describe-maintenance-window-executions"></a>

**列出在特定日期之前執行的所有任務**  
執行下列命令。

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

```
aws ssm describe-maintenance-window-executions \
    --window-id "mw-9a8b7c6d5eEXAMPLE" \
    --filters "Key=ExecutedBefore,Values=2019-05-12T05:00:00Z"
```

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

```
aws ssm describe-maintenance-window-executions ^
    --window-id "mw-9a8b7c6d5eEXAMPLE" ^
    --filters "Key=ExecutedBefore,Values=2019-05-12T05:00:00Z"
```

------

系統會傳回與以下相似的資訊。

```
{
    "WindowExecutions": [
        {
            "WindowId": "mw-0c50858d01EXAMPLE",
            "WindowExecutionId": "14bea65d-5ccc-462d-a2f3-e99c8EXAMPLE",
            "Status": "FAILED",
            "StatusDetails": "The following SSM parameters are invalid: LevelUp",
            "StartTime": 1557617747.993,
            "EndTime": 1557617748.101
        },
        {
            "WindowId": "mw-9a8b7c6d5eEXAMPLE",
            "WindowExecutionId": "791b72e0-f0da-4021-8b35-f95dfEXAMPLE",
            "Status": "SUCCESS",
            "StartTime": 1557594085.428,
            "EndTime": 1557594090.978
        },
        {
            "WindowId": "mw-0c50858d01EXAMPLE",
            "WindowExecutionId": "ecec60fa-6bb0-4d26-98c7-140308EXAMPLE",
            "Status": "SUCCESS",
            "StartTime": 1557593793.483,
            "EndTime": 1557593798.978
        }
    ]
}
```

**列出在特定日期之後執行的所有任務**  
執行下列命令。

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

```
aws ssm describe-maintenance-window-executions \
    --window-id "mw-9a8b7c6d5eEXAMPLE" \
    --filters "Key=ExecutedAfter,Values=2018-12-31T17:00:00Z"
```

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

```
aws ssm describe-maintenance-window-executions ^
    --window-id "mw-9a8b7c6d5eEXAMPLE" ^
    --filters "Key=ExecutedAfter,Values=2018-12-31T17:00:00Z"
```

------

系統會傳回與以下相似的資訊。

```
{
    "WindowExecutions": [
        {
            "WindowId": "mw-0c50858d01EXAMPLE",
            "WindowExecutionId": "14bea65d-5ccc-462d-a2f3-e99c8EXAMPLE",
            "Status": "FAILED",
            "StatusDetails": "The following SSM parameters are invalid: LevelUp",
            "StartTime": 1557617747.993,
            "EndTime": 1557617748.101
        },
        {
            "WindowId": "mw-9a8b7c6d5eEXAMPLE",
            "WindowExecutionId": "791b72e0-f0da-4021-8b35-f95dfEXAMPLE",
            "Status": "SUCCESS",
            "StartTime": 1557594085.428,
            "EndTime": 1557594090.978
        },
        {
            "WindowId": "mw-0c50858d01EXAMPLE",
            "WindowExecutionId": "ecec60fa-6bb0-4d26-98c7-140308EXAMPLE",
            "Status": "SUCCESS",
            "StartTime": 1557593793.483,
            "EndTime": 1557593798.978
        }
    ]
}
```

## 'describe-maintenance-window-schedule' 的範例
<a name="mw-cli-tutorials-describe-maintenance-window-schedule"></a>

**顯示後續 10 個排程替特定節點執行的維護時段**  
執行下列命令。

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

```
aws ssm describe-maintenance-window-schedule \
    --resource-type INSTANCE \
    --targets "Key=InstanceIds,Values=i-07782c72faEXAMPLE" \
    --max-results 10
```

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

```
aws ssm describe-maintenance-window-schedule ^
    --resource-type INSTANCE ^
    --targets "Key=InstanceIds,Values=i-07782c72faEXAMPLE" ^
    --max-results 10
```

------

系統會傳回與以下相似的資訊。

```
{
    "ScheduledWindowExecutions": [
        {
            "WindowId": "mw-0c50858d01EXAMPLE",
            "Name": "My-First-Maintenance-Window",
            "ExecutionTime": "2019-05-18T23:35:24.902Z"
        },
        {
            "WindowId": "mw-0c50858d01EXAMPLE",
            "Name": "My-First-Maintenance-Window",
            "ExecutionTime": "2019-05-25T23:35:24.902Z"
        },
        {
            "WindowId": "mw-0c50858d01EXAMPLE",
            "Name": "My-First-Maintenance-Window",
            "ExecutionTime": "2019-06-01T23:35:24.902Z"
        },
        {
            "WindowId": "mw-0c50858d01EXAMPLE",
            "Name": "My-First-Maintenance-Window",
            "ExecutionTime": "2019-06-08T23:35:24.902Z"
        },
        {
            "WindowId": "mw-9a8b7c6d5eEXAMPLE",
            "Name": "My-Second-Maintenance-Window",
            "ExecutionTime": "2019-06-15T23:35:24.902Z"
        },
        {
            "WindowId": "mw-0c50858d01EXAMPLE",
            "Name": "My-First-Maintenance-Window",
            "ExecutionTime": "2019-06-22T23:35:24.902Z"
        },
        {
            "WindowId": "mw-9a8b7c6d5eEXAMPLE",
            "Name": "My-Second-Maintenance-Window",
            "ExecutionTime": "2019-06-29T23:35:24.902Z"
        },
        {
            "WindowId": "mw-0c50858d01EXAMPLE",
            "Name": "My-First-Maintenance-Window",
            "ExecutionTime": "2019-07-06T23:35:24.902Z"
        },
        {
            "WindowId": "mw-9a8b7c6d5eEXAMPLE",
            "Name": "My-Second-Maintenance-Window",
            "ExecutionTime": "2019-07-13T23:35:24.902Z"
        },
        {
            "WindowId": "mw-0c50858d01EXAMPLE",
            "Name": "My-First-Maintenance-Window",
            "ExecutionTime": "2019-07-20T23:35:24.902Z"
        }
    ],
    "NextToken": "AAEABUXdceT92FvtKld/dGHELj5Mi+GKW/EXAMPLE"
}
```

**顯示替標記了特定金鑰/值對之節點排程的維護時段**  
執行下列命令。

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

```
aws ssm describe-maintenance-window-schedule \
    --resource-type INSTANCE \
    --targets "Key=tag:prod,Values=rhel7"
```

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

```
aws ssm describe-maintenance-window-schedule ^
    --resource-type INSTANCE ^
    --targets "Key=tag:prod,Values=rhel7"
```

------

系統會傳回與以下相似的資訊。

```
{
    "ScheduledWindowExecutions": [
        {
            "WindowId": "mw-0c50858d01EXAMPLE",
            "Name": "DemoRateStartDate",
            "ExecutionTime": "2019-10-20T05:34:56-07:00"
        },
        {
            "WindowId": "mw-0c50858d01EXAMPLE",
            "Name": "DemoRateStartDate",
            "ExecutionTime": "2019-10-21T05:34:56-07:00"
        },
        {
            "WindowId": "mw-0c50858d01EXAMPLE",
            "Name": "DemoRateStartDate",
            "ExecutionTime": "2019-10-22T05:34:56-07:00"
        },
        {
            "WindowId": "mw-0c50858d01EXAMPLE",
            "Name": "DemoRateStartDate",
            "ExecutionTime": "2019-10-23T05:34:56-07:00"
        },
        {
            "WindowId": "mw-0c50858d01EXAMPLE",
            "Name": "DemoRateStartDate",
            "ExecutionTime": "2019-10-24T05:34:56-07:00"
        }
    ],
    "NextToken": "AAEABccwSXqQRGKiTZ1yzGELR6cxW4W/EXAMPLE"
}
```

**顯示後續四個維護時段的開始時間**  
執行下列命令。

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

```
aws ssm describe-maintenance-window-schedule \
    --window-id "mw-0c50858d01EXAMPLE" \
    --max-results "4"
```

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

```
aws ssm describe-maintenance-window-schedule ^
    --window-id "mw-0c50858d01EXAMPLE" ^
    --max-results "4"
```

------

系統會傳回與以下相似的資訊。

```
{
    "WindowSchedule": [
        {
            "ScheduledWindowExecutions": [
                {
                    "ExecutionTime": "2019-10-04T10:10:10Z",
                    "Name": "My-First-Maintenance-Window",
                    "WindowId": "mw-0c50858d01EXAMPLE"
                },
                {
                    "ExecutionTime": "2019-10-11T10:10:10Z",
                    "Name": "My-First-Maintenance-Window",
                    "WindowId": "mw-0c50858d01EXAMPLE"
                },
                {
                    "ExecutionTime": "2019-10-18T10:10:10Z",
                    "Name": "My-First-Maintenance-Window",
                    "WindowId": "mw-0c50858d01EXAMPLE"
                },
                {
                    "ExecutionTime": "2019-10-25T10:10:10Z",
                    "Name": "My-First-Maintenance-Window",
                    "WindowId": "mw-0c50858d01EXAMPLE"
                }
            ]
        }
    ]
}
```

# 教學課程：使用 檢視任務和任務執行的相關資訊 AWS CLI
<a name="mw-cli-tutorial-task-info"></a>

本教學課程示範如何使用 AWS Command Line Interface (AWS CLI) 來檢視已完成維護時段任務的詳細資訊。

如果您直接從 [教學課程：使用 建立和設定維護時段 AWS CLI](maintenance-windows-cli-tutorials-create.md) 繼續執行，請確保維護時段有足夠的時間可執行至少一次，以查看其執行的結果。

當您按照此教學課程中的步驟，使用自己的選項和 ID 來取代斜體*紅色*文字。例如，使用您所建立之資源 ID 取代維護時段 ID *mw-0c50858d01EXAMPLE* 和執行個體 ID *i-02573cafcfEXAMPLE*。

**使用 檢視任務和任務執行的相關資訊 AWS CLI**

1. 執行以下命令，以檢視特定維護時段的任務執行清單。

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

   ```
   aws ssm describe-maintenance-window-executions \
       --window-id "mw-0c50858d01EXAMPLE"
   ```

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

   ```
   aws ssm describe-maintenance-window-executions ^
       --window-id "mw-0c50858d01EXAMPLE"
   ```

------

   系統會傳回與以下相似的資訊。

   ```
   {
       "WindowExecutions": [
           {
               "WindowId": "mw-0c50858d01EXAMPLE",
               "WindowExecutionId": "14bea65d-5ccc-462d-a2f3-e99c8EXAMPLE",
               "Status": "SUCCESS",
               "StartTime": 1557593793.483,
               "EndTime": 1557593798.978
           },
           {
               "WindowId": "mw-0c50858d01EXAMPLE",
               "WindowExecutionId": "791b72e0-f0da-4021-8b35-f95dfEXAMPLE",
               "Status": "SUCCESS",
               "StartTime": 1557593493.096,
               "EndTime": 1557593498.611
           },
           {
               "WindowId": "mw-0c50858d01EXAMPLE",
               "WindowExecutionId": "ecec60fa-6bb0-4d26-98c7-140308EXAMPLE",
               "Status": "SUCCESS",
               "StatusDetails": "No tasks to execute.",
               "StartTime": 1557593193.309,
               "EndTime": 1557593193.334
           }
       ]
   }
   ```

1. 執行以下命令，以取得有關的維護時段任務執行。

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

   ```
   aws ssm get-maintenance-window-execution \
       --window-execution-id "14bea65d-5ccc-462d-a2f3-e99c8EXAMPLE"
   ```

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

   ```
   aws ssm get-maintenance-window-execution ^
       --window-execution-id "14bea65d-5ccc-462d-a2f3-e99c8EXAMPLE"
   ```

------

   系統會傳回與以下相似的資訊。

   ```
   {
       "WindowExecutionId": "14bea65d-5ccc-462d-a2f3-e99c8EXAMPLE",
       "TaskIds": [
           "c9b05aba-197f-4d8d-be34-e73fbEXAMPLE"
       ],
       "Status": "SUCCESS",
       "StartTime": 1557593493.096,
       "EndTime": 1557593498.611
   }
   ```

1. 執行以下命令，以列出維護時段執行期間執行的任務清單。

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

   ```
   aws ssm describe-maintenance-window-execution-tasks \
       --window-execution-id "14bea65d-5ccc-462d-a2f3-e99c8EXAMPLE"
   ```

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

   ```
   aws ssm describe-maintenance-window-execution-tasks ^
       --window-execution-id "14bea65d-5ccc-462d-a2f3-e99c8EXAMPLE"
   ```

------

   系統會傳回與以下相似的資訊。

   ```
   {
       "WindowExecutionTaskIdentities": [
           {
               "WindowExecutionId": "14bea65d-5ccc-462d-a2f3-e99c8EXAMPLE",
               "TaskExecutionId": "c9b05aba-197f-4d8d-be34-e73fbEXAMPLE",
               "Status": "SUCCESS",
               "StartTime": 1557593493.162,
               "EndTime": 1557593498.57,
               "TaskArn": "AWS-RunShellScript",
               "TaskType": "RUN_COMMAND"
           }
       ]
   }
   ```

1. 執行以下命令，以取得有關執行任務的詳細資訊。

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

   ```
   aws ssm get-maintenance-window-execution-task \
       --window-execution-id "14bea65d-5ccc-462d-a2f3-e99c8EXAMPLE" \
       --task-id "c9b05aba-197f-4d8d-be34-e73fbEXAMPLE"
   ```

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

   ```
   aws ssm get-maintenance-window-execution-task ^
       --window-execution-id "14bea65d-5ccc-462d-a2f3-e99c8EXAMPLE" ^
       --task-id "c9b05aba-197f-4d8d-be34-e73fbEXAMPLE"
   ```

------

   系統會傳回與以下相似的資訊。

   ```
   {
       "WindowExecutionId": "14bea65d-5ccc-462d-a2f3-e99c8EXAMPLE",
       "TaskExecutionId": "c9b05aba-197f-4d8d-be34-e73fbEXAMPLE",
       "TaskArn": "AWS-RunShellScript",
       "ServiceRole": "arn:aws:iam::111122223333:role/MyMaintenanceWindowServiceRole",
       "Type": "RUN_COMMAND",
       "TaskParameters": [
           {
               "aws:InstanceId": {
                   "Values": [
                       "i-02573cafcfEXAMPLE"
                   ]
               },
               "commands": {
                   "Values": [
                       "df"
                   ]
               }
           }
       ],
       "Priority": 10,
       "MaxConcurrency": "1",
       "MaxErrors": "1",
       "Status": "SUCCESS",
       "StartTime": 1557593493.162,
       "EndTime": 1557593498.57
   }
   ```

1. 執行以下命令以獲得執行時特定的呼叫式任務。

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

   ```
   aws ssm describe-maintenance-window-execution-task-invocations \
       --window-execution-id "14bea65d-5ccc-462d-a2f3-e99c8EXAMPLE" \
       --task-id "c9b05aba-197f-4d8d-be34-e73fbEXAMPLE"
   ```

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

   ```
   aws ssm describe-maintenance-window-execution-task-invocations ^
       --window-execution-id "14bea65d-5ccc-462d-a2f3-e99c8EXAMPLE" ^
       --task-id "c9b05aba-197f-4d8d-be34-e73fbEXAMPLE"
   ```

------

   系統會傳回與以下相似的資訊。

   ```
   {
       "WindowExecutionTaskInvocationIdentities": [
           {
               "WindowExecutionId": "14bea65d-5ccc-462d-a2f3-e99c8EXAMPLE",
               "TaskExecutionId": "c9b05aba-197f-4d8d-be34-e73fbEXAMPLE",
               "InvocationId": "c336d2ab-09de-44ba-8f6a-6136cEXAMPLE",
               "ExecutionId": "76a5a04f-caf6-490c-b448-92c02EXAMPLE",
               "TaskType": "RUN_COMMAND",
               "Parameters": "{\"documentName\":\"AWS-RunShellScript\",\"instanceIds\":[\"i-02573cafcfEXAMPLE\"],\"maxConcurrency\":\"1\",\"maxErrors\":\"1\",\"parameters\":{\"commands\":[\"df\"]}}",
               "Status": "SUCCESS",
               "StatusDetails": "Success",
               "StartTime": 1557593493.222,
               "EndTime": 1557593498.466
           }
       ]
   }
   ```

# 教學課程：使用 更新維護時段 AWS CLI
<a name="maintenance-windows-cli-tutorials-update"></a>

本教學課程示範如何使用 AWS Command Line Interface (AWS CLI) 更新維護時段。它還說明如何更新不同的任務類型，包括 AWS Systems Manager Run Command和 自動化的任務類型 AWS Lambda，以及 AWS Step Functions。

本節中的範例使用以下 Systems Manager 動作來更新維護時段。
+ [UpdateMaintenanceWindow](https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_UpdateMaintenanceWindow.html)
+ [UpdateMaintenanceWindowTarget](https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_UpdateMaintenanceWindowTarget.html)
+ [UpdateMaintenanceWindowTask](https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_UpdateMaintenanceWindowTask.html)
+ [DeregisterTargetFromMaintenanceWindow](https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_DeregisterTargetFromMaintenanceWindow.html)

如需如何使用 Systems Manager 主控台更新維護時段的資訊，請參閱 [使用主控台更新或刪除維護時段資源](sysman-maintenance-update.md)。

當您按照此教學課程中的步驟，使用自己的選項和 ID 來取代斜體*紅色*文字。例如，使用您所建立之資源 ID 取代維護時段 ID *mw-0c50858d01EXAMPLE* 和執行個體 ID *i-02573cafcfEXAMPLE*。

**使用 更新維護時段 AWS CLI**

1. 開啟 AWS CLI 並執行下列命令來更新目標，以包含名稱和描述。

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

   ```
   aws ssm update-maintenance-window-target \
       --window-id "mw-0c50858d01EXAMPLE" \
       --window-target-id "e32eecb2-646c-4f4b-8ed1-205fbEXAMPLE" \
       --name "My-Maintenance-Window-Target" \
       --description "Description for my maintenance window target"
   ```

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

   ```
   aws ssm update-maintenance-window-target ^
       --window-id "mw-0c50858d01EXAMPLE" ^
       --window-target-id "e32eecb2-646c-4f4b-8ed1-205fbEXAMPLE" ^
       --name "My-Maintenance-Window-Target" ^
       --description "Description for my maintenance window target"
   ```

------

   系統會傳回與以下相似的資訊。

   ```
   {
       "WindowId": "mw-0c50858d01EXAMPLE",
       "WindowTargetId": "e32eecb2-646c-4f4b-8ed1-205fbEXAMPLE",
       "Targets": [
           {
               "Key": "InstanceIds",
               "Values": [
                   "i-02573cafcfEXAMPLE"
               ]
           }
       ],
       "Name": "My-Maintenance-Window-Target",
       "Description": "Description for my maintenance window target"
   }
   ```

1. 執行以下命令來使用 `replace` 選項移除描述欄位，並新增額外的目標。移除描述欄位，因為更新後不包括此欄位 (空值)。請確定已指定一個額外的執行個體，此節點已設定為與 Systems Manager 搭配使用。

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

   ```
   aws ssm update-maintenance-window-target \
       --window-id "mw-0c50858d01EXAMPLE" \
       --window-target-id "d208dedf-3f6b-41ff-ace8-8e751EXAMPLE" \
       --targets "Key=InstanceIds,Values=i-02573cafcfEXAMPLE,i-0471e04240EXAMPLE" \
       --name "My-Maintenance-Window-Target" \
       --replace
   ```

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

   ```
   aws ssm update-maintenance-window-target ^
       --window-id "mw-0c50858d01EXAMPLE" ^
       --window-target-id "d208dedf-3f6b-41ff-ace8-8e751EXAMPLE" ^
       --targets "Key=InstanceIds,Values=i-02573cafcfEXAMPLE,i-0471e04240EXAMPLE" ^
       --name "My-Maintenance-Window-Target" ^
       --replace
   ```

------

   系統會傳回與以下相似的資訊。

   ```
   {
       "WindowId": "mw-0c50858d01EXAMPLE",
       "WindowTargetId": "e32eecb2-646c-4f4b-8ed1-205fbEXAMPLE",
       "Targets": [
           {
               "Key": "InstanceIds",
               "Values": [
                   "i-02573cafcfEXAMPLE",
                   "i-0471e04240EXAMPLE"
               ]
           }
       ],
       "Name": "My-Maintenance-Window-Target"
   }
   ```

1. `start-date` 允許您延遲啟用維護時段直到指定的未來日期。`end-date` 選項可讓您設定不再執行維護時段的未來日期和時間點。以 ISO-8601 Extended 格式指定選項。

   執行以下命令，來指定定期排定維護時段執行的日期和時間範圍。

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

   ```
   aws ssm update-maintenance-window \
       --window-id "mw-0c50858d01EXAMPLE" \
       --start-date "2020-10-01T10:10:10Z" \
       --end-date "2020-11-01T10:10:10Z"
   ```

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

   ```
   aws ssm update-maintenance-window ^
       --window-id "mw-0c50858d01EXAMPLE" ^
       --start-date "2020-10-01T10:10:10Z" ^
       --end-date "2020-11-01T10:10:10Z"
   ```

------

1. 執行下列命令以更新 Run Command 任務
**提示**  
如果您的目標是適用於 Windows Server 的 Amazon Elastic Compute Cloud (Amazon EC2) 執行個體，則將下列命令中的 `df` 變更為 `ipconfig`，以及 `AWS-RunShellScript`變更為 `AWS-RunPowerShellScript`。

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

   ```
   aws ssm update-maintenance-window-task \
       --window-id "mw-0c50858d01EXAMPLE" \
       --window-task-id "4f7ca192-7e9a-40fe-9192-5cb15EXAMPLE" \
       --targets "Key=WindowTargetIds,Values=e32eecb2-646c-4f4b-8ed1-205fbEXAMPLE" \
       --task-arn "AWS-RunShellScript" \
       --service-role-arn "arn:aws:iam::account-id:role/MaintenanceWindowsRole" \
       --task-invocation-parameters "RunCommand={Comment=Revising my Run Command task,Parameters={commands=df}}" \
       --priority 1 --max-concurrency 10 --max-errors 4 \
       --name "My-Task-Name" --description "A description for my Run Command task"
   ```

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

   ```
   aws ssm update-maintenance-window-task ^
       --window-id "mw-0c50858d01EXAMPLE" ^
       --window-task-id "4f7ca192-7e9a-40fe-9192-5cb15EXAMPLE" ^
       --targets "Key=WindowTargetIds,Values=e32eecb2-646c-4f4b-8ed1-205fbEXAMPLE" ^
       --task-arn "AWS-RunShellScript" ^
       --service-role-arn "arn:aws:iam::account-id:role/MaintenanceWindowsRole" ^
       --task-invocation-parameters "RunCommand={Comment=Revising my Run Command task,Parameters={commands=df}}" ^
       --priority 1 --max-concurrency 10 --max-errors 4 ^
       --name "My-Task-Name" --description "A description for my Run Command task"
   ```

------

   系統會傳回與以下相似的資訊。

   ```
   {
       "WindowId": "mw-0c50858d01EXAMPLE",
       "WindowTaskId": "4f7ca192-7e9a-40fe-9192-5cb15EXAMPLE",
       "Targets": [
           {
               "Key": "WindowTargetIds",
               "Values": [
                   "e32eecb2-646c-4f4b-8ed1-205fbEXAMPLE"
               ]
           }
       ],
       "TaskArn": "AWS-RunShellScript",
       "ServiceRoleArn": "arn:aws:iam::111122223333:role/MaintenanceWindowsRole",
       "TaskParameters": {},
       "TaskInvocationParameters": {
           "RunCommand": {
               "Comment": "Revising my Run Command task",
               "Parameters": {
                   "commands": [
                       "df"
                   ]
               }
           }
       },
       "Priority": 1,
       "MaxConcurrency": "10",
       "MaxErrors": "4",
       "Name": "My-Task-Name",
       "Description": "A description for my Run Command task"
   }
   ```

1. 調整並執行下列命令以更新 Lambda 任務。

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

   ```
   aws ssm update-maintenance-window-task \
       --window-id mw-0c50858d01EXAMPLE \
       --window-task-id 4f7ca192-7e9a-40fe-9192-5cb15EXAMPLE \
       --targets "Key=WindowTargetIds,Values=e32eecb2-646c-4f4b-8ed1-205fbEXAMPLE" \
       --task-arn "arn:aws:lambda:region:111122223333:function:SSMTestLambda" \
       --service-role-arn "arn:aws:iam:account-id:role/MaintenanceWindowsRole" \
       --task-invocation-parameters '{"Lambda":{"Payload":"{\"InstanceId\":\"{{RESOURCE_ID}}\",\"targetType\":\"{{TARGET_TYPE}}\"}"}}' \
       --priority 1 --max-concurrency 10 --max-errors 5 \
       --name "New-Lambda-Task-Name" \
       --description "A description for my Lambda task"
   ```

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

   ```
   aws ssm update-maintenance-window-task ^
       --window-id mw-0c50858d01EXAMPLE ^
       --window-task-id 4f7ca192-7e9a-40fe-9192-5cb15EXAMPLE ^
       --targets "Key=WindowTargetIds,Values=e32eecb2-646c-4f4b-8ed1-205fbEXAMPLE" ^
       --task-arn --task-arn "arn:aws:lambda:region:111122223333:function:SSMTestLambda" ^
       --service-role-arn "arn:aws:iam:account-id:role/MaintenanceWindowsRole" ^
       --task-invocation-parameters '{"Lambda":{"Payload":"{\"InstanceId\":\"{{RESOURCE_ID}}\",\"targetType\":\"{{TARGET_TYPE}}\"}"}}' ^
       --priority 1 --max-concurrency 10 --max-errors 5 ^
       --name "New-Lambda-Task-Name" ^
       --description "A description for my Lambda task"
   ```

------

   系統會傳回與以下相似的資訊。

   ```
   {
       "WindowId": "mw-0c50858d01EXAMPLE",
       "WindowTaskId": "4f7ca192-7e9a-40fe-9192-5cb15EXAMPLE",
       "Targets": [
           {
               "Key": "WindowTargetIds",
               "Values": "e32eecb2-646c-4f4b-8ed1-205fbEXAMPLE"
           }
       ],
       "TaskArn": "arn:aws:lambda:us-east-2:111122223333:function:SSMTestLambda",
       "ServiceRoleArn": "arn:aws:iam::111122223333:role/MaintenanceWindowsRole",
       "TaskParameters": {},
       "TaskInvocationParameters": {
           "Lambda": {
               "Payload": "e30="
           }
       },
       "Priority": 1,
       "MaxConcurrency": "10",
       "MaxErrors": "5",
       "Name": "New-Lambda-Task-Name",
       "Description": "A description for my Lambda task"
   }
   ```

1. 如果您更新的是 Step Functions 任務，請調整和執行以下命令來更新其 task-invocation-parameters。

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

   ```
   aws ssm update-maintenance-window-task \
       --window-id "mw-0c50858d01EXAMPLE" \
       --window-task-id "4f7ca192-7e9a-40fe-9192-5cb15EXAMPLE" \
       --targets "Key=WindowTargetIds,Values=e32eecb2-646c-4f4b-8ed1-205fbEXAMPLE" \
       --task-arn "arn:aws:states:region:execution:SSMStepFunctionTest" \
       --service-role-arn "arn:aws:iam:account-id:role/MaintenanceWindowsRole" \
       --task-invocation-parameters '{"StepFunctions":{"Input":"{\"InstanceId\":\"{{RESOURCE_ID}}\"}"}}' \
       --priority 0 --max-concurrency 10 --max-errors 5 \
       --name "My-Step-Functions-Task" \
       --description "A description for my Step Functions task"
   ```

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

   ```
   aws ssm update-maintenance-window-task ^
       --window-id "mw-0c50858d01EXAMPLE" ^
       --window-task-id "4f7ca192-7e9a-40fe-9192-5cb15EXAMPLE" ^
       --targets "Key=WindowTargetIds,Values=e32eecb2-646c-4f4b-8ed1-205fbEXAMPLE" ^
       --task-arn "arn:aws:states:region:execution:SSMStepFunctionTest" ^
       --service-role-arn "arn:aws:iam:account-id:role/MaintenanceWindowsRole" ^
       --task-invocation-parameters '{"StepFunctions":{"Input":"{\"InstanceId\":\"{{RESOURCE_ID}}\"}"}}' ^
       --priority 0 --max-concurrency 10 --max-errors 5 ^
       --name "My-Step-Functions-Task" ^
       --description "A description for my Step Functions task"
   ```

------

   系統會傳回與以下相似的資訊。

   ```
   {
       "WindowId": "mw-0c50858d01EXAMPLE",
       "WindowTaskId": "4f7ca192-7e9a-40fe-9192-5cb15EXAMPLE",
       "Targets": [
           {
               "Key": "WindowTargetIds",
               "Values": [
                   "e32eecb2-646c-4f4b-8ed1-205fbEXAMPLE"
               ]
           }
       ],
       "TaskArn": "arn:aws:states:us-east-2:111122223333:execution:SSMStepFunctionTest",
       "ServiceRoleArn": "arn:aws:iam::111122223333:role/MaintenanceWindowsRole",
       "TaskParameters": {},
       "TaskInvocationParameters": {
           "StepFunctions": {
               "Input": "{\"instanceId\":\"{{RESOURCE_ID}}\"}"
           }
       },
       "Priority": 0,
       "MaxConcurrency": "10",
       "MaxErrors": "5",
       "Name": "My-Step-Functions-Task",
       "Description": "A description for my Step Functions task"
   }
   ```

1. 執行下列命令替維護時段取消註冊任務。此範例使用 `safe` 參數來判斷任次參考此目標，因此能夠安全的取消註冊。

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

   ```
   aws ssm deregister-target-from-maintenance-window \
       --window-id "mw-0c50858d01EXAMPLE" \
       --window-target-id "e32eecb2-646c-4f4b-8ed1-205fbEXAMPLE" \
       --safe
   ```

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

   ```
   aws ssm deregister-target-from-maintenance-window ^
       --window-id "mw-0c50858d01EXAMPLE" ^
       --window-target-id "e32eecb2-646c-4f4b-8ed1-205fbEXAMPLE" ^
       --safe
   ```

------

   系統會傳回與以下相似的資訊。

   ```
   An error occurred (TargetInUseException) when calling the DeregisterTargetFromMaintenanceWindow operation: 
   This Target cannot be deregistered because it is still referenced in Task: 4f7ca192-7e9a-40fe-9192-5cb15EXAMPLE
   ```

1. 執行以下命令替維護時段取消註冊目標，即使任務參考此目標。您可以使用 `no-safe` 強制取消註冊操作。

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

   ```
   aws ssm deregister-target-from-maintenance-window \
       --window-id "mw-0c50858d01EXAMPLE" \
       --window-target-id "e32eecb2-646c-4f4b-8ed1-205fbEXAMPLE" \
       --no-safe
   ```

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

   ```
   aws ssm deregister-target-from-maintenance-window ^
       --window-id "mw-0c50858d01EXAMPLE" ^
       --window-target-id "e32eecb2-646c-4f4b-8ed1-205fbEXAMPLE" ^
       --no-safe
   ```

------

   系統會傳回與以下相似的資訊。

   ```
   {
       "WindowId": "mw-0c50858d01EXAMPLE",
       "WindowTargetId": "e32eecb2-646c-4f4b-8ed1-205fbEXAMPLE"
   }
   ```

1. 執行下列命令以更新 Run Command 任務 這個範例使用名為 `UpdateLevel` 的 Systems Manager Parameter Store 參數，格式如下：'`{{ssm:UpdateLevel}}`'

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

   ```
   aws ssm update-maintenance-window-task \
       --window-id "mw-0c50858d01EXAMPLE" \
       --window-task-id "4f7ca192-7e9a-40fe-9192-5cb15EXAMPLE" \
       --targets "Key=InstanceIds,Values=i-02573cafcfEXAMPLE"  \
       --task-invocation-parameters "RunCommand={Comment=A comment for my task update,Parameters={UpdateLevel='{{ssm:UpdateLevel}}'}}"
   ```

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

   ```
   aws ssm update-maintenance-window-task ^
       --window-id "mw-0c50858d01EXAMPLE" ^
       --window-task-id "4f7ca192-7e9a-40fe-9192-5cb15EXAMPLE" ^
       --targets "Key=InstanceIds,Values=i-02573cafcfEXAMPLE"  ^
       --task-invocation-parameters "RunCommand={Comment=A comment for my task update,Parameters={UpdateLevel='{{ssm:UpdateLevel}}'}}"
   ```

------

   系統會傳回與以下相似的資訊。

   ```
   {
       "WindowId": "mw-0c50858d01EXAMPLE",
       "WindowTaskId": "4f7ca192-7e9a-40fe-9192-5cb15EXAMPLE",
       "Targets": [
           {
               "Key": "InstanceIds",
               "Values": [
                   "i-02573cafcfEXAMPLE"
               ]
           }
       ],
       "TaskArn": "AWS-RunShellScript",
       "ServiceRoleArn": "arn:aws:iam::111122223333:role/MyMaintenanceWindowServiceRole",
       "TaskParameters": {},
       "TaskInvocationParameters": {
           "RunCommand": {
               "Comment": "A comment for my task update",
               "Parameters": {
                   "UpdateLevel": [
                       "{{ssm:UpdateLevel}}"
                   ]
               }
           }
       },
       "Priority": 10,
       "MaxConcurrency": "1",
       "MaxErrors": "1"
   }
   ```

1. 執行以下命令更新 Automation 任務來替 `task-invocation-parameters` 參數指定 `WINDOW_ID` 和 `WINDOW_TASK_ID` 參數：

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

   ```
   aws ssm update-maintenance-window-task \
       --window-id "mw-0c50858d01EXAMPLE" \
       --window-task-id "4f7ca192-7e9a-40fe-9192-5cb15EXAMPLE" \
       --targets "Key=WindowTargetIds,Values=e32eecb2-646c-4f4b-8ed1-205fbEXAMPLE \
       --task-arn "AutoTestDoc" \
       --service-role-arn "arn:aws:iam:account-id:role/MyMaintenanceWindowServiceRole \
       --task-invocation-parameters "Automation={Parameters={InstanceId='{{RESOURCE_ID}}',initiator='{{WINDOW_ID}}.Task-{{WINDOW_TASK_ID}}'}}" \
       --priority 3 --max-concurrency 10 --max-errors 5
   ```

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

   ```
   aws ssm update-maintenance-window-task ^
       --window-id "mw-0c50858d01EXAMPLE" ^
       --window-task-id "4f7ca192-7e9a-40fe-9192-5cb15EXAMPLE" ^
       --targets "Key=WindowTargetIds,Values=e32eecb2-646c-4f4b-8ed1-205fbEXAMPLE ^
       --task-arn "AutoTestDoc" ^
       --service-role-arn "arn:aws:iam:account-id:role/MyMaintenanceWindowServiceRole ^
       --task-invocation-parameters "Automation={Parameters={InstanceId='{{RESOURCE_ID}}',initiator='{{WINDOW_ID}}.Task-{{WINDOW_TASK_ID}}'}}" ^
       --priority 3 --max-concurrency 10 --max-errors 5
   ```

------

   系統會傳回與以下相似的資訊。

   ```
   {
       "WindowId": "mw-0c50858d01EXAMPLE",
       "WindowTaskId": "4f7ca192-7e9a-40fe-9192-5cb15EXAMPLE",
       "Targets": [
           {
               "Key": "WindowTargetIds",
               "Values": [
                   "e32eecb2-646c-4f4b-8ed1-205fbEXAMPLE"
               ]
           }
       ],
       "TaskArn": "AutoTestDoc",
       "ServiceRoleArn": "arn:aws:iam::111122223333:role/MyMaintenanceWindowServiceRole",
       "TaskParameters": {},
       "TaskInvocationParameters": {
           "Automation": {
               "Parameters": {
                   "multi": [
                       "{{WINDOW_TASK_ID}}"
                   ],
                   "single": [
                       "{{WINDOW_ID}}"
                   ]
               }
           }
       },
       "Priority": 0,
       "MaxConcurrency": "10",
       "MaxErrors": "5",
       "Name": "My-Automation-Task",
       "Description": "A description for my Automation task"
   }
   ```

# 教學課程：使用 刪除維護時段 AWS CLI
<a name="mw-cli-tutorial-delete-mw"></a>

若要刪除您在這些教學中所建立的維護時段，請執行下列命令。

```
aws ssm delete-maintenance-window --window-id "mw-0c50858d01EXAMPLE"
```

系統會傳回與以下相似的資訊。

```
{
   "WindowId":"mw-0c50858d01EXAMPLE"
}
```

# 教學課程：使用主控台建立修補維護時段
<a name="maintenance-window-tutorial-patching"></a>

**重要**  
您可以繼續使用這個舊版主題來建立維護時段，以進行修補。不過，建議您改用修補程式政策。如需詳細資訊，請參閱[Quick Setup中的修補程式政策組態](patch-manager-policies.md)及[使用 Quick Setup 修補程式政策設定組織中執行個體的修補](quick-setup-patch-manager.md)。

為了盡可能降低對伺服器可用性的影響，建議您設定維護時段在不會插斷您商業運作的期間執行修補。

在開始此程序之前 AWS Systems Manager，您必須為 中的Maintenance Windows工具 設定角色和許可。如需詳細資訊，請參閱[設定 Maintenance Windows](setting-up-maintenance-windows.md)。

**建立維護時段以進行修補**

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

1. 在導覽窗格中，選擇 **Maintenance Windows**。

1. 選擇**建立維護時段**。

1. 針對 **Name (名稱)**，輸入名稱，並將其指定為維護時段以修補關鍵與重要的更新。

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

1. 如果您想允許維護時段任務在受管節點上執行 (即使您尚未將這些節點註冊為目標)，請選擇 **Allow unregistered targets** (允許未註冊目標)。

   如果您選擇此選項，即可在向維護時段註冊任務時選擇未註冊的節點 (依據節點 ID)。

   如果您未選擇此選項，則必須在向維護時段註冊任務時選擇先前註冊過的目標。

1. 在 **Schedule (排程)** 區段頂端，使用三個排程選項之一來指定維護時段的排程。

   如需有關建立 Cron/Rate 運算式的詳細資訊，請參閱[參考：Systems Manager 的 Cron 和 Rate 運算式](reference-cron-and-rate-expressions.md)。

1. 針對 **Duration (持續時間)**，輸入維護時段將執行的時數。您指定的值會根據維護時段的開始時間，決定維護時段的特定結束時間。在產生的結束時間減去您在下一個步驟中為 **Stop initiating tasks (停止啟動任務)** 指定的小時數過後，將不允許啟動任何維護時段任務。

   例如，如果維護時段從下午 3 點開始，持續時間為三小時，而 **Stop initiating tasks (停止啟動任務)** 的值為一小時，則在下午 5 點之後無法啟動任何維護時段任務。

1. 針對 **Stop initiating tasks (停止初始任務)**，輸入在維護時段執行結束之前，系統應該停止排程新任務的時數。

1. (選用) 對於 **Window start date** (時段開始日期)，依照 ISO-8601 Extended 格式，指定您希望開始啟用維護時段的日期和時間。這可讓您延遲啟用維護時段，直到指定的未來日期為止。

1. (選用) 對於 **Window end date** (時段結束日期)，依照 ISO-8601 Extended 格式，指定您希望停用維護時段的日期和時間。這可讓您設定不再執行維護時段的未來日期和時間點。

1. (選用) 對於**排程時區**，以網際網路號碼分配局 (IANA) 格式，指定排程的維護時段執行所依據的時區。例如："America/Los\$1Angeles"、"etc/UTC" 或 "Asia/Seoul"。

   如需有關有效格式的詳細資訊，請參閱 IANA 網站上的[時區資料庫有效格式](https://www.iana.org/time-zones)。

1. (選用) 在 **Manage tags (管理標籤)** 區域，將一或多個標籤金鑰名稱/值對套用到維護時段。

   標籤是您指派給資源的選用性中繼資料。標籤允許您以不同的方式 (例如用途、擁有者或環境) 將資源分類。例如，您可能想要標記此維護時段，以識別其執行的任務類型。在這種情況下，您可以指定以下索引鍵名稱/值對：
   + `Key=TaskType,Value=Patching`

1. 選擇**建立維護時段**。

1. 在維護時段清單中，選擇您剛建立的維護時段，然後選擇 **Actions (動作)**、**Register targets (註冊目標)**。

1. (選用) 在 **Maintenance window target details (維護時段目標詳細資訊)** 部分，提供此目標的名稱、描述及擁有者資訊 (您的名稱或別名)。

1. 對於**目標選擇**，選擇**指定執行個體標籤**。

1. 對於**指定執行個體標籤**，輸入標籤鍵和標籤值，以識別要向維護時段註冊的節點，然後選擇**新增**。

1. 選擇 **Register target (註冊目標)**。系統會建立一個維護時段目標。

1. 在您建立的維護時段的詳細資訊頁面中，選擇 **Actions (動作)**、**Register run command task (註冊執行命令任務)**。

1. (選用) 在 **Maintenance window task details (維護時段任務詳細資訊)** 中提供此任務的名稱與描述。

1. 如需 **Command document** (命令文件)，請選擇 `AWS-RunPatchBaseline`。

1. 在 **Task priority (任務優先順序)** 中選擇優先順序。零 (`0`) 是最高的優先順序。

1. 針對 **Targets (目標)**，請在 **Target by (目標依據)** 下，選擇您之前在此程序建立的維護時段目標。

1. 對於**速率控制**：
   + 在**並行**中，指定可同時執行命令的受管節點數目或百分比。
**注意**  
如果您透過指定套用至受管節點的標籤或指定 AWS 資源群組來選取目標，而且您不確定目標的受管節點數量，則透過指定百分比來限制可同時執行文件的目標數量。
   + 在 **Error threshold** (錯誤閾值) 中，指定在特定數目或百分比之節點上的命令失敗之後，停止在其他受管節點上執行命令。例如，如果您指定三個錯誤，則 Systems Manager 會在收到第四個錯誤時停止傳送命令。仍在處理命令的受管節點也可能會傳送錯誤。

1. (選用) 對於 **IAM 服務角色**，請選擇一個角色，以便為 Systems Manager 提供執行維護時段任務時承擔的許可。

   如果您未指定服務角色 ARN，則 Systems Manager 會使用帳戶中的服務連結角色。如果帳戶中不存在適當的 Systems Manager 服務連結角色，則會在成功註冊任務時建立該角色。
**注意**  
為了改善安全狀態，強烈建議您建立自訂政策和自訂服務角色，以便執行維護時段任務。您可以制定政策，僅提供特定維護時段任務所需的許可。如需詳細資訊，請參閱[設定 Maintenance Windows](setting-up-maintenance-windows.md)。

1. (選用) 針對**輸出選項**，若要將命令輸出儲存至檔案，請選取**啟用將輸出寫入 S3** 方塊。在方塊中輸入儲存貯體和字首 (資料夾) 名稱。
**注意**  
授予能力以將資料寫入至 S3 儲存貯體的 S3 許可，會是指派給受管節點之執行個體設定檔的許可，而不是執行此任務之 IAM 使用者的許可。如需詳細資訊，請參閱[設定 Systems Manager 所需的執行個體許可](setup-instance-permissions.md)或[建立混合環境的 IAM 服務角色](hybrid-multicloud-service-role.md)。此外，若指定的 S3 儲存貯體位於不同的 AWS 帳戶內，請驗證與受管節點相關聯的執行個體設定檔或 IAM 服務角色是否具有寫入該儲存貯體的必要許可。

   若要將輸出串流至 Amazon CloudWatch Logs 日誌群組，請選取 **CloudWatch output** (CloudWatch 輸出) 方塊。在方塊中輸入日誌群組名稱。

1. 在 **SNS notifications** (SNS 通知) 區段中，如果您要傳送有關命令執行狀態的通知，請選取 **Enable SNS notifications** (啟用 SNS 通知) 核取方塊。

   如需為 Run Command 設定 Amazon SNS 通知的詳細資訊，請參閱 [使用 Amazon SNS 通知監控 Systems Manager 狀態變更](monitoring-sns-notifications.md)。

1. 對於 **Parameters (參數)**：
   + 在 **Operation (操作)** 中選擇 **Scan (掃描)** 以掃描遺漏的修補程式，或選擇 **Install (安裝)** 以掃描並安裝遺漏的修補程式。
   + 您無需在 **Snapshot Id (快照 ID)** 欄位中輸入任何資訊。此系統會自動產生並提供此參數。
   + 除非您希望 Patch Manager 使用與修補基準不同的修補程式集，否則不需要在 **Install Override List** (安裝覆寫清單) 欄位中輸入任何內容。如需相關資訊，請參閱[參數名稱：`InstallOverrideList`](patch-manager-aws-runpatchbaseline.md#patch-manager-aws-runpatchbaseline-parameters-installoverridelist)。
   + 針對**重新啟動選項**，指定如果在 `Install` 操作期間安裝了修補程式，或是 Patch Manager 偵測到自上次節點重新啟動後安裝的其他修補程式，是否要重新啟動節點。如需相關資訊，請參閱[參數名稱：`RebootOption`](patch-manager-aws-runpatchbaseline.md#patch-manager-aws-runpatchbaseline-parameters-norebootoption)。
   + (選用) 在 **Comment (註解)** 中輸入有關此命令的追蹤註記或提醒。
   + 在 **Timeout (seconds) (逾時 (秒))** 中，輸入系統應等待操作完成的時間，超過此時間將視為失敗。

1. 選擇 **Register run command task** (註冊執行命令任務)。

在維護時段任務完成後，您可以在 Systems Manager 主控台的 [Fleet Manager](fleet-manager.md) 工具中檢視修補程式合規詳細資訊。

您也可以在 [Patch Manager](patch-manager.md) 工具中的**合規報告**索引標籤上檢視合規資訊。

您也可以使用 [DescribePatchGroupState](https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_DescribePatchGroupState.html) 與 [DescribeInstancePatchStatesForPatchGroup](https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_DescribeInstancePatchStatesForPatchGroup.html) API，以檢視合規的詳細資訊。如需有關修補程式合規資料的詳細資訊，請參閱[關於修補程式合規](compliance-about.md#compliance-monitor-patch)。

# 使用維護時段進行修補的排程
<a name="sysman-patch-scheduletasks"></a>

在您設定修補基線 (以及選用的修補程式群組) 之後，即可使用維護時段將修補程式套用至您的節點。維護時段可讓您指定執行修補程式的時間，不中斷商業運作，以降低對伺服器可用性的影響。維護時段的運作方式如下：

1. 建立維護時段，其中包含您修補操作的排程。

1. 選擇維護時段目標，方法是指定 `Patch Group` 或 `PatchGroup` 標籤作為標籤名稱，並指定您已定義 Amazon Elastic Compute Cloud (Amazon EC2) 標籤的任何值，例如例如「Web 伺服器」或「US-EAST-PROD」。(如果您已在 [EC2 執行個體中繼資料中允許標籤](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Using_Tags.html#allow-access-to-tags-in-IMDS)，則必須使用 `PatchGroup`，不留空格。)

1. 建立新的維護時段任務，並指定 `AWS-RunPatchBaseline` 文件。

當您設定任務時，您可以選擇掃描節點，或掃描節點並在其上安裝修補程式。如果您選擇掃描節點，Patch Manager ( AWS Systems Manager中的工具) 將掃描每個節點，並產生遺漏修補程式清單以供您查看。

如果您選擇掃描並安裝修補程式，則 Patch Manager 會掃描每個節點，並將已安裝修補程式清單與基準中的已核准修補程式清單進行比較。Patch Manager 會識別遺漏的修補程式，然後下載並安裝所有遺漏且已核准的修補程式。

如果您要執行一次性掃描或進行安裝以修復問題，可使用 Run Command 直接呼叫 `AWS-RunPatchBaseline` 文件。

**重要**  
安裝修補程式之後，Systems Manager 將重新啟動每個節點。需要重新啟動是為了確保修補程式已正確安裝，並確保系統未讓節點處於可能不良的狀態。(例外：如果 `AWS-RunPatchBaseline` 文件中的 `RebootOption` 參數設為 `NoReboot`，受管節點不會在 Patch Manager 執行之後重新啟動。如需詳細資訊，請參閱 [參數名稱：`RebootOption`](patch-manager-aws-runpatchbaseline.md#patch-manager-aws-runpatchbaseline-parameters-norebootoption)。) 

# 註冊維護時段任務時使用虛擬參數
<a name="maintenance-window-tasks-pseudo-parameters"></a>

在 Maintenance Windows ( AWS Systems Manager中的工具) 中註冊任務時，可以指定四種任務類型特有的參數。(在 CLI 命令中，這些都是使用 `--task-invocation-parameters` 選項提供。)

 您也可以使用「虛擬參數」**語法來參考特定的值，例如 `{{RESOURCE_ID}}`、`{{TARGET_TYPE}}` 和 `{{WINDOW_TARGET_ID}}`。維護時段任務執行時，它會傳遞正確的值，而不是虛擬參數預留位置。本主題後面的[支援的虛擬參數](#pseudo-parameters)中提供了您可以使用之虛擬參數的完整清單。

**重要**  
對於目標類型 `RESOURCE_GROUP`，視任務所需的 ID 格式而定，您可以在任務執行時選擇使用 `{{TARGET_ID}}` 和 `{{RESOURCE_ID}}` 參考資源。`{{TARGET_ID}}` 會傳回資源的完整 ARN。`{{RESOURCE_ID}}` 只會傳回資源的較短名稱或 ID，如下列範例所示。  
`{{TARGET_ID}}` 格式：`arn:aws:ec2:us-east-1:123456789012:instance/i-02573cafcfEXAMPLE`
`{{RESOURCE_ID}}` 格式：`i-02573cafcfEXAMPLE`
對於目標類型 `INSTANCE`，`{{TARGET_ID}}` 和 `{{RESOURCE_ID}}` 參數都只產生執行個體 ID。如需詳細資訊，請參閱[支援的虛擬參數](#pseudo-parameters)。  
`{{TARGET_ID}}` 和 `{{RESOURCE_ID}}`只能用來將 AWS 資源 IDs 傳遞至 Automation、Lambda 和 Step Functions 任務。這兩個虛擬參數不能與 Run Command 任務搭配使用。

## 虛擬參數範例
<a name="pseudo-parameter-examples"></a>

假設您 AWS Lambda 任務的承載需要依其 ID 參考執行個體。

無論您是使用 `INSTANCE` 或 `RESOURCE_GROUP` 維護時段目標，都可以使用 `{{RESOURCE_ID}}` 虛擬參數加以實現。例如：

```
"TaskArn": "arn:aws:lambda:us-east-2:111122223333:function:SSMTestFunction",
    "TaskType": "LAMBDA",
    "TaskInvocationParameters": {
        "Lambda": {
            "ClientContext": "ew0KICAi--truncated--0KIEXAMPLE",
            "Payload": "{ \"instanceId\": \"{{RESOURCE_ID}}\" }",
            "Qualifier": "$LATEST"
        }
    }
```

如果除了 Amazon Elastic Compute Cloud (Amazon EC2) 執行個體之外，您的 Lambda 任務還要針對其他受支援的目標類型執行 (例如 Amazon DynamoDB 資料表)，則可以使用相同的語法，`{{RESOURCE_ID}}` 只會產生資料表的名稱。但是，如果您需要資料表的完整 ARN，請使用 `{{TARGET_ID}}`，如下列範例所示。

```
"TaskArn": "arn:aws:lambda:us-east-2:111122223333:function:SSMTestFunction",
    "TaskType": "LAMBDA",
    "TaskInvocationParameters": {
        "Lambda": {
            "ClientContext": "ew0KICAi--truncated--0KIEXAMPLE",
            "Payload": "{ \"tableArn\": \"{{TARGET_ID}}\" }",
            "Qualifier": "$LATEST"
        }
    }
```

相同的語法適用於定位執行個體或其他資源類型。已將多個資源類型新增至資源群組時，任務會針對每個適當的資源執行。

**重要**  
並非資源群組中包含的所有資源類型都會產生 `{{RESOURCE_ID}}` 參數的值。如需支援的資源類型清單，請參閱[支援的虛擬參數](#pseudo-parameters)。

另一個例子是，若要執行可停止 EC2 執行個體的 Automation 任務，您可將 `AWS-StopEC2Instance` Systems Manager 文件 (SSM 文件) 指定為 `TaskArn` 值，並使用 `{{RESOURCE_ID}}` 虛擬參數：

```
"TaskArn": "AWS-StopEC2Instance",
    "TaskType": "AUTOMATION"
    "TaskInvocationParameters": {
        "Automation": {
            "DocumentVersion": "1",
            "Parameters": {
                "instanceId": [
                    "{{RESOURCE_ID}}"
                ]
            }
        }
    }
```

若要執行複製 Amazon Elastic Block Store (Amazon EBS)磁碟區快照的 Automation 任務，您可以將 `AWS-CopySnapshot` SSM 文件指定為 `TaskArn` 值，並使用 `{{RESOURCE_ID}}` 虛擬參數：

```
"TaskArn": "AWS-CopySnapshot",
    "TaskType": "AUTOMATION"
    "TaskInvocationParameters": {
        "Automation": {
            "DocumentVersion": "1",
            "Parameters": {
                "SourceRegion": "us-east-2",
                "targetType":"RESOURCE_GROUP",
                "SnapshotId": [
                    "{{RESOURCE_ID}}"
                ]
            }
        }
    }
```

## 支援的虛擬參數
<a name="pseudo-parameters"></a>

以下清單說明您可以在 `--task-invocation-parameters` 選項中使用 `{{PSEUDO_PARAMETER}}` 語法指定的虛擬參數。
+ **`WINDOW_ID`**：目標維護時段 ID。
+ **`WINDOW_TASK_ID`**：正在執行的時段任務 ID。
+ **`WINDOW_TARGET_ID`**：包含目標的目標時段的 ID (目標 ID)。
+ **`WINDOW_EXECUTION_ID`**：目前執行時段的 ID。
+ **`TASK_EXECUTION_ID`**：目前執行任務的 ID。
+ **`INVOCATION_ID`**：目前呼叫的 ID。
+ **`TARGET_TYPE`**：目標類型。支援的類型包括 `RESOURCE_GROUP` 和 `INSTANCE`。
+ **`TARGET_ID`**: 

  如果您指定的目標類型為 `INSTANCE`，則 `TARGET_ID` 虛擬參數會由執行個體的 ID 取代。例如 `i-078a280217EXAMPLE`。

  如果您指定的目標類型為 `RESOURCE_GROUP`，則任務執行所參考的值為資源的完整 ARN。例如：`arn:aws:ec2:us-east-1:123456789012:instance/i-078a280217EXAMPLE`。下表提供資源群組中特定資源類型的範例 `TARGET_ID` 值。
**注意**  
`TARGET_ID` 不支援 Run Command 任務。    
[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/systems-manager/latest/userguide/maintenance-window-tasks-pseudo-parameters.html)
+ **`RESOURCE_ID`**：資源群組中所包含資源類型的簡短 ID。下表提供資源群組中特定資源類型的範例 `RESOURCE_ID` 值。
**注意**  
`RESOURCE_ID` 不支援 Run Command 任務。    
[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/systems-manager/latest/userguide/maintenance-window-tasks-pseudo-parameters.html)
**注意**  
如果您指定的 AWS 資源群組包含不會產生`RESOURCE_ID`值的資源類型，且未列在上表中，則不會填入 `RESOURCE_ID` 參數。該資源仍會發生執行呼叫。在這些情況下，請改用 `TARGET_ID` 虛擬參數，這將被取代為資源的完整 ARN。

# 維護時段排程與作用期間選項
<a name="maintenance-windows-schedule-options"></a>

當您建立維護時段時，您必須使用 [Cron 或 Rate 表達式](reference-cron-and-rate-expressions.md)，指定維護時段執行的頻繁程度。或者，您可以指定一段日期範圍，讓維護時段能根據其定期排程來執行，以及該定期排程依循的時區。

不過請注意，該時區選項與開始日期和結束日期選項不互相影響。您指定的任何開始日期和結束日期時間 (包含或不含時區位移) 只能決定維護時段能定期執行的「有效期間」 **。時區選項決定維護時段排程在有效期間「之中」**定期執行的國際時區基準。

**注意**  
您可以使用 ISO-8601 時間戳記格式指定開始和結束日期。例如：`2021-04-07T14:29:00-08:00`  
您可以使用網際網路號碼分配局 (IANA) 格式指定時區。例如，`America/Chicago`、`Europe/Berlin` 或 `Asia/Tokyo`。

**Topics**
+ [範例 1：指定維護時段開始日期](#schedule-example-start-date)
+ [範例 2：指定維護時段開始日期和結束日期](#schedule-example-start-end-date)
+ [範例 3：建立只執行一次的維護時段](#schedule-example-one-time)
+ [範例 4：指定維護時段的排程偏移天數](#schedule-example-schedule-offset)

## 範例 1：指定維護時段開始日期
<a name="schedule-example-start-date"></a>

假設您使用 AWS Command Line Interface (AWS CLI) 建立具有下列選項的維護時段：
+ `--start-date 2021-01-01T00:00:00-08:00`
+ `--schedule-timezone "America/Los_Angeles"`
+ `--schedule "cron(0 09 ? * WED *)"`

例如：

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

```
aws ssm create-maintenance-window \
    --name "My-LAX-Maintenance-Window" \
    --allow-unassociated-targets \
    --duration 3 \
    --cutoff 1 \
    --start-date 2021-01-01T00:00:00-08:00 \
    --schedule-timezone "America/Los_Angeles" \
    --schedule "cron(0 09 ? * WED *)"
```

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

```
aws ssm create-maintenance-window ^
    --name "My-LAX-Maintenance-Window" ^
    --allow-unassociated-targets ^
    --duration 3 ^
    --cutoff 1 ^
    --start-date 2021-01-01T00:00:00-08:00 ^
    --schedule-timezone "America/Los_Angeles" ^
    --schedule "cron(0 09 ? * WED *)"
```

------

這表示維護時段在其指定的開始日期和時間*前*無法第一次執行，也就是美國太平洋時間 2021 年 1 月 1 日星期五的午夜。(此時區比 UTC 時間慢 8 個小時。) 在此情況下，時段期間的開始日期和時間不代表維護時段第一次執行的時間。結合 `--schedule-timezone` 和 `--schedule` 值，代表維護時段會在美國太平洋時區 (IANA 格式的 "America/Los Angeles" (美洲/洛杉磯)) 每週三的上午 9 點執行。啟用期間的第一次執行，會在美國太平洋時間 2021 年 1 月 4 日週三的上午 9 點。

## 範例 2：指定維護時段開始日期和結束日期
<a name="schedule-example-start-end-date"></a>

假設您接下來使用這些選項建立維護時段：
+ `--start-date 2019-01-01T00:03:15+09:00`
+ `--end-date 2019-06-30T00:06:15+09:00`
+ `--schedule-timezone "Asia/Tokyo"`
+ `--schedule "rate(7 days)"`

例如：

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

```
aws ssm create-maintenance-window \
    --name "My-NRT-Maintenance-Window" \
    --allow-unassociated-targets \
    --duration 3 \
    --cutoff 1 \
    --start-date 2019-01-01T00:03:15+09:00 \
    --end-date 2019-06-30T00:06:15+09:00 \
    --schedule-timezone "Asia/Tokyo" \
    --schedule "rate(7 days)"
```

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

```
aws ssm create-maintenance-window ^
    --name "My-NRT-Maintenance-Window" ^
    --allow-unassociated-targets ^
    --duration 3 ^
    --cutoff 1 ^
    --start-date 2019-01-01T00:03:15+09:00 ^
    --end-date 2019-06-30T00:06:15+09:00 ^
    --schedule-timezone "Asia/Tokyo" ^
    --schedule "rate(7 days)"
```

------

此維護時段的啟用期間將會在日本標準時間 2019 年 1 月 1 日的上午 3:15 開始。此維護時段的有效期間會在日本標準時間 2019 年 6 月 30 日星期日的上午 6:15 結束。(此時區比 UTC 時間快 9 個小時)。結合 `--schedule-timezone` 和 `--schedule` 值，代表維護時段會在日本標準時區 (IANA 格式的 "Asia/Tokyo" (亞洲/東京)) 每週二的上午 3:15 執行。這是因為維護時段每七天執行一次，從 1 月 1 日週二上午 3:15 啟用。最後一次執行會在日本標準時間 2019 年 6 月 25 日星期二的上午 3:15。這是已啟用維護時段期間在五天之後結束之前的最後一個週二。

## 範例 3：建立只執行一次的維護時段
<a name="schedule-example-one-time"></a>

現在您使用此選項建立維護時段：
+ `--schedule "at(2020-07-07T15:55:00)"`

例如：

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

```
aws ssm create-maintenance-window \
    --name "My-One-Time-Maintenance-Window" \
    --schedule "at(2020-07-07T15:55:00)" \
    --duration 5 \
    --cutoff 2 \
    --allow-unassociated-targets
```

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

```
aws ssm create-maintenance-window ^
    --name "My-One-Time-Maintenance-Window" ^
    --schedule "at(2020-07-07T15:55:00)" ^
    --duration 5 ^
    --cutoff 2 ^
    --allow-unassociated-targets
```

------

此維護時段只會在 UTC 時間 2020 年 7 月 7 日的下午 3:55 執行一次。維護時段已啟用為視需要執行最多五個小時，但在維護時段期間結束的兩個小時之前都無法啟動新的任務。

## 範例 4：指定維護時段的排程偏移天數
<a name="schedule-example-schedule-offset"></a>

現在您使用此選項建立維護時段：

```
--schedule-offset 2
```

例如：

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

```
aws ssm create-maintenance-window \
    --name "My-Cron-Offset-Maintenance-Window" \
    --schedule "cron(0 30 23 ? * TUE#3 *)" \
    --duration 4 \
    --cutoff 1 \
    --schedule-offset 2 \
    --allow-unassociated-targets
```

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

```
aws ssm create-maintenance-window ^
    --name "My-Cron-Offset-Maintenance-Window" ^
    --schedule "cron(0 30 23 ? * TUE#3 *)" ^
    --duration 4 ^
    --cutoff 1 ^
    --schedule-offset 2 ^
    --allow-unassociated-targets
```

------

排程偏移是在執行維護時段之前，在 CRON 表達式所指定的日期和時間之後等待的天數。

在上述範例中，CRON 表達式會排定維護時段，在每個月的第三個週二晚上 11:30 執行：

```
--schedule "cron(0 30 23 ? * TUE#3 *)
```

但是，包括 `--schedule-offset 2` 表示維護時段將在每個月的第三個星期二「後」**兩天的晚上 11:30 執行。

僅 CRON 表達式支援排程偏移。

**詳細資訊**  
+ [參考：Systems Manager 的 Cron 和 Rate 運算式](reference-cron-and-rate-expressions.md)
+ [使用主控台建立維護時段](sysman-maintenance-create-mw.md)
+ [教學課程：使用 建立和設定維護時段 AWS CLI](maintenance-windows-cli-tutorials-create.md)
+ 《*AWS Systems Manager API 參考*》中的 [CreateMaintenanceWindow](https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_CreateMaintenanceWindow.html)
+ [https://docs.aws.amazon.com/cli/latest/reference/ssm/create-maintenance-window.html](https://docs.aws.amazon.com/cli/latest/reference/ssm/create-maintenance-window.html) 在 *AWS Systems Manager AWS CLI 命令參考的 區段中*
+ IANA 網站上的[時區資料庫](https://www.iana.org/time-zones)

# 註冊不含目標的維護時段任務
<a name="maintenance-windows-targetless-tasks"></a>

對於建立的每個維護時段，您可以指定執行維護時段時要執行的一或多個任務。在大多數情況下，您必須指定要在其中執行任務的資源或目標。但是，在某些情況下，您不需要在任務中明確指定目標。

必須為維護時段 Systems Manager Run Command 類型任務指定一或多個目標。根據任務的性質，其他維護時段任務類型 (Systems Manager Automation AWS Lambda和 AWS Step Functions) 的目標為選用。

對於 Lambda 和 Step Functions 任務類型，是否需要目標取決於您建立的函數或狀態機的內容。

**注意**  
當任務已註冊目標 AWS Lambda時，自動化和 AWS Step Functions 任務會從資源群組和標籤解析目標，並為每個已解析的資源傳送一個調用，這會導致多個任務調用。例如，假設您只需要對在包含多個執行個體的資源群組中註冊的 Lambda 任務進行一次調用。在此情況下，如果您在 AWS 管理主控台中工作，請選擇**註冊 Lambda 任務**或**編輯 Lambda 任務**頁面中的**不需要任務目標**選項。如果您使用 AWS CLI 命令，請勿在執行 [https://docs.aws.amazon.com/cli/latest/reference/ssm/register-task-with-maintenance-window.html](https://docs.aws.amazon.com/cli/latest/reference/ssm/register-task-with-maintenance-window.html) 命令或 [https://docs.aws.amazon.com/cli/latest/reference/ssm/update-maintenance-window-task.html](https://docs.aws.amazon.com/cli/latest/reference/ssm/update-maintenance-window-task.html) 命令時使用 `--targets` 參數指定目標。

在許多情況下，您不需要明確指定自動化任務的目標。例如，假設您正在建立 Automation 類型任務來使用 `AWS-UpdateLinuxAmi` Runbook 更新 Linux 的 Amazon Machine Image (AMI)。當任務執行時，AMI 已更新為可用的最新版本 Linux 發行版本套件和 Amazon 軟體。從 AMI 建立的新執行個體已經安裝這些更新。因為在 Runbook 的輸入參數中指定了要更新的 AMI ID，所以不需要在維護時段任務中再次指定目標。

同樣地，假設您使用 AWS Command Line Interface (AWS CLI) 來註冊使用 `AWS-RestartEC2Instance` Runbook 的維護時段自動化任務。因為要重新啟動的節點是在 `--task-invocation-parameters` 參數中，所以您不需要指定 `--targets` 選項。

**注意**  
對於未指定目標的維護時段任務，您無法提供 `--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)) 中回報。這些值不會影響任務的執行，可以忽略。

下列範例示範針對無目標維護時段任務，省略 `--targets`、`--max-errors` 和 `--max-concurrency` 選項。

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

```
aws ssm register-task-with-maintenance-window \
    --window-id "mw-ab12cd34eEXAMPLE" \
    --service-role-arn "arn:aws:iam::123456789012:role/MaintenanceWindowAndAutomationRole" \
    --task-type "AUTOMATION" \
    --name "RestartInstanceWithoutTarget" \
    --task-arn "AWS-RestartEC2Instance" \
    --task-invocation-parameters "{\"Automation\":{\"Parameters\":{\"InstanceId\":[\"i-02573cafcfEXAMPLE\"]}}}" \
    --priority 10
```

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

```
aws ssm register-task-with-maintenance-window ^
    --window-id "mw-ab12cd34eEXAMPLE" ^
    --service-role-arn "arn:aws:iam::123456789012:role/MaintenanceWindowAndAutomationRole" ^
    --task-type "AUTOMATION" ^
    --name "RestartInstanceWithoutTarget" ^
    --task-arn "AWS-RestartEC2Instance" ^
    --task-invocation-parameters "{\"Automation\":{\"Parameters\":{\"InstanceId\":[\"i-02573cafcfEXAMPLE\"]}}}" ^
    --priority 10
```

------

**注意**  
對於 2020 年 12 月 23 日之前註冊的維護時段任務：如果您為任務指定了目標，且不再需要一個目標，您可以使用 Systems Manager 主控台或 [https://docs.aws.amazon.com/cli/latest/reference/ssm/update-maintenance-window-task.html](https://docs.aws.amazon.com/cli/latest/reference/ssm/update-maintenance-window-task.html) AWS CLI 命令更新該任務以移除目標。

**詳細資訊**  
+ [錯誤訊息：「沒有目標的維護時段任務不支援 MaxConcurrency 值」和「沒有目標的維護時段任務不支援 MaxErrors 值」](troubleshooting-maintenance-windows.md#maxconcurrency-maxerrors-not-supported)

# 對維護時段進行故障診斷
<a name="troubleshooting-maintenance-windows"></a>

使用以下資訊以協助您對維護時段的問題進行故障診斷。

**Topics**
+ [編輯任務錯誤：在可編輯維護時段任務的頁面上，IAM 角色清單傳回錯誤訊息：「我們無法找到為此任務指定的 IAM 維護時段角色。它可能已刪除，也可能尚未建立。」](#maintenance-window-role-troubleshooting)
+ [並非所有維護時段目標都會更新](#targets-not-updated)
+ [任務失敗並顯示任務叫用狀態：「提供的角色未包含正確的 SSM 許可。」](#incorrect-ssm-permissions)
+ [任務失敗並顯示錯誤消息：「正在驗證和解決步驟輸入時，步驟失敗」](#step-fails)
+ [錯誤訊息：「沒有目標的維護時段任務不支援 MaxConcurrency 值」和「沒有目標的維護時段任務不支援 MaxErrors 值」](#maxconcurrency-maxerrors-not-supported)

## 編輯任務錯誤：在可編輯維護時段任務的頁面上，IAM 角色清單傳回錯誤訊息：「我們無法找到為此任務指定的 IAM 維護時段角色。它可能已刪除，也可能尚未建立。」
<a name="maintenance-window-role-troubleshooting"></a>

**問題 1**：建立任務後，您最初指定的 AWS Identity and Access Management (IAM) 維護時段角色已刪除。

**Possible fix** (可能的修正)：1) 選取不同的 IAM 維護時段角色 (如果您帳戶中有現有的)，或者建立新的角色，並為任務選取此角色。

**問題 2**：如果任務是使用 AWS Command Line Interface (AWS CLI) AWS Tools for Windows PowerShell或 AWS SDK 建立的，則可能已指定不存在的 IAM 維護時段角色名稱。例如，在建立任務之前，IAM 維護時段角色可能已遭到刪除，或者角色名稱輸入錯誤，例如 **myrole** 而不是 **my-role**。

**Possible fix** (可能的修正)：選取要使用之 IAM 維護時段角色的正確名稱，或建立新的角色，並為任務指定此角色。

## 並非所有維護時段目標都會更新
<a name="targets-not-updated"></a>

**問題：**您注意到維護時段任務並未在維護時段目標的所有資源上執行。例如，在維護時段的執行結果中，該資源的任務會標示為失敗或逾時。

**解決方案：**維護時段任務未在目標資源上執行的最常見原因涉及連線和可用性。例如：
+ Systems Manager 在維護時段操作之前或期間失去資源的連線。
+ 在維護時段操作期間，資源已離線或停用。

您可以等待下一個排定的維護時段時間，在資源上執行任務。您可以在無法使用或離線的資源上手動執行維護時段任務。

## 任務失敗並顯示任務叫用狀態：「提供的角色未包含正確的 SSM 許可。」
<a name="incorrect-ssm-permissions"></a>

**問題**：您已為任務指定維護時段服務角色，但任務無法成功執行，且任務叫用狀態會報告「提供的角色未包含正確的 SSM 許可」。
+ **解決方案**：在 [任務 1：使用主控台為維護時段服務角色建立自訂政策](configuring-maintenance-window-permissions-console.md#create-custom-policy-console) 中，我們提供您可以連接至[自訂維護時段服務角色](configuring-maintenance-window-permissions-console.md#create-custom-role-console)的基本政策。此政策包含許多任務場景所需的許可。不過，由於您可以執行的任務種類繁多，您可能需要在維護時段角色的政策中提供其他許可。

  例如，某些自動化動作適用於 AWS CloudFormation 堆疊。因此，您可能需要為維護時段服務角色的政策新增其他許可：`cloudformation:CreateStack`、`cloudformation:DescribeStacks` 以及 `cloudformation:DeleteStack`。

  另一個例子：Automation Runbook `AWS-CopySnapshot` 需建立 Amazon Elastic Block Store (Amazon EBS) 快照的權限。因此，您可能需要新增許可 `ec2:CreateSnapshot`。

  如需有關 AWS 受管 Automation Runbook 所需角色許可的資訊，請參閱 Automation Runbook [AWS Systems Manager 參考中的 Runbook](https://docs.aws.amazon.com/systems-manager-automation-runbooks/latest/userguide/automation-runbook-reference.html) 說明。

  如需有關 AWS 受管 SSM 文件所需角色許可的資訊，請在文件區段 Systems Manager 主控台中檢閱[文件](https://console.aws.amazon.com//systems-manager/documents)的內容。

  如需有關 Step Functions 任務、Lambda 任務以及自訂 Automation Runbook 和 SSM 文件所需角色許可的資訊，請向這些資源的作者確認許可需求。

## 任務失敗並顯示錯誤消息：「正在驗證和解決步驟輸入時，步驟失敗」
<a name="step-fails"></a>

**問題**：您在任務中使用的 Automation Runbook 或 Systems Manager 命令文件需要您指定輸入，例如 `InstanceId` 或 `SnapshotId`，但未提供值或未正確提供值。
+ **Solution 1** (解決方案 1)：如果您的任務是針對單一資源 (例如單一節點或單一快照)，請在任務的輸入參數中輸入其 ID。
+ **Solution 2** (解決方案 2)：如果您的任務是針對多個資源，例如當您使用 Runbook `AWS-CreateImage` 時，從多個節點建立映像，您可以在輸入參數中使用支援維護時段任務的其中一個虛擬參數來表示命令中的節點 ID。

  以下命令使用 AWS CLI向維護時段註冊 Systems Manager Automation 任務。`--targets` 值表示維護時段目標 ID。此外，即使 `--targets` 參數會指定時段目標 ID，Automation Runbook 的參數需要提供節點 ID。在這種情況下，命令會使用虛擬參數 `{{RESOURCE_ID}}` 作為 `InstanceId` 值。

  **AWS CLI 命令：**

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

  下列範例命令會重新啟動屬於維護時段目標群組且ID 為 e32eecb2-646c-4f4b-8ed1-205fbEXAMPLE 的 Amazon Elastic Compute Cloud (Amazon EC2) 執行個體。

  ```
  aws ssm register-task-with-maintenance-window \
      --window-id "mw-0c50858d01EXAMPLE" \
      --targets Key=WindowTargetIds,Values=e32eecb2-646c-4f4b-8ed1-205fbEXAMPLE \
      --task-arn "AWS-RestartEC2Instance" \
      --service-role-arn arn:aws:iam::123456789012:role/MyMaintenanceWindowServiceRole \
      --task-type AUTOMATION \
      --task-invocation-parameters "Automation={DocumentVersion=5,Parameters={InstanceId='{{RESOURCE_ID}}'}}" \
      --priority 0 --max-concurrency 10 --max-errors 5 --name "My-Restart-EC2-Instances-Automation-Task" \
      --description "Automation task to restart EC2 instances"
  ```

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

  ```
  aws ssm register-task-with-maintenance-window ^
      --window-id "mw-0c50858d01EXAMPLE" ^
      --targets Key=WindowTargetIds,Values=e32eecb2-646c-4f4b-8ed1-205fbEXAMPLE ^
      --task-arn "AWS-RestartEC2Instance" ^
      --service-role-arn arn:aws:iam::123456789012:role/MyMaintenanceWindowServiceRole ^
      --task-type AUTOMATION ^
      --task-invocation-parameters "Automation={DocumentVersion=5,Parameters={InstanceId='{{RESOURCE_ID}}'}}" ^
      --priority 0 --max-concurrency 10 --max-errors 5 --name "My-Restart-EC2-Instances-Automation-Task" ^
      --description "Automation task to restart EC2 instances"
  ```

------

  如需使用維護時段任務之虛擬參數的詳細資訊，請參閱 [註冊維護時段任務時使用虛擬參數](maintenance-window-tasks-pseudo-parameters.md) 和 [任務註冊範例](mw-cli-register-tasks-examples.md#task-examples)。

## 錯誤訊息：「沒有目標的維護時段任務不支援 MaxConcurrency 值」和「沒有目標的維護時段任務不支援 MaxErrors 值」
<a name="maxconcurrency-maxerrors-not-supported"></a>

**問題：**當註冊 Run Command 類型任務時，您必須至少指定一個目標，以執行任務。對於其他任務類型 （自動化和 AWS Step Functions) AWS Lambda，根據任務的性質，目標是選用的。選項 `MaxConcurrency` (同時執行任務的資源數量) 和 `MaxErrors` (在任務失敗之前在目標資源上執行任務的失敗次數) 不需要或不支援未指定目標的維護時段任務。如果在沒有指定任務目標時為這些選項的其中之一指定了值，則系統會產生這些錯誤訊息。

**解決方案**：如果您收到其中一個錯誤，請移除並行和錯誤閾值的值，然後繼續註冊或更新維護時段任務。

如需有關執行未指定目標之任務的詳細資訊，請參閱《*AWS Systems Manager 使用者指南*》中的 [註冊不含目標的維護時段任務](maintenance-windows-targetless-tasks.md)。

# AWS Systems Manager Quick Setup
<a name="systems-manager-quick-setup"></a>

使用 中的Quick Setup工具 AWS Systems Manager，以建議的最佳實務快速設定常用的 Amazon Web Services 服務和功能。 透過自動化常見或建議的任務，Quick Setup簡化了包括 Systems Manager 在內的服務設定。這些任務包括建立必要的 AWS Identity and Access Management (IAM) 執行個體描述檔角色和設定操作最佳實務，例如定期修補程式掃描和庫存收集。使用 Quick Setup 無需付費。但是，根據您設定的服務類型以及使用限制可能會產生費用，而對用於設定服務的服務不會收取任何費用。若要開始使用 Quick Setup，請開啟 [Systems Manager 主控台](https://console.aws.amazon.com/systems-manager/quick-setup)。在導覽窗格中，選擇 **Quick Setup**。

**注意**  
如果您被引向 Quick Setup，以協助您將執行個體設定為由 Systems Manager 管理，則請完成 [使用 Quick Setup 設定 Amazon EC2 主機管理](quick-setup-host-management.md) 中的程序。

## Quick Setup 有哪些優點？
<a name="quick-setup-features"></a>

Quick Setup 的優點包括：
+ **簡化服務與功能組態**

  Quick Setup 會帶您演練設定操作最佳實務，並自動部署這些組態。Quick Setup 儀表板會顯示組態部署狀態的即時檢視。
+ **跨多個帳戶自動部署設定**

  您可以在個別 Quick Setup中使用 AWS 帳戶 ，或跨多個 AWS 帳戶 和 AWS 區域 進行整合 AWS Organizations。跨多個帳戶使用 Quick Setup，有助於確保您的組織維持一致的組態。
+ **消除組態漂移**

  每當使用者對透過 Quick Setup 所做的選擇相衝突的服務或功能進行任何變更，即會發生漂移。Quick Setup 會定期檢查組態漂移並嘗試進行修補。

## 誰應該使用Quick Setup？
<a name="quick-setup-audience"></a>

對於已經擁有所設定服務和功能的經驗，並且想要簡化設定程序的客戶來說，Quick Setup 非常有用。如果您不熟悉 AWS 服務 使用 設定的 Quick Setup，建議您進一步了解 服務。請先檢閱相關使用者指南中的內容，然後再使用 Quick Setup 建立組態。

## Quick Setup 中的 可用性 AWS 區域
<a name="quick-setup-getting-started-regions"></a>

在下文中 AWS 區域，您可以按照 中的設定，或僅針對您選擇的組織帳戶和區域 AWS Organizations，使用整個組織的所有Quick Setup組態類型。您也可以在這些區域中以單一帳戶來使用 Quick Setup。
+ 美國東部 (俄亥俄)
+ 美國東部 (維吉尼亞北部)
+ 美國西部 (加利佛尼亞北部)
+ 美國西部 (奧勒岡)
+ 亞太區域 (孟買)
+ 亞太區域 (首爾)
+ 亞太區域 (新加坡)
+ 亞太地區 (雪梨)
+ 亞太區域 (東京)
+ 加拿大 (中部)
+ 歐洲 (法蘭克福)
+ 歐洲 (斯德哥爾摩)
+ 歐洲 (愛爾蘭)
+ 歐洲 (倫敦)
+ Europe (Paris)
+ 南美洲 (聖保羅)

在下列區域中，個別帳戶僅能使用[主機管理](quick-setup-host-management.md)組態類型：
+ 歐洲 (米蘭)
+ 亞太地區 (香港)
+ Middle East (Bahrain)
+ 中國 (北京)
+ 中國 (寧夏)
+ AWS GovCloud （美國東部）
+ AWS GovCloud （美國西部）

 如需取得 Systems Manager 所有支援的區域之清單，請參閱 *Amazon Web Services 一般參考* 中 [Systems Manager 服務端點](https://docs.aws.amazon.com/general/latest/gr/ssm.html#ssm_region)裡的**區域**直欄。

# Quick Setup 入門
<a name="quick-setup-getting-started"></a>

請使用本主題中的資訊來熟悉 Quick Setup 的使用。

**Topics**
+ [用於 Quick Setup 登入的 IAM 角色和許可](#quick-setup-getting-started-iam)
+ [手動加入，以便透過程式設計方式使用 Quick Setup API](#quick-setup-api-manual-onboarding)

## 用於 Quick Setup 登入的 IAM 角色和許可
<a name="quick-setup-getting-started-iam"></a>

Quick Setup 推出新的主控台體驗和新的 API。現在您可以使用 主控台 AWS CLI CloudFormation、 和 SDKs 與此 API 互動。如果選擇加入新的體驗，則會使用新的 API 重新建立現有的組態。根據帳戶中現有的組態數量，此程序可能需要幾分鐘的時間。

若要使用 Quick Setup 的新主控台，您必須擁有以下動作的許可：

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

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "ssm-quicksetup:*",
                "cloudformation:DescribeStackSetOperation",
                "cloudformation:ListStacks",
                "cloudformation:DescribeStacks",
                "cloudformation:DescribeStackResources",
                "cloudformation:ListStackSetOperations",
                "cloudformation:ListStackInstances",
                "cloudformation:DescribeStackSet",
                "cloudformation:ListStackSets",
                "cloudformation:DescribeStackInstance",
                "cloudformation:DescribeOrganizationsAccess",
                "cloudformation:ActivateOrganizationsAccess",
                "cloudformation:GetTemplate",
                "cloudformation:ListStackSetOperationResults",
                "cloudformation:DescribeStackEvents",
                "cloudformation:UntagResource",
                "ec2:DescribeInstances",
                "ssm:DescribeAutomationExecutions",
                "ssm:GetAutomationExecution",
                "ssm:ListAssociations",
                "ssm:DescribeAssociation",
                "ssm:GetDocument",
                "ssm:ListDocuments",
                "ssm:DescribeDocument",
                "ssm:ListResourceDataSync",
                "ssm:DescribePatchBaselines",
                "ssm:GetPatchBaseline",
                "ssm:DescribeMaintenanceWindows",
                "ssm:DescribeMaintenanceWindowTasks",
                "ssm:GetOpsSummary",
                "organizations:DeregisterDelegatedAdministrator",
                "organizations:DescribeAccount",
                "organizations:DescribeOrganization",
                "organizations:ListDelegatedAdministrators",
                "organizations:ListRoots",
                "organizations:ListParents",
                "organizations:ListOrganizationalUnitsForParent",
                "organizations:DescribeOrganizationalUnit",
                "organizations:ListAWSServiceAccessForOrganization",
                "s3:GetBucketLocation",
                "s3:ListAllMyBuckets",
                "s3:ListBucket",
                "resource-groups:ListGroups",
                "iam:ListRoles",
                "iam:ListRolePolicies",
                "iam:GetRole",
                "iam:CreatePolicy",
                "organizations:RegisterDelegatedAdministrator",
                "organizations:EnableAWSServiceAccess",
                "cloudformation:TagResource"
            ],
            "Resource": "*"
        },
        {
            "Effect": "Allow",
            "Action": [
                "cloudformation:RollbackStack",
                "cloudformation:CreateStack",
                "cloudformation:UpdateStack",
                "cloudformation:DeleteStack"
            ],
            "Resource": [
                "arn:aws:cloudformation:*:*:stack/StackSet-AWS-QuickSetup-*",
                "arn:aws:cloudformation:*:*:stack/AWS-QuickSetup-*",
                "arn:aws:cloudformation:*:*:type/resource/*",
                "arn:aws:cloudformation:*:*:stack/StackSet-SSMQuickSetup"
            ]
        },
        {
            "Effect": "Allow",
            "Action": [
                "cloudformation:CreateStackSet",
                "cloudformation:UpdateStackSet",
                "cloudformation:DeleteStackSet",
                "cloudformation:DeleteStackInstances",
                "cloudformation:CreateStackInstances",
                "cloudformation:StopStackSetOperation"
            ],
            "Resource": [
                "arn:aws:cloudformation:*:*:stackset/AWS-QuickSetup-*",
                "arn:aws:cloudformation:*:*:stackset/SSMQuickSetup",
                "arn:aws:cloudformation:*:*:type/resource/*",
                "arn:aws:cloudformation:*:*:stackset-target/AWS-QuickSetup-*:*"
            ]
        },
        {
            "Effect": "Allow",
            "Action": [
                "iam:CreateRole",
                "iam:DeleteRole",
                "iam:AttachRolePolicy",
                "iam:DetachRolePolicy",
                "iam:GetRolePolicy",
                "iam:PutRolePolicy"
            ],
            "Resource": [
                "arn:aws:iam::*:role/AWS-QuickSetup-*",
                "arn:aws:iam::*:role/service-role/AWS-QuickSetup-*"
            ]
        },
        {
            "Effect": "Allow",
            "Action": "iam:PassRole",
            "Resource": "arn:aws:iam::111122223333:role/AWS-QuickSetup-*",
            "Condition": {
                "StringEquals": {
	            "iam:PassedToService": [
	                "ssm-quicksetup.amazonaws.com",
	                "cloudformation.amazonaws.com"
	            ]
                }
            }
        },
        {
            "Effect": "Allow",
            "Action": [
                "ssm:DeleteAssociation",
                "ssm:CreateAssociation",
                "ssm:StartAssociationsOnce"
            ],
            "Resource": "*"
        },
        {
            "Effect": "Allow",
            "Action": "ssm:StartAutomationExecution",
            "Resource": [
                "arn:aws:ssm:*:*:document/AWS-EnableExplorer",
                "arn:aws:ssm:*:*:automation-execution/*"
            ]
        },
        {
            "Effect": "Allow",
            "Action": [
                "ssm:GetOpsSummary",
                "ssm:CreateResourceDataSync",
                "ssm:UpdateResourceDataSync"
            ],
            "Resource": "arn:aws:ssm:*:*:resource-data-sync/AWS-QuickSetup-*"
        },
        {
            "Effect": "Allow",
            "Action": [
                "iam:CreateServiceLinkedRole"
            ],
            "Condition": {
                "StringEquals": {
                    "iam:AWSServiceName": [
                        "accountdiscovery.ssm.amazonaws.com",
                        "ssm.amazonaws.com",
                        "ssm-quicksetup.amazonaws.com",
                        "stacksets.cloudformation.amazonaws.com"
                    ]
                }
            },
            "Resource": "*"
        },
        {
            "Effect": "Allow",
            "Action": [
                "iam:CreateServiceLinkedRole"
            ],
            "Resource": "arn:aws:iam::*:role/aws-service-role/stacksets.cloudformation.amazonaws.com/AWSServiceRoleForCloudFormationStackSetsOrgAdmin"
        }
    ]
}
```

------

若要將使用者限制為唯讀許可，則僅允許 Quick Setup API 的 `ssm-quicksetup:List*` 和 `ssm-quicksetup:Get*` 操作。

在加入期間， 會代表您Quick Setup建立下列 AWS Identity and Access Management (IAM) 角色：
+ `AWS-QuickSetup-LocalExecutionRole`：授予 CloudFormation 許可，以便使用任何範本 (不包括修補程式政策範本)，以及建立必要的資源。
+ `AWS-QuickSetup-LocalAdministrationRole` – 准許 AWS CloudFormation 擔任 `AWS-QuickSetup-LocalExecutionRole`。
+ `AWS-QuickSetup-PatchPolicy-LocalExecutionRole` – 准許 AWS CloudFormation 使用修補程式政策範本，並建立必要的資源。
+ `AWS-QuickSetup-PatchPolicy-LocalAdministrationRole` – 准許 AWS CloudFormation 擔任 `AWS-QuickSetup-PatchPolicy-LocalExecutionRole`。

如果您要加入管理帳戶 - 您用來在其中建立組織的帳戶 AWS Organizations-Quick Setup 也會代表您建立下列角色：
+ `AWS-QuickSetup-SSM-RoleForEnablingExplorer` – 授予 `AWS-EnableExplorer` 自動化 Runbook 許可。`AWS-EnableExplorer` Runbook 會設定 Systems Manager 中的Explorer工具 ，以顯示多個 AWS 帳戶 和 的資訊 AWS 區域。
+ `AWSServiceRoleForAmazonSSM` – 服務連結角色，授予 Systems Manager 管理和使用 AWS 之資源的存取權。
+ `AWSServiceRoleForAmazonSSM_AccountDiscovery` – 服務連結角色，授予 Systems Manager 在同步資料時呼叫 AWS 服務 以探索 AWS 帳戶 資訊的許可。如需詳細資訊，請參閱[使用 角色來收集 OpsCenter和 AWS 帳戶 的資訊 Explorer](using-service-linked-roles-service-action-2.md)。

登入管理帳戶時，Quick Setup 會在 AWS Organizations 與 CloudFormation 之間啟用受信任存取，以跨組織部署 Quick Setup 組態。若要啟用受信任存取，您的管理帳戶必須擁有管理員許可。登入後，您不再需要管理員許可。如需詳細資訊，請參閱[啟用 Organizations 的受信任存取](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/stacksets-orgs-enable-trusted-access.html)。

如需 AWS Organizations 帳戶類型的相關資訊，請參閱*AWS Organizations 《 使用者指南*》中的[AWS Organizations 術語和概念](https://docs.aws.amazon.com/organizations/latest/userguide/orgs_getting-started_concepts.html)。

**注意**  
Quick Setup 使用 CloudFormation StackSets 跨 AWS 帳戶 和 區域部署您的組態。如果目標帳戶數目乘以區域數目得出的結果超過 10,000，則組態無法部署。我們建議您審視您的使用案例，並建立使用較少目標的組態，以因應貴組織的成長。堆疊執行個體不會部署至您組織的管理帳戶。如需詳細資訊，請參閱[建立具有服務受管許可的堆疊集時的考量](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/stacksets-getting-started-create.html?icmpid=docs_cfn_console#stacksets-orgs-considerations)。

## 手動加入，以便透過程式設計方式使用 Quick Setup API
<a name="quick-setup-api-manual-onboarding"></a>

如果透過主控台來使用 Quick Setup，此服務會為您處理加入步驟。如果您計劃使用 SDKs或 AWS CLI 來使用 Quick Setup API，您仍然可以使用 主控台來完成入門步驟，因此您不需要手動執行這些步驟。不過，有些客戶需要透過程式設計方式完成 Quick Setup 的加入步驟，無需與主控台互動。如果此方法符合使用案例，則您必須完成下列步驟。所有這些步驟都必須從您的 AWS Organizations 管理帳戶完成。

**完成 Quick Setup 的手動加入**

1.  CloudFormation 使用 Organizations 啟用 的受信任存取。這為管理帳戶提供為組織建立和管理 StackSets 所需的許可。您可以使用 CloudFormation的 `ActivateOrganizationsAccess` API 動作來完成此步驟。如需詳細資訊，請參閱《AWS CloudFormation API 參考》**中的 [ActivateOrganizationsAccess](https://docs.aws.amazon.com/AWSCloudFormation/latest/APIReference/API_ActivateOrganizationsAccess.html)。

1. 啟用 Systems Manager 與 Organizations 的整合。這可讓 Systems Manager 在組織的所有帳戶中建立服務連結角色。這也允許 Systems Manager 在組織及其帳戶中代表您執行操作。您可以使用 AWS Organizations的 `EnableAWSServiceAccess` API 動作來完成此步驟。Systems Manager 的服務主體為 `ssm.amazonaws.com`。如需詳細資訊，請參閱《AWS Organizations API 參考》**中的 [EnableAWSServiceAccess](https://docs.aws.amazon.com/organizations/latest/APIReference/API_EnableAWSServiceAccess.html)。

1. 為 Explorer 建立必要的 IAM 角色。這可讓 Quick Setup 為組態建立儀表板，便於您檢視部署和關聯狀態。建立 IAM 角色，以及連接 `AWSSystemsManagerEnableExplorerExecutionPolicy` 受管政策。修改角色的信任政策以符合下列條件。把每個*帳戶 ID* 取代為您的資訊。

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

****  

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

------

1. 為 Explorer 更新 Quick Setup 的服務設定。您可以使用 Quick Setup 的 `UpdateServiceSettings` API 動作來完成此步驟。指定您在上一個步驟中為 `ExplorerEnablingRoleArn` 請求參數建立的 IAM 角色 ARN。如需詳細資訊，請參閱《Quick Setup API 參考》**中的 [UpdateServiceSettings](https://docs.aws.amazon.com/quick-setup/latest/APIReference/API_UpdateServiceSettings.html)。

1. 建立 CloudFormation StackSets 要使用的必要 IAM 角色。您必須建立*執行*角色和*管理*角色。

   1. 建立執行角色。執行角色應至少連接其中一個 `AWSQuickSetupDeploymentRolePolicy` 或 `AWSQuickSetupPatchPolicyDeploymentRolePolicy` 受管政策。如果您只是要建立修補程式政策組態，則可以使用 `AWSQuickSetupPatchPolicyDeploymentRolePolicy` 受管政策。所有其他組態都使用 `AWSQuickSetupDeploymentRolePolicy` 政策。修改角色的信任政策以符合下列條件。將每個*帳戶 ID* 和*管理角色名稱*取代為您的資訊。

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

****  

      ```
      {
          "Version":"2012-10-17",		 	 	 
          "Statement": [
              {
                  "Effect": "Allow",
                  "Principal": {
                      "AWS": "arn:aws:iam::111122223333:role/administration role name"
                  },
                  "Action": "sts:AssumeRole"
              }
          ]
      }
      ```

------

   1. 建立管理角色。此許可政策必須符合下列條件。將每個*帳戶 ID* 和*執行角色名稱*取代為您的資訊。

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

****  

      ```
      {
          "Version":"2012-10-17",		 	 	 
          "Statement": [
              {
                  "Action": [
                      "sts:AssumeRole"
                  ],
                  "Resource": "arn:*:iam::111122223333:role/execution role name",
                  "Effect": "Allow"
              }
          ]
      }
      ```

------

      修改角色的信任政策以符合下列條件。把每個*帳戶 ID* 取代為您的資訊。

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

****  

      ```
      {
          "Version":"2012-10-17",		 	 	 
          "Statement": [
              {
                  "Effect": "Allow",
                  "Principal": {
                      "Service": "cloudformation.amazonaws.com"
                  },
                  "Action": "sts:AssumeRole",
                  "Condition": {
                      "StringEquals": {
                          "aws:SourceAccount": "111122223333"
                      },
                      "ArnLike": {
                          "aws:SourceArn": "arn:aws:cloudformation:*:111122223333:stackset/AWS-QuickSetup-*"
                      }
                  }
              }
          ]
      }
      ```

------

# Systems Manager 的擔任角色組態
<a name="quick-setup-assume-role"></a>

## 若要建立 Systems Manager Quick Setup 的擔任角色：
<a name="create-assume-role"></a>

Systems Manager Quick Setup 需要一個角色，允許 Systems Manager 在您的帳戶中安全地執行動作。此角色會授予 Systems Manager 在執行個體上執行命令，以及代表您設定 EC2 執行個體、IAM 角色和其他 Systems Manager 資源所需的許可。

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

1. 在導覽窗格中，選擇**政策**，然後選擇**建立政策**

1. 使用以下 JSON 新增`SsmOnboardingInlinePolicy`政策。（此政策會啟用必要動作，以便將執行個體描述檔許可連接至您指定的執行個體。 例如，允許建立執行個體描述檔，並將其與 EC2 執行個體建立關聯）。

1. 完成後，在導覽窗格中，選擇**角色**，然後選擇**建立角色**。

1. 對於**信任的實體類型**，將其保留為預設值 （服務）。

1. 在**使用案例中**，選擇 **Systems Manager**，然後選擇**下一步**。

1. 在**新增許可**頁面上：

1. 新增`SsmOnboardingInlinePolicy`政策

1. 選擇**下一步**

1. 針對**角色名稱**，輸入描述性名稱 （例如 `AmazonSSMRoleForAutomationAssumeQuickSetup`)。

1. （選用） 新增標籤以協助識別和組織角色。

1. 選擇建**立角色**。

**重要**  
角色必須包含與 的信任關係`ssm.amazonaws.com`。當您在步驟 4 中選取 Systems Manager 做為服務時，會自動設定此選項。

建立角色之後，您可以在設定快速設定時選取該角色。此角色可讓 Systems Manager 管理 EC2 執行個體、IAM 角色和其他 Systems Manager 資源，並代表您執行命令，同時透過特定的有限許可來維護安全性。

## 許可政策
<a name="permissions-policies"></a>

**`SsmOnboardingInlinePolicy`**  
下列政策定義 Systems Manager Quick Setup 的許可：

```
{
    "Version": "2012-10-17" 		 	 	 ,
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "iam:CreateInstanceProfile",
                "iam:ListInstanceProfilesForRole",
                "ec2:DescribeIamInstanceProfileAssociations",
                "iam:GetInstanceProfile",
                "iam:AddRoleToInstanceProfile"
            ],
            "Resource": "*"
        },
        {
            "Effect": "Allow",
            "Action": [
                "ec2:AssociateIamInstanceProfile"
            ],
            "Resource": "arn:aws:ec2:*:*:instance/*",
            "Condition": {
                "Null": {
                    "ec2:InstanceProfile": "true"
                },
                "ArnLike": {
                    "ec2:NewInstanceProfile": "arn:aws:iam::*:instance-profile/[INSTANCE_PROFILE_ROLE_NAME]"
                }
            }
        },
        {
            "Effect": "Allow",
            "Action": "iam:PassRole",
            "Resource": "arn:aws:iam::*:role/[INSTANCE_PROFILE_ROLE_NAME]",
            "Condition": {
                "StringEquals": {
                    "iam:PassedToService": "ec2.amazonaws.com"
                }
            }
        }
    ]
        }
```

**信任關係**  
*這會透過上述步驟自動新增*

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

# 使用 Quick Setup 的委派管理員
<a name="quick-setup-delegated-administrator"></a>

註冊 的委派管理員帳戶後Quick Setup，在該帳戶中具有適當許可的使用者可以建立、更新、檢視和刪除以 AWS Organizations 結構中組織單位為目標的組態管理員。此委派管理員帳戶也可以管理由組織的管理帳戶建立的組態管理員。

Organizations 中的管理帳戶可以在組織中將一個帳戶註冊為委派管理員。如果您將帳戶註冊為 Quick Setup 的委派管理員，由於部署和監控 Quick Setup 組態時需要使用這些服務，因而此帳戶也會自動成為 AWS CloudFormation StackSets 和 Systems Manager Explorer 的委派管理員。

**注意**  
目前，Quick Setup 委派管理員不支援修補程式政策組態類型。組織的修補程式政策組態必須在組織的管理帳戶中建立和維護。如需詳細資訊，請參閱[建立修補程式政策](quick-setup-patch-manager.md#create-patch-policy)。

下列主題說明如何註冊和取消註冊 Quick Setup 的委派管理員。

**Topics**
+ [註冊 Quick Setup 的委派管理員](quick-setup-register-delegated-administrator.md)
+ [取消註冊 Quick Setup 的委派管理員](quick-setup-deregister-delegated-administrator.md)

# 註冊 Quick Setup 的委派管理員
<a name="quick-setup-register-delegated-administrator"></a>

按照下列程序註冊 Quick Setup 的委派管理員。

**註冊 Quick Setup 委派管理員**

1. 登入您的 AWS Organizations 管理帳戶。

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

1. 在導覽窗格中，選擇 **Quick Setup**。

1. 選擇**設定**。

1. 在 **Delegated administrator for Quick Setup** (Explorer 的委派管理員) 區段中，確認您已設定必要的服務連結角色和服務存取選項。如有必要，請選擇 **Create role** (建立角色) 和 **Enable access** (啟用存取) 按鈕設定這些選項。

1. 針對**帳戶 ID**，輸入 AWS 帳戶 ID。此帳戶必須是其中的成員帳戶 AWS Organizations。

1. 選擇 **Register delegated administrator (註冊委派管理員)**。

# 取消註冊 Quick Setup 的委派管理員
<a name="quick-setup-deregister-delegated-administrator"></a>

按照下列程序取消註冊 Quick Setup 的委派管理員。

**取消註冊 Quick Setup 的委派管理員**

1. 登入您的 AWS Organizations 管理帳戶。

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

1. 在導覽窗格中，選擇 **Quick Setup**。

1. 選擇**設定**。

1. 在 **Quick Setup 的委派管理員**區段中，從**動作**下拉式清單中選擇**取消註冊**。

1. 選取**確認**。

# 了解 Quick Setup 的術語和詳細資訊
<a name="quick-setup-using"></a>

Quick Setup是 中的工具 AWS Systems Manager，會在Quick Setup首頁的組態管理員資料表 AWS 區域 中顯示您跨所有 建立的所有**組態管理員**的結果。在此頁面上，您可以就每個組態 **View details** (檢視詳細資訊)、從 **Actions** (動作) 下拉式選單中刪除組態，也可以 **Create** (建立) 組態。**組態管理員**資料表包含以下資訊：
+ **名稱**：建立時提供的組態管理員名稱。
+ **Configuration type** (組態類型)：建立組態時選擇的組態類型。
+ **版本**：目前部署的組態類型版本。
+ **Organizational units** (組織單位)：如果選擇了一組 **Custom** (自訂) 目標，顯示要將組態部署到其中的組織單位 (OU)。組織單位和自訂目標僅可用於組織的管理帳戶。管理帳戶是您在 AWS Organizations中用於建立組織的帳戶。
+ **部署類型** – 指出部署適用於整個組織 (`Organizational`)，還是僅適用於您的帳戶 (`Local`)。
+ **Regions** (區域)：如果選擇了一組 **Custom** (自訂) 目標或 **Current account** (目前帳戶) 中的目標，要將組態部署到其中的區域。
+ **部署狀態** – 部署狀態會指出 是否 AWS CloudFormation 已成功部署目標或堆疊執行個體。目標和堆疊執行個體包含您在建立組態期間選擇的組態選項。
+ **Association status** (關聯狀態)：關聯狀態是由您建立的組態所建立之所有關聯的狀態。所有目標的關聯必須成功執行，否則狀態為 **Failed** (失敗)。

  Quick Setup 會為每個組態目標建立並執行 State Manager 關聯。State Manager 是 AWS Systems Manager中的工具。

若要檢視部署到目前瀏覽區域的組態，請選取**組態**索引標籤。

## 組態詳細資訊
<a name="quick-setup-details"></a>

**Configuration details** (組態詳細資訊) 頁面會顯示組態及其相關關聯部署的資訊。您可以在此頁面中編輯組態選項、更新目標或刪除組態。您也可以檢視每個組態部署的詳細資訊，從而了解關聯的更多資訊。

根據組態，會顯示下列一或多個狀態圖表：

**組態部署狀態**  
顯示成功、失敗、執行中或待定部署的數量。部署發生在包含受組態影響之節點的指定目標帳戶和區域中。

**組態關聯狀態**  
顯示成功、失敗或待定 State Manager 關聯的數量。Quick Setup 在每個部署中為所選組態選項建立關聯。

**設定狀態**  
顯示組態類型所執行的動作數目及其目前狀態。

**支援合規**  
顯示符合組態指定政策的支援數量。

**Configuration details** (組態詳細資訊) 資料表會顯示組態部署的相關資訊。您可以檢視有關每個部署的詳細資訊，方法是依序選取部署和 **View details** (檢視詳細資訊)。每個部署的詳細資訊頁面會顯示部署到該部署中節點的關聯。

## 編輯和刪除您的組態
<a name="quick-setup-edit-delete"></a>

您可以從 **Configuration details** (組態詳細資訊) 頁面編輯組態的組態選項，方法是依序選擇 **Actions** (動作) 和 **Edit configuration options** (編輯組態選項)。將新選項新增至組態後，Quick Setup 會執行部署並建立新關聯。從組態中移除選項後，Quick Setup 會執行部署並移除任何相關關聯。

**注意**  
您可以隨時為帳戶編輯 Quick Setup 組態。若要編輯 **Organization** (組織) 組態，**Configuration status** (組態狀態) 必須為 **Success** (成功) 或 **Failed** (失敗)。

您也可以透過選擇 **Actions** (動作) 和 **Add OUs** (新增 OU)、**Add Regions** (新增區域)、**Remove OUs** (移除 OU) 或 **Remove Regions** (移除區域)，來更新組態中包含的目標。如果您的帳戶未設定為管理帳戶，或者僅為目前帳戶建立了組態，則無法更新目標組織單位 (OU)。移除區域或 OU 會從這些區域或 OU 中移除關聯。

Quick Setup 會定期發行新版本的組態。您可以選取**升級組態**選項，將組態升級到最新版本。

透過依序選擇組態、**Actions** (動作) 和 **Delete configuration** (刪除組態)，您可以從 Quick Setup 中刪除組態。您也可以從 **Configuration details** (組態詳細資訊) 頁面的 **Actions** (動作) 下拉式清單中，選擇 **Delete configuration** (刪除組態) 來刪除組態。Quick Setup 隨即會提示您 **Remove all OUs and Regions** (移除所有 OU 和區域)，而這可能需要一些時間才能完成。刪除組態還會刪除所有相關關聯。此兩步驟刪除過程會將所有已部署資源從所有帳戶和區域中移除，然後刪除組態。

## 組態合規
<a name="quick-setup-compliance"></a>

您可以在 Explorer 或合規 (二者都是 AWS Systems Manager中的工具) 中檢視執行個體是否符合您組態建立的關聯。若要進一步了解合規，請參閱 [了解有關合規性的詳細資訊](compliance-about.md)。若要進一步了解在 Explorer 中檢視合規，請參閱 [AWS Systems Manager Explorer](Explorer.md)。

# 使用Quick Setup API 來管理組態和部署
<a name="quick-setup-api"></a>

您可以使用 提供的 APIQuick Setup，使用 AWS CLI 或您偏好的 SDK 來建立和管理組態和部署。您也可以使用 CloudFormation 來建立部署組態的組態管理員資源。您可以使用 API 來建立用於部署組態*定義*的組態管理員。組態定義包含部署特定組態類型所需的全部必要資訊。如需有關 Quick Setup API 的詳細資訊，請參閱 [Quick Setup API Reference](https://docs.aws.amazon.com/quick-setup/latest/APIReference/)。

下列範例示範如何使用 AWS CLI 和 建立組態管理員 CloudFormation。

------
#### [ AWS CLI ]

```
aws ssm-quicksetup create-configuration-manager \
--name configuration manager name \
--description Description of your configuration manager
--configuration-definitions JSON string containing configuration defintion
```

以下是包含修補程式政策組態定義的 JSON 字串範例。

```
'{"Type":"AWSQuickSetupType-PatchPolicy","LocalDeploymentAdministrationRoleArn":"arn:aws:iam::123456789012:role/AWS-QuickSetup-StackSet-Local-AdministrationRole","LocalDeploymentExecutionRoleName":"AWS-QuickSetup-StackSet-Local-ExecutionRole","Parameters":{"ConfigurationOptionsInstallNextInterval":"true","ConfigurationOptionsInstallValue":"cron(0 2 ? * SAT#1 *)","ConfigurationOptionsPatchOperation":"ScanAndInstall","ConfigurationOptionsScanNextInterval":"false","ConfigurationOptionsScanValue":"cron(0 1 * * ? *)","HasDeletedBaseline":"false","IsPolicyAttachAllowed":"true","OutputBucketRegion":"","OutputLogEnableS3":"false","OutputS3BucketName":"","OutputS3KeyPrefix":"","PatchBaselineRegion":"us-east-1","PatchBaselineUseDefault":"custom","PatchPolicyName":"dev-patch-policy","RateControlConcurrency":"5","RateControlErrorThreshold":"0%","RebootOption":"RebootIfNeeded","ResourceGroupName":"","SelectedPatchBaselines":"{\"ALMA_LINUX\":{\"value\":\"arn:aws:ssm:us-east-1:123456789012:patchbaseline/pb-0cb0c4966f86b059b\",\"label\":\"AWS-AlmaLinuxDefaultPatchBaseline\",\"description\":\"Default Patch Baseline for Alma Linux Provided by AWS.\",\"disabled\":false},\"AMAZON_LINUX_2\":{\"value\":\"arn:aws:ssm:us-east-1:123456789012:patchbaseline/pb-0be8c61cde3be63f3\",\"label\":\"AWS-AmazonLinux2DefaultPatchBaseline\",\"description\":\"Baseline containing all Security and Bugfix updates approved for Amazon Linux 2 instances\",\"disabled\":false},\"AMAZON_LINUX_2023\":{\"value\":\"arn:aws:ssm:us-east-1:123456789012:patchbaseline/pb-05c9c9bf778d4c4d0\",\"label\":\"AWS-AmazonLinux2023DefaultPatchBaseline\",\"description\":\"Default Patch Baseline for Amazon Linux 2023 Provided by AWS.\",\"disabled\":false},\"DEBIAN\":{\"value\":\"arn:aws:ssm:us-east-1:123456789012:patchbaseline/pb-09a5f8eb62bde80b1\",\"label\":\"AWS-DebianDefaultPatchBaseline\",\"description\":\"Default Patch Baseline for Debian Provided by AWS.\",\"disabled\":false},\"MACOS\":{\"value\":\"arn:aws:ssm:us-east-1:123456789012:patchbaseline/pb-0ee4f94581368c0d4\",\"label\":\"AWS-MacOSDefaultPatchBaseline\",\"description\":\"Default Patch Baseline for MacOS Provided by AWS.\",\"disabled\":false},\"ORACLE_LINUX\":{\"value\":\"arn:aws:ssm:us-east-1:123456789012:patchbaseline/pb-06bff38e95fe85c02\",\"label\":\"AWS-OracleLinuxDefaultPatchBaseline\",\"description\":\"Default Patch Baseline for Oracle Linux Server Provided by AWS.\",\"disabled\":false},\"REDHAT_ENTERPRISE_LINUX\":{\"value\":\"arn:aws:ssm:us-east-1:123456789012:patchbaseline/pb-0cbb3a633de00f07c\",\"label\":\"AWS-RedHatDefaultPatchBaseline\",\"description\":\"Default Patch Baseline for Redhat Enterprise Linux Provided by AWS.\",\"disabled\":false},\"ROCKY_LINUX\":{\"value\":\"arn:aws:ssm:us-east-1:123456789012:patchbaseline/pb-03ec98bc512aa3ac0\",\"label\":\"AWS-RockyLinuxDefaultPatchBaseline\",\"description\":\"Default Patch Baseline for Rocky Linux Provided by AWS.\",\"disabled\":false},\"UBUNTU\":{\"value\":\"pb-06e3563bd35503f2b\",\"label\":\"custom-UbuntuServer-Blog-Baseline\",\"description\":\"Default Patch Baseline for Ubuntu Provided by AWS.\",\"disabled\":false},\"WINDOWS\":{\"value\":\"pb-016889927b2bb8542\",\"label\":\"custom-WindowsServer-Blog-Baseline\",\"disabled\":false}}","TargetInstances":"","TargetOrganizationalUnits":"ou-9utf-example","TargetRegions":"us-east-1,us-east-2","TargetTagKey":"Patch","TargetTagValue":"true","TargetType":"Tags"}}' \
```

------
#### [ CloudFormation ]

```
AWSTemplateFormatVersion: '2010-09-09'
Resources:
SSMQuickSetupTestConfigurationManager:
Type: "AWS::SSMQuickSetup::ConfigurationManager"
Properties:
    Name: "MyQuickSetup"
    Description: "Test configuration manager"
    ConfigurationDefinitions:
    - Type: "AWSQuickSetupType-CFGRecording"
      Parameters:
        TargetAccounts:
            Ref: AWS::AccountId
        TargetRegions:
            Ref: AWS::Region
        LocalDeploymentAdministrationRoleArn: !Sub "arn:aws:iam::${AWS::AccountId}:role/AWS-QuickSetup-StackSet-ContractTest-AdministrationRole"
        LocalDeploymentExecutionRoleName: "AWS-QuickSetup-StackSet-ContractTest-ExecutionRole"
    Tags:
        foo1: "bar1"
```

------

# 支援的 Quick Setup 組態類型
<a name="quick-setup-config-types"></a>

**支援的組態類型**  
Quick Setup 逐步引導您設定多個 Systems Manager 和其他 的操作最佳實務 AWS 服務，並自動部署這些組態。Quick Setup 儀表板會顯示組態部署狀態的即時檢視。

您可以透過與 整合，Quick Setup在個別 AWS 帳戶 或跨多個 AWS 帳戶 和 區域使用 AWS Organizations。跨多個帳戶使用 Quick Setup，有助於確保您的組織維持一致的組態。

Quick Setup 支援下列組態類型。
+ [使用 Quick Setup 設定 Amazon EC2 主機管理](quick-setup-host-management.md)
+ [使用 Quick Setup 為組織設定預設主機管理組態](quick-setup-default-host-management-configuration.md)
+ [使用 Quick Setup 建立 AWS Config組態記錄器](quick-setup-config.md)
+ [使用 部署 AWS Config 一致性套件 Quick Setup](quick-setup-cpack.md)
+ [使用 Quick Setup 修補程式政策設定組織中執行個體的修補](quick-setup-patch-manager.md)
+ [Change Manager 組織設定](change-manager-organization-setup.md)
+ [使用 Quick Setup 設定 DevOps Guru](quick-setup-devops.md)
+ [使用 Quick Setup 部署 Distributor 套件](quick-setup-distributor.md)
+ [使用Quick Setup依照排程自動停止和啟動 EC2 執行個體](quick-setup-scheduler.md)
+ [OpsCenter 組織設定](OpsCenter-quick-setup-cross-account.md)
+ [AWS 資源總管 使用 設定 Quick Setup](Resource-explorer-quick-setup.md)

# 使用 Quick Setup 設定 Amazon EC2 主機管理
<a name="quick-setup-host-management"></a>

使用 中的Quick Setup工具 AWS Systems Manager，在 Amazon Elastic Compute Cloud (Amazon EC2) 執行個體上快速設定必要的安全角色和常用的 Systems Manager 工具。您可以在Quick Setup個別帳戶或多個帳戶中使用 ， AWS 區域 並與 整合 AWS Organizations。這些工具可協助您管理及監控執行個體的運作狀態，同時提供開始使用所需的最低許可。

如果您不熟悉 Systems Manager 服務和功能，我們建議您檢閱*《AWS Systems Manager 使用者指南》*，然後使用 Quick Setup 建立組態。如需有關 Systems Manager 的詳細資訊，請參閱 [什麼是 AWS Systems Manager？](what-is-systems-manager.md)。

**重要**  
如果您符合下列其中一種情況，則 Quick Setup 可能不是 EC2 管理的正確工具：  
您第一次嘗試建立 EC2 執行個體來試用 AWS 功能。
您仍然是 EC2 執行個體管理的新手。
反之，建議您探索下列內容：  
[Amazon EC2 入門](https://aws.amazon.com/ec2/getting-started)
《Amazon EC2 使用者指南》**中的 [Launch an instance using the new launch instance wizard](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-launch-instance-wizard.html)
《Amazon EC2 使用者指南》**中的 [Tutorial: Get started with Amazon EC2 Linux instances](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EC2_GetStarted.html)
如果您已熟悉 EC2 執行個體管理，並且想要簡化多個 EC2 執行個體的組態和管理，則請使用 Quick Setup。無論您的組織擁有數十個、數千個還是數百萬個 EC2 執行個體，皆請使用下列 Quick Setup 程序，一次性為其設定多個選項。

**注意**  
此組態類型可讓您為定義於 的整個組織 AWS Organizations、僅部分組織帳戶和區域或單一帳戶設定多個選項。其中一個選項是每兩週檢查並套用更新至 SSM Agent。如果您是組織管理員，也可以選擇使用預設主機管理組態類型，每兩週以代理程式更新組織中的*所有* EC2 執行個體。如需相關資訊，請參閱[使用 Quick Setup 為組織設定預設主機管理組態](quick-setup-default-host-management-configuration.md)。

## 為 EC2 執行個體設定主機管理選項
<a name="host-management-configuration"></a>

若要設定主機管理，請在 AWS Systems Manager Quick Setup主控台中執行下列任務。

**開啟主機管理組態頁面**

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

1. 在導覽窗格中，選擇 **Quick Setup**。

1. 在**主機管理**卡中，選擇**建立**。
**提示**  
如果您的帳戶中已有一或多個組態，請先選擇**程式庫**索引標籤或**組態**區段中的**建立**按鈕，以檢視卡。

**設定 Systems Manager 主機管理選項**
+ 若要設定 Systems Manager 功能，請在**組態選項**區段中，選擇要為組態啟用的 **Systems Manager** 群組中的選項：

     
**每兩週更新一次 Systems Manager (SSM) Agent**  
讓 Systems Manager 能夠每兩週檢查一次是否有新版本的代理程式。如果有新版本，則 Systems Manager 會自動將受管節點上的代理程式更新為最新發行版本。Quick Setup 不會在沒有代理程式的執行個體上安裝代理程式。如需有關哪些 AMIs 已預先安裝 SSM Agent 的資訊，請參閱[尋找預先安裝了 SSM Agent的 AMIs](ami-preinstalled-agent.md)。  
建議您選擇此選項，以確保節點始終執行最新版本的 SSM Agent。如需 SSM Agent 的詳細資訊，包括如何手動安裝代理程式的資訊。請參閱 [使用 SSM Agent](ssm-agent.md)。  
**每 30 分鐘從執行個體收集一次庫存資訊**  
讓 Quick Setup 能夠設定下列類型中繼資料的收集：  
  + **AWS 元件** – EC2 驅動程式、代理程式、版本等。
  + **應用程式** – 應用程式名稱、發佈者、版本等。
  + **節點詳細資訊** – 系統名稱、作業系統 (OS) 名稱、作業系統版本、上次啟動時間、DNS、網域、工作團隊、作業系統架構等。
  + **網路組態** – IP 地址、MAC 地址、DNS、閘道、子網路遮罩等。
  + **服務** – 名稱、顯示名稱、狀態、相依服務、服務類型、啟動類型等 (僅限 Windows Server 節點)。
  + **Windows 角色** – 名稱、顯示名稱、路徑、功能類型、安裝狀態等 (僅限 Windows Server 受管節點)。
  + **Windows 更新** – Hotfix ID、安裝人員、安裝日期等 (僅限 Windows Server 節點)。
如需 中的工具庫存的詳細資訊 AWS Systems Manager，請參閱 [AWS Systems Manager庫存](systems-manager-inventory.md)。  
即使您只選取幾個節點，**Inventory collection** (庫存收集) 選項可能需要最多 10 分鐘才能完成。  
**每天掃描執行個體是否遺漏修補程式**  
讓 Patch Manager (Systems Manager 中的工具) 能夠每天掃描節點，然後在**合規**頁面上產生報告。此報告會根據*預設修補基準*來顯示修補程式相容的受管節點數量。此報告包含每個節點的清單及其合規狀態。  
如需修補操作和修補程式基準的資訊，請參閱 [AWS Systems Manager Patch Manager](patch-manager.md)。  
如需有關修補程式合規資訊，請參閱 Systems Manager [Compliance](https://console.aws.amazon.com/systems-manager/compliance) (合規) 頁面。  
如需有關在一個組態中修補多個帳戶和區域中受管節點的資訊，請參閱 [Quick Setup中的修補程式政策組態](patch-manager-policies.md) 和 [使用 Quick Setup 修補程式政策設定組織中執行個體的修補](quick-setup-patch-manager.md)。  
Systems Manager 支援多種掃描受管節點的方法，以檢查修補程式合規性。如果一次實作多個方法，則您看到的修補程式合規資訊永遠是最近一次掃描的結果。先前掃描的結果會覆寫。如果掃描方法使用不同的修補基準，且具有不同的核准規則，則修補程式合規資訊可能會意外變更。如需詳細資訊，請參閱[識別建立修補程式合規資料的執行](patch-manager-compliance-data-overwrites.md)。

**設定 Amazon CloudWatch 主機管理選項**
+ 若要設定 CloudWatch 功能，請在**組態選項**區段中，選擇要為組態啟用的 **Amazon CloudWatch** 群組中的選項：

     
**安裝並設定 CloudWatch 代理程式**  
在 Amazon EC2 執行個體上安裝 CloudWatch 統一代理程式的基本組態。代理程式會從 Amazon CloudWatch 的執行個體收集指標和日誌檔案。其還會整合此資訊，以便您快速判斷執行個體的運作狀態。如需 CloudWatch 代理程式基本組態的詳細資訊，請參閱[《CloudWatch 代理程式預先指定的指標集》](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/create-cloudwatch-agent-configuration-file-wizard.html#cloudwatch-agent-preset-metrics)。可能需要額外付費。如需詳細資訊，請參閱 [Amazon CloudWatch 定價](https://aws.amazon.com/cloudwatch/pricing/)。  
**每 30 天更新一次 CloudWatch 代理程式**  
讓 Systems Manager 能夠每 30 天檢查一次是否有新版本的 CloudWatch 代理程式。如果有新版本，則 Systems Manager 會更新執行個體上的代理程式。建議您選擇此選項，以確保執行個體始終執行最新版本的 CloudWatch 代理程式。

**設定 Amazon EC2 啟動代理程式主機管理選項**
+ 若要設定 Amazon EC2 啟動代理程式功能，請在**組態選項**區段中，選擇要為組態啟用的 **Amazon EC2 啟動代理程式**群組中的選項：

     
**每 30 天更新一次 EC2 啟動代理程式**  
讓 Systems Manager 能夠每 30 天檢查一次執行個體上是否安裝了新版本的啟動代理程式。如果有新版本，則 Systems Manager 會更新執行個體上的代理程式。建議您選擇此選項，以確保執行個體始終執行最新版本的適用啟動代理程式。對於 Amazon EC2 Windows 執行個體，此選項支援 EC2Launch、EC2Launch v2 和 EC2Config。對於 Amazon EC2 Linux 執行個體，此選項支援 `cloud-init`。對於 Amazon EC2 Mac 執行個體，此選項支援 `ec2-macos-init`。Quick Setup 不支援更新安裝在啟動代理程式不支援的作業系統上或 AL2023 上的啟動代理程式。  
如需這些初始化代理程式的詳細資訊，請參閱下列主題：  
  +  [使用 EC2Launch v2 設定 Windows 執行個體](https://docs.aws.amazon.com/AWSEC2/latest/WindowsGuide/ec2launch-v2.html) 
  +  [使用 EC2Launch 設定 Windows 執行個體](https://docs.aws.amazon.com/AWSEC2/latest/WindowsGuide/ec2launch.html) 
  +  [使用 EC2Config 服務設定 Windows 執行個體](https://docs.aws.amazon.com/AWSEC2/latest/WindowsGuide/ec2config-service.html) 
  +  [cloud-init 文件](https://cloudinit.readthedocs.io/en/22.2.2/index.html) 
  +  [ec2-macos-init](https://github.com/aws/ec2-macos-init) 

**選取要由主機管理組態更新的 EC2 執行個體**
+ 在**目標**區段中，選擇對應方法來判斷要部署組態的帳戶和區域：
**注意**  
您無法建立多個以相同 AWS 區域為目標的 Quick Setup 主機管理組態。

------
#### [ Entire organization ]

  您的組態會部署到組織中的所有組織單位 OUs) 和 AWS 區域 。

**注意**  
**Entire organization** (整個組織) 選項只有在您從組織的管理帳戶設定主機管理時才可用。

------
#### [ Custom ]

  1. 在**目標 OU** 區段中，選取要部署此主機管理組態的 OU。

  1. 在**目標區域**區段中，選取要部署此主機管理組態的區域。

------
#### [ Current account ]

  選擇其中一個區域選項，然後依照該選項的步驟操作。

   

**目前區域**  
選擇如何僅以目前區域中的執行個體為目標：  
  + **所有執行個體**：主機管理組態會自動將目前區域中的每個 EC2 設定為目標。
  + **標籤**：選擇**新增**，然後輸入要新增至目標執行個體的索引鍵和選用值。
  + **資源群組**：在**資源群組**欄位中，選取包含目標 EC2 執行個體的現有資源群組。
  + **手動**：在**執行個體**區段中，選取每個目標 EC2 執行個體的核取方塊。

**選擇區域**  
透過選擇下列其中一項，選擇如何在指定的區域中鎖定目標執行個體：  
  + **所有執行個體**：指定區域中的所有執行個體都是目標執行個體。
  + **標籤**：選擇**新增**，然後輸入已新增至目標執行個體的索引鍵和選用值。
在**目標區域**區段中，選取要部署此主機管理組態的區域。

------

**指定執行個體設定檔選項**
+ *僅限**整個組織**和**自訂**目標。*

  在**執行個體設定檔選項**區段中，選擇是要將所需的 IAM 政策新增至連接到執行個體的現有執行個體設定檔，還是要允許Quick Setup使用您所選組態所需的許可建立 IAM 政策和執行個體設定檔。

指定所有組態選項後，選擇**建立**。

# 使用 Quick Setup 為組織設定預設主機管理組態
<a name="quick-setup-default-host-management-configuration"></a>

使用 中的Quick Setup工具 AWS Systems Manager，您可以為已新增至組織的所有帳戶和區域啟用預設主機管理組態 AWS Organizations。如此可確保組織中所有 Amazon Elastic Compute Cloud (EC2) 執行個體的 SSM Agent 會處於最新狀態，且可連線到 Systems Manager。

**開始之前**  
啟用此設定之前，請先確認符合下列要求。
+ 最新版 SSM Agent 已安裝在組織中要管理的所有 EC2 執行個體上。
+ 要管理的 EC2 執行個體正在使用 Instance Metadata Service Version 2 (IMDSv2)。
+ 您會登入組織的管理帳戶，如 中所述 AWS Organizations，使用具有管理員許可的 AWS Identity and Access Management (IAM) 身分 （使用者、角色或群組）。

**使用預設 EC2 執行個體管理角色**  
預設主機管理組態會使用 Systems Manager 的 `default-ec2-instance-management-role` 服務設定。這是具有許可的角色，您希望組織中所有帳戶皆可使用該角色，以允許執行個體上的 SSM Agent 與雲端中的 Systems Manager 服務之間進行通訊。

如果您已使用 [https://docs.aws.amazon.com/cli/latest/reference/ssm/update-service-setting.html](https://docs.aws.amazon.com/cli/latest/reference/ssm/update-service-setting.html) CLI 命令設定此角色，則預設主機管理組態會使用該角色。如果您尚未設定此角色，Quick Setup 會為您建立並套用角色。

若要檢查是否已為您的組織指定此角色，請使用 [https://docs.aws.amazon.com/cli/latest/reference/ssm/get-service-setting.html](https://docs.aws.amazon.com/cli/latest/reference/ssm/get-service-setting.html) 命令。

## 啟用每兩週自動更新 SSM Agent
<a name="dhmc-enable-automatic-updates"></a>

使用下列程序為您的整個 AWS Organizations 組織啟用預設主機管理組態選項。

**若要啟用每兩週自動更新 SSM Agent**

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

1. 在導覽窗格中，選擇 **Quick Setup**。

1. 在**預設主機管理組態**卡中，選擇**建立**。
**提示**  
如果您的帳戶中已有一或多個組態，請先選擇**程式庫**索引標籤或**組態**區段中的**建立**按鈕，以檢視卡。

1. 在**組態選項**區段中，選取**啟用 SSM Agent 每兩週的自動更新**。

1. 選擇 **Create** (建立)

# 使用 Quick Setup 建立 AWS Config組態記錄器
<a name="quick-setup-config"></a>

使用 中的Quick Setup工具 AWS Systems Manager，您可以快速建立採用 技術的組態記錄器 AWS Config。使用組態記錄器來偵測您資源組態中的變更，並將這些變更作為組態項目擷取。如果您不熟悉 AWS Config，建議您先檢閱《 *AWS Config 開發人員指南*》中的內容，再使用 建立組態，以進一步了解 服務Quick Setup。如需詳細資訊 AWS Config，請參閱《 *AWS Config 開發人員指南*》中的[什麼是 AWS Config？](https://docs.aws.amazon.com/config/latest/developerguide/WhatIsConfig.html)。

根據預設，組態記錄器會在 AWS Config 執行 AWS 區域 的 中記錄所有支援的資源。您可以自訂組態，以便僅記錄您指定的資源類型。如需詳細資訊，請參閱《 *AWS Config 開發人員指南*》中的[選取哪些資源 AWS Config 記錄](https://docs.aws.amazon.com/config/latest/developerguide/select-resources.html)。

 AWS Config 開始記錄組態時，需支付服務費用。如需定價資訊，請參閱 [AWS Config 定價](https://aws.amazon.com/config/pricing/)。

**注意**  
如果您已建立組態記錄器，則 Quick Setup 不會停止記錄或對已在記錄的資源類型進行任何變更。如果您選擇使用 Quick Setup 記錄其他資源類型，服務會將它們附加到現有的記錄器群組。刪除 Quick Setup **Config 紀錄**組態類型不會停止組態記錄器。變更會繼續進行記錄，並且會收取服務使用費，直到您停止組態記錄器為止。若要進一步了解管理組態記錄器，請參閱*《AWS Config 開發人員指南》*中的[管理組態記錄器](https://docs.aws.amazon.com/config/latest/developerguide/stop-start-recorder.html)。

若要設定 AWS Config 錄製，請在 AWS Systems Manager 主控台中執行下列任務。

**使用 設定 AWS Config 錄製 Quick Setup**

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

1. 在導覽窗格中，選擇 **Quick Setup**。

1. 在**設定記錄**卡中，選擇**建立**。
**提示**  
如果您的帳戶中已有一或多個組態，請先選擇**程式庫**索引標籤或**組態**區段中的**建立**按鈕，以檢視卡。

1. 在**組態選項**區段中，執行下列動作：

   1. 針對**選擇要記錄 AWS 的資源類型**，指定要記錄所有支援的資源，還是只記錄您選擇的資源類型。

   1. 在**交付設定**欄位中，指定是建立新的 Amazon Simple Storage Service (Amazon S3) 儲存貯體，還是選擇要向其傳送組態快照的現有儲存貯體。

   1. 針對**通知選項**，選擇您偏好的通知選項。 AWS Config 使用 Amazon Simple Notification Service (Amazon SNS) 來通知您與資源相關的重要 AWS Config 事件。如果您選擇**使用現有的 SNS 主題**選項，則必須提供您要使用該帳戶中現有 Amazon SNS 主題的 AWS 帳戶 ID 和名稱。如果您以多個 AWS 區域為目標，則每個區域中的主題名稱必須相同。

1. 在 **Schedule** (排程) 區段中，選擇您希望 Quick Setup 修補對與您的組態不同的資源所做的變更的頻率。**Default** (預設) 選項會執行一次。如果您不要 Quick Setup 修復對與組態不同的資源所做的變更，請選擇 **Custom** (自訂) 下的 **Disable remediation** (停用修補)。

1. 在**目標**區段中，選擇下列其中一個選項，以識別用於記錄的帳戶和區域。
**注意**  
如果您使用單一帳戶，則無法使用組織和組織單位 (OU) 的選項。您可以選擇將此組態套用至您帳戶 AWS 區域 中的所有 ，還是只套用您選取的區域。
   + **Entire organization** (整個組織) – 組織中的所有帳戶和區域。
   + **Custom** (自訂) – 僅您指定的 OU 與區域。
     + 在**目標 OU** 區段中，選取您希望允許記錄的 OU。
     + 在**目標區域**區段中，選取您希望允許記錄的區域。
   + **Current account** (目前帳戶) – 只有您在目前登入的帳戶中指定的區域才會成為目標。選擇下列其中一項：
     + **Current Region** (目前區域) – 只有在主控台中選取的區域中的受管節點才能成為目標。
     + **選擇區域**：選擇要套用記錄組態的個別區域。

1. 選擇**建立**。

# 使用 部署 AWS Config 一致性套件 Quick Setup
<a name="quick-setup-cpack"></a>

一致性套件是 AWS Config 規則和修補動作的集合。利用 Quick Setup，您可以用單一實體的形式在帳戶和 AWS 區域 中，或是跨 AWS Organizations中的組織部署一致性套件。這可協助您使用通用架構和封裝模型，大規模管理 AWS 資源的組態合規性，從政策定義到稽核和彙總報告。

若要部署一致性套件，請在 AWS Systems Manager Quick Setup 主控台中執行下列任務。

**注意**  
您必須先啟用 AWS Config 錄製，才能部署此組態。如需詳細資訊，請參閱*《AWS Config 開發人員指南》*中的[一致性套件](https://docs.aws.amazon.com/config/latest/developerguide/conformance-packs.html)。

**若要使用 Quick Setup 部署一致性套件**

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

1. 在導覽窗格中，選擇 **Quick Setup**。

1. 在**一致性套件**卡中，選擇**建立**。
**提示**  
如果您的帳戶中已有一或多個組態，請先選擇**程式庫**索引標籤或**組態**區段中的**建立**按鈕，以檢視卡。

1. 在**一致性套件**區段中，選擇您要部署的一致性套件。

1. 在 **Schedule** (排程) 區段中，選擇您希望 Quick Setup 修補對與您的組態不同的資源所做的變更的頻率。**Default** (預設) 選項會執行一次。如果您不要 Quick Setup 修復對與組態不同的資源所做的變更，請選擇 **Custom** (自訂) 下的 **Disabled** (已停用)。

1. 在**目標**區段中，選擇是否要將一致性套件部署到整個組織、部分組織 AWS 區域或您目前登入的帳戶。

   如果您選擇 **Entire organization** (整個組織)，請繼續步驟 8。

   如果選擇 **Custom** (自訂)，請繼續步驟 7。

1. 在 **Target Regions** (目標區域) 區段中，選取您要部署一致性套件的區域的核取方塊。

1. 選擇**建立**。

# 使用 Quick Setup 修補程式政策設定組織中執行個體的修補
<a name="quick-setup-patch-manager"></a>

使用 中的Quick Setup工具 AWS Systems Manager，您可以建立由 提供支援的修補程式政策Patch Manager。修補程式政策定義了在自動化修補 Amazon Elastic Compute Cloud (Amazon EC2) 執行個體和其他受管節點時使用的排程和基準。使用單一修補程式政策組態，您可以定義為組織中多個 AWS 區域 的所有帳戶、僅您選擇的帳戶和區域或者單一帳戶-區域對進行修補。如需有關修補程式政策的詳細資訊，請參閱 [Quick Setup中的修補程式政策組態](patch-manager-policies.md)。

**先決條件**  
若要使用 Quick Setup 定義節點的修補程式政策，則節點必須是*受管節點*。如需有關管理節點的詳細資訊，請參閱 [為組織設定 Systems Manager 統一主控台](systems-manager-setting-up-organizations.md)。

**重要**  
**修補程式合規掃描方法**：Systems Manager 支援多種掃描受管節點的方法，可檢查修補程式合規情況。如果一次實作多個方法，則您看到的修補程式合規資訊永遠是最近一次掃描的結果。先前掃描的結果會覆寫。如果掃描方法使用不同的修補基準，且具有不同的核准規則，則修補程式合規資訊可能會意外變更。如需詳細資訊，請參閱[識別建立修補程式合規資料的執行](patch-manager-compliance-data-overwrites.md)。  
**關聯合規狀態和修補程式政策**：Quick Setup 修補程式政策下受管節點的修補狀態符合該節點的 State Manager 關聯執行狀態。如果關聯執行狀態為 `Compliant`，受管節點的修補程式狀態也會標示為 `Compliant`。如果關聯執行狀態為 `Non-Compliant`，受管節點的修補程式狀態也會標示為 `Non-Compliant`。

## 修補程式政策組態支援的區域
<a name="patch-policies-supported-regions"></a>

下列區域目前支援 Quick Setup 中的修補程式政策組態：
+ 美國東部 (俄亥俄) (us-east-2)
+ 美國東部 (維吉尼亞北部) (us-east-1)
+ 美國西部 (加利佛尼亞北部) (us-west-1)
+ 美國西部 (奧勒岡) (us-west-2)
+ 亞太區域 (孟買) (ap-south-1)
+ 亞太區域 (首爾) (ap-northeast-2)
+ 亞太地區 (新加坡) (ap-southeast-1)
+ 亞太地區 (雪梨) (ap-southeast-2)
+ 亞太地區 (東京) (ap-northeast-1)
+ 加拿大 (中部) (ca-central-1)
+ 歐洲 (法蘭克福) (eu-central-1)
+ 歐洲 (愛爾蘭) (eu-west-1)
+ 歐洲 (倫敦) (eu-west-2)
+ 歐洲 (巴黎) (eu-west-3)
+ 歐洲 (斯德哥爾摩) (eu-north-1)
+ 南美洲 (聖保羅) (sa-east-1)

## 適用於修補程式政策 S3 儲存貯體的許可
<a name="patch-policy-s3-bucket-permissions"></a>

建立修補程式政策時，Quick Setup 會建立一個包含名為 `baseline_overrides.json` 的檔案的 Amazon S3 儲存貯體。此檔案儲存您為修補程式政策指定之修補基準的相關資訊。

此儲存貯體的名稱格式為 `aws-quicksetup-patchpolicy-account-id-quick-setup-configuration-id`。

例如：`aws-quicksetup-patchpolicy-123456789012-abcde`

如果您為某個組織建立修補程式政策，則此儲存貯體會建立在該組織的管理帳戶中。

您必須向其他 AWS 資源提供使用 AWS Identity and Access Management (IAM) 政策存取此 S3 儲存貯體的許可，有兩種使用案例：
+ [情況 1：將您自己的而不是由 Quick Setup 提供的執行個體設定檔或服務角色連接至受管節點](#patch-policy-instance-profile-service-role)
+ [情況 2：使用 VPC 端點連線至 Systems Manager](#patch-policy-vpc)

在這兩種情況下您所需要的許可政策都已呈現在下面的 [Quick Setup S3 儲存貯體的政策許可](#patch-policy-bucket-permissions) 一節中。

### 情況 1：將您自己的而不是由 Quick Setup 提供的執行個體設定檔或服務角色連接至受管節點
<a name="patch-policy-instance-profile-service-role"></a>

修補程式政策組態包含**將必要的 IAM 政策新增至連接至執行個體的現有執行個體設定檔**的選項。

如果您未選擇此選項，但想要 Quick Setup 使用此修補程式政策修補受管的節點，則必須實作下列項目：
+ IAM 受管政策 `AmazonSSMManagedInstanceCore` 必須連接至用於為受管節點提供 Systems Manager 許可的 [IAM 執行個體設定檔](setup-instance-permissions.md)或 [IAM 服務角色](hybrid-multicloud-service-role.md)。
+ 您必須將存取修補程式政策儲存貯體的許可作為內嵌政策新增至 IAM 執行個體設定檔或 IAM 服務角色。您可以向所有 `aws-quicksetup-patchpolicy` 儲存貯體或僅向針對您的組織或帳戶建立的特定儲存貯體提供萬用字元存取權，如先前的程式碼範例所示。
+ 您必須使用以下鍵值對標記 IAM 執行個體設定檔或 IAM 服務角色。

  `Key: QSConfigId-quick-setup-configuration-id, Value: quick-setup-configuration-id`

  *quick-setup-configuration-id* 代表套用至 AWS CloudFormation 堆疊的參數值，用於建立修補程式政策組態。若要擷取此 ID，請執行以下操作：

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

  1. 選取用來建立修補程式政策的堆疊名稱。名稱的格式為 `StackSet-AWS-QuickSetup-PatchPolicy-LA-q4bkg-52cd2f06-d0f9-499e-9818-d887cEXAMPLE`。

  1. 選擇**參數**索引標籤。

  1. 在**參數**清單的**鍵**欄中，找到鍵 **QSConfigurationId**。在同一列的**值**欄中，找到組態 ID，例如 `abcde`。

     在此範例中，對於要套用至執行個體設定檔或服務角色的標籤，其鍵為 `QSConfigId-abcde`，且值為 `abcde`。

如需有關將標籤新增至 IAM 角色的資訊，請參閱《[IAM 使用者指南》中的標記 IAM 角色](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_tags_roles.html#id_tags_roles_procs-console)和管理[執行個體描述檔 (AWS CLI 或 AWS API) 上的標籤](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_tags_instance-profiles.html#id_tags_instance-profile_procs-cli-api)。 **

### 情況 2：使用 VPC 端點連線至 Systems Manager
<a name="patch-policy-vpc"></a>

如果您使用 VPC 端點連線至 Systems Manager，則您的 S3 VPC 端點政策必須允許存取 Quick Setup 修補程式政策 S3 儲存貯體。

如需將許可新增至 S3 VPC 端點政策的相關資訊，請參閱《Amazon S3 使用者指南》**中的[使用儲存貯體政策控制來自 VPC 端點的存取](https://docs.aws.amazon.com/AmazonS3/latest/userguide/example-bucket-policies-vpc-endpoint.html)一節。

### Quick Setup S3 儲存貯體的政策許可
<a name="patch-policy-bucket-permissions"></a>

您可以向所有 `aws-quicksetup-patchpolicy` 儲存貯體或僅向針對您的組織或帳戶建立的特定儲存貯體提供萬用字元存取權。若要為下述兩種情況提供必要的許可，請使用其中一種格式。

------
#### [ All patch policy buckets ]

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

****  

```
{
  "Version":"2012-10-17",		 	 	 
  "Statement": [
    {
      "Sid": "AccessToAllPatchPolicyRelatedBuckets",
      "Effect": "Allow",
      "Action": "s3:GetObject",
      "Resource": "arn:aws:s3:::aws-quicksetup-patchpolicy-*"
    }
  ]
}
```

------

------
#### [ Specific patch policy bucket ]

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

****  

```
{
  "Version":"2012-10-17",		 	 	 
  "Statement": [
    {
      "Sid": "AccessToMyPatchPolicyRelatedBucket",
      "Effect": "Allow",
      "Action": "s3:GetObject",
      "Resource": "arn:aws:s3:::aws-quicksetup-patchpolicy-111122223333-quick-setup-configuration-id"
    }
  ]
}
```

------

**注意**  
建立修補程式政策組態後，您可以在 S3 主控台中找到儲存貯體的完整名稱。例如：`aws-quicksetup-patchpolicy-123456789012-abcde`

------

## 修補程式政策作業中的隨機修補基準 ID
<a name="qs-patch-baselines-and-compliance"></a>

修補程式政策的修補作業會使用 `AWS-RunPatchBaseline` SSM 命令文件中的 `BaselineOverride` 參數。

當您使用 `AWS-RunPatchBaseline` 進行修補程式政策*以外*的修補時，您可以使用 `BaselineOverride` 來指定作業期間要使用的與指定的預設值不同的修補基準清單。您可以在名為 `baseline_overrides.json` 的檔案中建立此清單，然後手動將其新增至您擁有的一個 Amazon S3 儲存貯體，如 [使用 BaselineOverride 參數](patch-manager-baselineoverride-parameter.md) 中所述。

然而，對於以修補程式政策為基礎的修補作業，Systems Manager 會自動建立 S3 儲存貯體並在其中新增 `baseline_overrides.json` 檔案。然後，每次 Quick Setup 執行修補操作 (使用 Run Command 工具) 時，系統都會為每個修補基準產生一個隨機 ID。每個修補程式政策修補作業的這個 ID 都不同，而且您無法在您的帳戶中儲存或存取它所代表的修補基準。

因此，您不會在修補日誌中看到組態中選取的修補基準的 ID。這適用於您可能選取的 AWS 受管修補程式基準和自訂修補程式基準。日誌中報告的基準 ID 是針對該特定修補作業產生的基準 ID。

此外，如果您嘗試在 Patch Manager 中檢視有關使用隨機 ID 產生之修補基準的詳細資訊，則系統會報告該修補基準不存在。這是預期會出現的行為，可以忽略。

## 建立修補程式政策
<a name="create-patch-policy"></a>

若要建立修補程式政策，請在 Systems Manager 主控台執行下列任務。

**使用 Quick Setup 建立修補程式政策**

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

   如果您要設定為組織進行修補，請確保您已登入到組織的管理帳戶。您無法使用委派管理員帳戶或成員帳戶來設定政策。

1. 在導覽窗格中，選擇 **Quick Setup**。

1. 在 **Patch Manager** (修補程式管理員) 卡上，選擇 **Create** (建立)。
**提示**  
如果您的帳戶中已有一或多個組態，請先選擇**程式庫**索引標籤或**組態**區段中的**建立**按鈕，以檢視卡。

1. 對於 **Configuration name** (組態名稱)，請輸入名稱以協助識別修補程式政策。

1. 在 **Scanning and installation** (掃描和安裝) 區段的 **Patch operation** (修補程式操作) 下，選擇修補程式政策是要 **Scan** (掃描) 指定的目標，還是在指定目標上 **Scan and install** (掃描並安裝) 修補程式。

1. 在 **Scanning schedule** (掃描排程) 下，選擇 **Use recommended defaults** (使用建議的預設值) 或 **Custom scan schedule** (自訂掃描排程)。預設的掃描排程每天會在凌晨 1 點 (UTC) 掃描您的目標。
   + 如果您選擇 **Custom scan schedule** (自訂掃描排程)，則請選取 **Scanning frequency** (掃描頻率)。
   + 如果您選擇 **Daily** (每日)，則請輸入您要掃描目標的時間 (UTC)。
   + 如果您選擇 **Custom CRON Expression** (自訂 CRON 運算式)，則請將排程輸入為 **CRON expression** (CRON 運算式)。如需有關格式化 Systems Manager 的 CRON 運算式的詳細資訊，請參閱 [參考：Systems Manager 的 Cron 和 Rate 運算式](reference-cron-and-rate-expressions.md)。

     此外，請選取 **Wait to scan targets until first CRON interval** (等待掃描目標，直到第一個 CRON 間隔為止)。依預設，Patch Manager 會在節點變為目標時立即進行掃描。

1. 如果您選擇 **Scan and install** (掃描並安裝)，則請選擇將修補程式安裝到指定目標時要使用的 **Installation schedule** (安裝排程)。如果您選擇 **Use recommended defaults** (使用建議的預設值)，則 Patch Manager 每週會在星期日凌晨 2 點 (UTC) 安裝修補程式。
   + 如果您選擇 **Custom install schedule** (自訂安裝排程)，請選取 **Installation Frequency** (安裝頻率)。
   + 如果您選擇 **Daily** (每日)，請輸入您要在目標上安裝更新的時間 (UTC)。
   + 如果您選擇 **Custom CRON expression** (自訂 CRON 運算式)，請將排程輸入為 **CRON expression** (CRON 運算式)。如需有關格式化 Systems Manager 的 CRON 運算式的詳細資訊，請參閱 [參考：Systems Manager 的 Cron 和 Rate 運算式](reference-cron-and-rate-expressions.md)。

     此外，請清除 **Wait to install updates until first CRON interval** (等待安裝更新，直到第一個 CRON 間隔)，以便在節點變為目標時立即在節點上安裝更新。依預設，Patch Manager 會等到第一個 CRON 間隔才能安裝更新。
   + 請選擇 **Reboot if needed** (必要時重新啟動)，在安裝修補程式之後重新啟動節點 建議在安裝後重新啟動，但可能會導致可用性問題。

1. 在 **Patch baseline** (修補基準) 中，選擇掃描和更新目標時要使用的修補基準。

   依預設，Patch Manager 會使用預先定義的修補基準。如需詳細資訊，請參閱[預先定義的基準](patch-manager-predefined-and-custom-patch-baselines.md#patch-manager-baselines-pre-defined)。

   如果您選擇**自訂修補程式基準**，請變更您不想使用預先定義修補程式基準之作業系統的所選 AWS 修補程式基準。
**注意**  
如果您使用 VPC 端點連線至 Systems Manager，請確保您的 S3 VPC 端點政策允許存取該 S3 儲存貯體。如需詳細資訊，請參閱[適用於修補程式政策 S3 儲存貯體的許可](#patch-policy-s3-bucket-permissions)。
**重要**  
如果您在 Quick Setup 中使用[修補程式政策組態](patch-manager-policies.md)，則您對自訂修補基準所做的更新會每小時與 Quick Setup 同步一次。  
如果刪除修補程式政策中參照的自訂修補基準，則修補程式政策的 Quick Setup **Configuration details** (組態詳細資訊) 頁面上會顯示橫幅。此橫幅會通知您修補程式政策參照修補基準不再存在，而後續的修補操作將會失敗。在此情況下，請返回到 Quick Setup **Configurations** (組態) 頁面，選取 Patch Manager 組態，然後選擇 **Actions** (動作)、**Edit configuration** (編輯組態)。刪除的修補基準名稱會反白顯示，您必須為受影響的作業系統選取新的修補基準。

1. (選用) 在 **Patching log storage** (修補日誌存放區) 區段中，選取 **Write output to S3 bucket** (將輸出寫入 S3 儲存貯體) 以將修補程式操作日誌存放在 Amazon S3 儲存貯體中。
**注意**  
如果您要為組織設定修補程式政策，則組織的管理帳戶必須至少擁有此儲存貯體的唯讀許可。政策中包含的所有組織單位都必須擁有該儲存貯體的寫入存取權。如需有關授予儲存貯體存取權給不同帳戶的資訊，請參閱《Amazon Simple Storage Service 使用者指南》**中的[範例 2：儲存貯體擁有者授予跨帳戶儲存貯體許可](https://docs.aws.amazon.com/AmazonS3/latest/userguide/example-walkthroughs-managing-access-example2.html)。

1. 選擇**瀏覽 S3** 以選取要儲存修補程式日誌輸出的儲存貯體。管理帳戶必須擁有此儲存貯體的讀取存取權。在 **Targets** (目標) 區段中設定的所有非管理帳戶和目標都必須擁有對所提供的 S3 儲存貯體的寫入存取權以進行記錄。

1. 在 **Targets** (目標) 區段中，選擇下列其中一個選項，以識別此修補程式政策操作的帳戶和區域。
**注意**  
如果您使用單一帳戶，則無法使用組織和組織單位 (OU) 的選項。您可以選擇是要將此組態套用至帳戶中的所有 AWS 區域 ，還是僅套用至您選擇的區域。  
如果先前為帳戶指定了主區域，但尚未加入 Quick Setup 的新主控台體驗，則無法將該區域排除在**目標**組態之外。
   + **Entire organization** (整個組織) – 組織中的所有帳戶和區域。
   + **Custom** (自訂) – 僅您指定的 OU 與區域。
     + 在 **Target OUs** (目標 OU) 區段中，選取您要設定修補程式政策的 OU。
     + 在 **Target Regions** (目標區域) 區段中，選取您要套用修補程式政策的區域。
   + **Current account** (目前帳戶) – 只有您在目前登入的帳戶中指定的區域才會成為目標。選擇下列其中一項：
     + **Current Region** (目前區域) – 只有在主控台中選取的區域中的受管節點才能成為目標。
     + **Choose Regions** (選擇區域) – 選擇要套用修補程式政策的個別區域。

1. 對於 **Choose how you want to target instances** (選擇將執行個體設為目標的方式)，選擇下列其中一個選項：
   + **All managed nodes** (所有受管節點) – 所選 OU 與區域中的所有受管節點。
   + **Specify the resource group** (指定資源群組) – 從清單中選擇資源群組的名稱，將其關聯資源設為目標。
**注意**  
目前，只有單一帳號組態支援選取資源群組。若要修補多個帳戶中的資源，請選擇不同的鎖定目標選項。
   + **Specify a node tag** (指定節點標籤) – 僅在您將其設為目標的所有帳戶和區域中修補標記有您指定之金鑰值對的節點。
   + **Manual** (手動) – 從清單中手動選擇所有指定帳號和區域中的受管節點。
**注意**  
此選項目前僅支援 Amazon EC2 執行個體。您可以在修補程式政策組態中手動新增最多 25 個執行個體。

1. 在 **Rate control** (速率控制) 區段中，執行下列操作：
   + 針對 **Concurrency** (並行)，輸入要同時執行修補程式政策的節點數目或百分比。
   + 針對 **Error threshold** (錯誤閾值)，輸入修補程式政策失敗之前可能會發生錯誤的節點數目或百分比。

1. (選用) 選取**將必要的 IAM 政策新增至連接至執行個體的現有執行個體設定檔**核取方塊。

   此選項會將此 Quick Setup 組態建立的 IAM 政策套用至已連接執行個體設定檔 (EC2 執行個體) 或服務角色的節點 (啟用混合模式節點)。當您的受管節點已連接執行個體設定檔或服務角色時，建議選取此選項，但其不包含使用 Systems Manager 所需的所有許可。

   您在此選取的項目會套用至稍後在帳戶和區域 (其會套用此修補程式政策組態) 中建立的受管節點。
**重要**  
如果您未選取此核取方塊，但想要 Quick Setup 使用此修補程式政策修補受管節點，則必須執行下列動作：  
將存取為修補程式政策建立之 S3 儲存貯體的許可新增至 [IAM 執行個體設定檔](setup-instance-permissions.md)或 [IAM 服務角色](hybrid-multicloud-service-role.md)  
使用特定的鍵值對標記您的 IAM 執行個體設定檔或 IAM 服務角色。  
如需相關資訊，請參閱[情況 1：將您自己的而不是由 Quick Setup 提供的執行個體設定檔或服務角色連接至受管節點](#patch-policy-instance-profile-service-role)。

1. 選擇**建立**。

   若要在建立修補程式政策之後檢閱修補狀態，您可以從 [https://console.aws.amazon.com/systems-manager/quick-setup](https://console.aws.amazon.com/systems-manager/quick-setup) 頁面存取組態。

# 使用 Quick Setup 設定 DevOps Guru
<a name="quick-setup-devops"></a>

您可以使用 Quick Setup 快速設定 DevOps Guru 選項。Amazon DevOps Guru 是一項受服務支援的機器學習 (ML)，可讓您輕鬆地改善應用程式的操作效能和可用性。DevOps Guru 會偵測到與正常操作模式不同的行為，因此您可以在這些問題影響客戶之前找出操作問題。DevOps Guru 會自動從您的 AWS 應用程式擷取操作資料，並提供單一儀表板，以視覺化方式呈現操作資料中的問題。您可以開始使用 DevOps Guru 來改善應用程式的可用性和可靠性，而無需手動設定或機器學習專業知識。

使用 Quick Setup 設定 DevOps Guru 在以下 AWS 區域 中可用：
+ 美國東部 (維吉尼亞北部)
+ 美國東部 (俄亥俄)
+ 美國西部 (奧勒岡)
+ 歐洲 (法蘭克福)
+ 歐洲 (愛爾蘭)
+ 歐洲 (斯德哥爾摩)
+ 亞太區域 (新加坡)
+ 亞太區域 (雪梨)
+ 亞太區域 (東京)

如需定價詳細資訊，請參閱 [Amazon DevOps Guru 定價](https://aws.amazon.com/devops-guru/pricing/)。

若要設定 DevOps Guru，請在 AWS Systems Manager Quick Setup 主控台中執行以下任務。

**若要使用 Quick Setup 設定 DevOps Guru**

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

1. 在導覽窗格中，選擇 **Quick Setup**。

1. 在 **DevOps Guru** 卡中，選擇**建立**。
**提示**  
如果您的帳戶中已有一或多個組態，請先選擇**程式庫**索引標籤或**組態**區段中的**建立**按鈕，以檢視卡。

1. 在 **Configuration options** (組態選項) 區段中，選擇您要分析的 AWS 資源類型和您的通知偏好設定。

   如果未選取**分析我組織中所有帳戶內的所有 AWS 資源**選項，您可以稍後在 DevOps Guru 主控台中選擇要分析的 AWS 資源。DevOps Guru 會分析不同的 AWS 資源類型 (例如 Amazon Simple Storage Service (Amazon S3) 儲存貯體和 Amazon Elastic Compute Cloud (Amazon EC2) 執行個體)，可分為兩個定價群組。您需針對每個作用中的資源支付分析的 AWS 資源小時數的費用。只有在一小時內產生指標、事件或日誌項目時，資源才會處於作用中狀態。您針對特定 AWS 資源類型支付的費率取決於價格群組。

   如果您選取 **Enable SNS notifications** (啟用 SNS 通知) 選項，即會在您的主題目標組織單位 (OU) 中的每個 AWS 帳戶 帳戶建立 Amazon Simple Notification Service (Amazon SNS) 主題。DevOps Guru 會使用此主題通知您重要的 DevOps Guru 事件，例如建立新的洞察。如果您未啟用此選項，您可以稍後在 DevOps Guru 主控台中新增主題。

   如果您選取 **Enable AWS Systems Manager OpsItems** (啟用 AWS Systems Manager OpsItems) 選項，即會為相關的 Amazon EventBridge 事件和 Amazon CloudWatch 警示建立營運工作項目 (OpsItems)。

1. 在 **Schedule** (排程) 區段中，選擇您希望 Quick Setup 修補對與您的組態不同的資源所做的變更的頻率。**Default** (預設) 選項會執行一次。如果您不要 Quick Setup 修復對與組態不同的資源所做的變更，請選擇 **Custom** (自訂) 下的 **Disabled** (已停用)。

1. 在 **Targets** (目標) 區段中，選擇是否允許 DevOps Guru 分析部分組織單位 (OU) 中的資源，或是您目前登入的帳戶。

   如果選擇 **Custom** (自訂)，請繼續步驟 8。

   如果選擇 **Current account** (目前帳戶)，請繼續步驟 9。

1. 在 **Target OUs** (目標 OU) 和 **Target Regions** (目標區域) 區段中，選取您要使用 DevOps Guru 的 OU 和區域的核取方塊。

1. 選擇您要在目前帳戶中使用 DevOps Guru 的區域。

1. 選擇**建立**。

# 使用 Quick Setup 部署 Distributor 套件
<a name="quick-setup-distributor"></a>

Distributor 是 中的工具 AWS Systems Manager。Distributor 套件是可安裝型軟體或可部署為單一實體的資產的集合。使用 Quick Setup，您可以在 和 AWS 帳戶 AWS 區域 中或跨 組織部署Distributor套件 AWS Organizations。目前，只有 EC2Launch v2 代理程式、Amazon Elastic File System (Amazon EFS) 公用程式套件和 Amazon CloudWatch 代理程式可以使用 Quick Setup 部署。如需有關 Distributor 的詳細資訊，請參閱「[AWS Systems Manager Distributor](distributor.md)」。

若要部署Distributor套件，請在 AWS Systems Manager Quick Setup 主控台中執行下列任務。

**若要使用 Quick Setup 部署 Distributor 套件**

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

1. 在導覽窗格中，選擇 **Quick Setup**。

1. 在**分發者**卡上，選擇**建立**。
**提示**  
如果您的帳戶中已有一或多個組態，請先選擇**程式庫**索引標籤或**組態**區段中的**建立**按鈕，以檢視卡。

1. 在 **Configuration options** (組態選項) 區段中，選擇您要部署的套件。

1. 在 **Targets** (目標) 區段中，選擇是否將套件部署至您的整個組織、某些組織單位 (OU) 或您目前登入的帳戶。

   如果您選擇 **Entire organization** (整個組織)，請繼續步驟 8。

   如果選擇 **Custom** (自訂)，請繼續步驟 7。

1. 在 **Target OUs** (目標 OU) 區段中，選取您要部署套件的 OU 和區域的核取方塊。

1. 選擇**建立**。

# 使用Quick Setup依照排程自動停止和啟動 EC2 執行個體
<a name="quick-setup-scheduler"></a>

使用 中的Quick Setup工具 AWS Systems Manager，您可以設定 Resource Scheduler 來自動啟動和停止 Amazon Elastic Compute Cloud (Amazon EC2) 執行個體。

此 Quick Setup 組態可根據您指定的排程啟動和停用執行個體，從而協助您降低營運成本。此工具可協助您避免在不需要執行個體時執行它們所產生不必要的成本。

例如，您目前可能會讓執行個體持續執行，即使每天僅使用 10 小時，每週僅 5 天。相反，您可以對執行個體進行排程，每天在工作時間後停用。因此，這些執行個體可以節省 70% 的費用，因為執行時間從 168 小時縮短為 50 小時。使用 Quick Setup 無需付費。但是，根據您設定的資源以及使用限制可能會產生費用，而對用於設定服務的服務不會收取任何費用。

使用資源排程器，您可以選擇 AWS 帳戶 根據您定義的排程，在多個 之間自動停止 AWS 區域 和啟動執行個體。Quick Setup 組態會使用您指定的標籤索引鍵和值來鎖定 Amazon EC2 執行個體。資源排程器只會停用或啟動其標籤符合您在組態中指定值的執行個體。請注意，如果連接至執行個體的 Amazon EBS 磁碟區已加密，您必須將 AWS KMS 金鑰所需的許可新增至 資源排程器的 IAM 角色，才能啟動執行個體。

**每個組態的執行個體數量上限**  
個別組態支援每個區域排程最多 5,000 個執行個體。如果您的案例需要在指定區域中排程 5,000 個以上的執行個體，則您必須建立多個組態。相應地標記您的執行個體，讓每個組態最多可管理 5,000 個執行個體。建立多個資源排程器 Quick Setup 組態時，您必須指定不同的標籤金鑰值。例如，一個組態可以使用值為 `Production` 的標籤键 `Environment`，而另一個則使用 `Environment` 和 `Development`。

**排程行為**  
下列要點說明排程組態的特定行為：
+ 只有當標記的執行個體處於 `Stopped` 狀態時，資源排程器才會啟動執行個體。同樣，只有在執行個體處於 `running` 狀態時，才會停用執行個體。資源排程器會在事件驅動模型上運作，並且只會在您指定的時間啟動或停用執行個體。例如，您可以建立在上午 9 點啟動執行個體的排程。資源排程器會啟動與您指定之標籤相關聯的所有執行個體，其在上午 9 點處於 `Stopped` 狀態 如果稍後手動停用執行個體，則資源排程器將不會再次啟動它們以維持 `Running` 狀態。同樣，如果根據排程在停用執行個體後手動啟動它，則資源排程器將不會再次停用執行個體。
+ 如果您建立的排程的開始時間晚於 24 小時制日內的停止時間，則資源排程器會假設您的執行個體在夜間執行。例如，您可以建立在晚上 9 點啟動執行個體，在早晨 7 點停用執行個體的排程。資源排程器會啟動與您指定之標籤相關聯的所有執行個體 (其在晚上 9 點處於 `Stopped` 狀態) 並在次日早晨 7 點停用。對於隔夜排程，開始時間適用於您為排程選取的天數。但是，停止時間適用於排程中的次日。
+ 建立排程組態時，執行個體的目前狀態可能會變更為符合排程的需求。

  例如，假設今天是星期三，而您為受管執行個體指定的排程*僅限*星期二和星期四的上午 9 點開始，下午 5 點停止。由於您目前的時間在執行個體執行的指定時間之外，它們會在建立組態後停止。執行個體在下一個指定的小時之前 (即星期四上午 9 點) 不會再次執行。

  如果您的執行個體目前處於 `Stopped` 狀態，且您指定了它們將在目前的時間執行的排程，則資源排程器會在建立組態後啟動它們。

如果您刪除組態，則執行個體將不會再根據先前定義的排程停用和啟動。在極少數情況下，執行個體可能會因為 API 操作失敗而無法成功停用或啟動。

若要設定 Amazon EC2 執行個體的排程，請在 AWS Systems Manager Quick Setup主控台中執行下列任務。

**使用 Quick Setup 設定執行個體排程**

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

1. 在導覽窗格中，選擇 **Quick Setup**。

1. 在**資源排程器**卡中，選擇**建立**。
**提示**  
如果您的帳戶中已有一或多個組態，請先選擇**程式庫**索引標籤或**組態**區段中的**建立**按鈕，以檢視卡。

1. 在 **Instance tag** (執行個體標籤) 區段中，指定套用至要與執行個體關聯之執行個體的標籤金鑰和值。

1. 在 **Schedule options** (排程選項) 區段中，指定要啟動和停用執行個體的時區、天數和時間。

1. 在 **Targets** (目標) 區段中，選擇是否為您的組織單位 (OU) 的 **Custom** (自訂) 群組設定排程，還是為您登入的 **Current account** (當前帳戶) 設定排程：
   + **Custom** (自訂) – 在 **Target OUs** (目標 OU) 區段中，選取您要設定排程的 OU。接著，在 **Target Regions** (目標) 區段中，選取您要設定排程的區域。
   + **目前帳戶** – 選取 **Current Region** (目前區域) 或 **Choose Regions** (選擇區域)。如果已選取 **Choose Regions** (選擇區域)，請選擇您要設定排程的 **Target Regions** (目標區域)。

1. 驗證 **Summary** (摘要) 區段中的排程資訊。

1. 選擇**建立**。

# AWS 資源總管 使用 設定 Quick Setup
<a name="Resource-explorer-quick-setup"></a>

使用 中的Quick Setup工具 AWS Systems Manager，您可以快速設定 AWS 資源總管 來搜尋和探索 中 AWS 帳戶 或整個 AWS 組織中的資源。您可以使用名稱、標籤和 ID 等中繼資料來搜尋資源。 AWS 資源總管 會使用*索引*來快速回應搜尋查詢。Resource Explorer 可使用各種資料來源建立並維護索引，以便收集 AWS 帳戶中資源的相關資訊。

Resource Explorer 的 Quick Setup 可自動執行索引組態程序。如需詳細資訊 AWS 資源總管，請參閱 AWS 資源總管 《 使用者指南》中的[什麼是 AWS 資源總管？](https://docs.aws.amazon.com/resource-explorer/latest/userguide/welcome.html)。

在使用 Quick Setup 期間，Resource Explorer 會執行下列動作：
+ 在 的每個 AWS 區域 中建立索引 AWS 帳戶。
+ 更新區域中指定為帳戶彙總工具索引的索引。
+ 在彙總工具索引區域中建立預設檢視。此檢視沒有篩選條件，因此會傳回在索引中發現的所有資源。

**最低許可**

若要執行下列程序中的步驟，必須擁有下列許可：
+ **動作**：`resource-explorer-2:*`，**資源**：沒有具體資源 (`*`)
+ **動作**：`iam:CreateServiceLinkedRole`，**資源**：沒有具體資源 (`*`)

**設定 Resource Explorer**

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

1. 在導覽窗格中，選擇 **Quick Setup**。

1. 在 **Resource Explorer** 卡中，選擇**建立**。

1. 在**彙總工具索引區域**區段中，選擇要包含**彙總工具索引**的區域。應該選取適合使用者地理位置的區域。

1. (選用) 選取**取代上方所選區域以外的區域中現有的彙總工具索引**核取方塊。

1. 在**目標**區段中，選擇包含了要探索資源的目標**組織**或特定**組織單位 (OU)**。

1. 在**區域**區段中，選擇要在組態中包含的**區域**。

1. 檢閱組態摘要，然後選擇**建立**。

在 **Resource Explorer** 頁面上，您可以監控組態狀態。

# 針對 Quick Setup 結果進行疑難排解
<a name="quick-setup-results-troubleshooting"></a>

使用下列資訊以協助您對 Quick Setup ( AWS Systems Manager中的工具) 的問題進行疑難排解。本主題包含根據 Quick Setup 問題類型解決問題的具體任務。

**問題：部署失敗**  
如果 CloudFormation 堆疊集在建立過程中失敗，則部署將失敗。使用以下步驟調查部署失敗的原因。

1. 導覽至 [AWS CloudFormation 主控台](https://console.aws.amazon.com/cloudformation)。

1. 選擇 Quick Setup 組態建立的堆疊。**Stack name** (堆疊名稱) 包括 `QuickSetup`，其後接著您選擇的組態類型，例如 `SSMHostMgmt`。
**注意**  
CloudFormation 有時會刪除失敗的堆疊部署。如果堆疊在 **Stacks** (堆疊) 資料表中不可用，請從篩選條件清單中選擇 **Deleted** (已刪除)。

1. 檢視 **Status** (狀態) 和 **Status reason** (狀態原因)。如需堆疊狀態的詳細資訊，請參閱《AWS CloudFormation 使用者指南**》中的[堆疊狀態碼](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/cfn-console-view-stack-data-resources.html#cfn-console-view-stack-data-resources-status-codes)。

1. 要想了解失敗的確切步驟，請在 **Events** (事件) 標籤中檢視每個事件的 **Status** (狀態)。

1. 檢閱《AWS CloudFormation 使用者指南》**中的[疑難排解](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/troubleshooting.html)。

1. 如果無法使用 CloudFormation 疑難排解步驟解決部署失敗問題，請刪除組態後重新設定。

**問題：關聯失敗**  
如果任何關聯在設定過程中失敗，**Configuration details** (組態詳細資訊) 頁面上的 **Configuration details** (組態詳細資訊) 資料表會顯示 **Configuration status** (組態狀態) 為 **Failed** (失敗)。使用以下步驟對失敗關聯進行疑難排解。

1. 在 **Configuration details** (組態詳細資訊) 資料表中選擇失敗組態，再選擇 **View Details** (檢視詳細資訊)。

1. 複製 **Association name** (關聯名稱)。

1. 導覽至 **State Manager**，然後將關聯名稱貼到搜尋欄位中。

1. 依序選擇關聯與 **Execution history** (執行歷史記錄) 標籤。

1. 在 **Execution ID (執行 ID)** 下方，選擇失敗的關聯執行。

1. **Association execution targets (關聯執行目標)** 頁面會列出執行關聯的所有節點。選擇執行失敗的 **Output (輸出)** 按鈕。

1. 在 **Output (輸出)** 頁面中，選擇 **Step - Output (步驟 - 輸出)** 以檢視命令執行中該步驟的錯誤訊息。每個步驟都可以顯示不同的錯誤訊息。請檢閱所有步驟的錯誤訊息，以協助對問題進行故障診段。
如果檢視步驟輸出無法解決問題，則可嘗試重新建立關聯。若要重新建立關聯，請先刪除 State Manager 中的失敗關聯。刪除關聯後，編輯組態並選擇刪除的選項，然後選擇 **Update** (更新)。  
若要調查 **Organization** (組織) 組態的 **Failed** (失敗) 關聯，您必須登入含失敗關聯的帳戶，然後如先前所述使用下列失敗關聯程序。從管理帳戶檢視結果時，**關聯 ID** 不是目標帳戶的超連結。

**問題：漂移狀態**  
在檢視組態的詳細資訊頁面時，您可以檢視每個部署的偏離狀態。只要使用者對服務或功能所做的變更會與透過 Quick Setup 所做的選擇產生衝突，就會發生組態偏離。如果關聯在初始組態之後發生了變更，資料表會顯示一個警告圖示，指示偏離項目的數量。將游標停留在圖示上，即可確認偏離的原因。
在 State Manager 中刪除關聯時，相關部署會顯示偏離警告。要想解決此問題，請編輯組態，然後選擇刪除關聯時移除的選項。選擇 **Update** (更新)，然後等待部署完成。