

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

# 從 AWS Step Functions 同步執行 AWS Systems Manager 自動化任務 AWS Step Functions
<a name="run-aws-systems-manager-automation-tasks-synchronously-from-aws-step-functions"></a>

*Elie El khoury，Amazon Web Services*

## 總結
<a name="run-aws-systems-manager-automation-tasks-synchronously-from-aws-step-functions-summary"></a>

此模式說明如何 AWS Step Functions 與 整合 AWS Systems Manager。它使用 AWS SDK 服務整合，從狀態機器工作流程使用任務字符呼叫 Systems Manager **startAutomationExecution** API，並暫停直到字符傳回成功或失敗呼叫。為了示範整合，此模式會實作圍繞 `AWS-RunShellScript`或 文件的自動化`AWS-RunPowerShellScript`文件 （執行手冊） 包裝函式，並使用 `.waitForTaskToken` 同步呼叫 `AWS-RunShellScript`或 `AWS-RunPowerShellScript`。如需 Step Functions 中 AWS SDK 服務整合的詳細資訊，請參閱 [AWS Step Functions 開發人員指南](https://docs.aws.amazon.com/step-functions/latest/dg/supported-services-awssdk.html)。

Step Functions ****是一種低程式碼的視覺化工作流程服務，可用來建置分散式應用程式、自動化 IT 和業務流程，以及使用 AWS 服務建置資料和機器學習管道。工作流程會管理故障、重試、平行化、服務整合和可觀測性，讓您可以專注於更高價值的商業邏輯。

自動化是 的功能 AWS Systems Manager，可簡化常見的維護、部署和修復任務， AWS 服務 例如 Amazon Elastic Compute Cloud (Amazon EC2)、Amazon Relational Database Service (Amazon RDS)、Amazon Redshift 和 Amazon Simple Storage Service (Amazon S3)。自動化可讓您精細控制自動化的並行。例如，您可以指定要同時鎖定多少資源，以及在自動化停止之前可以發生的錯誤數量。

如需實作詳細資訊，包括 Runbook 步驟、參數和範例，請參閱[其他資訊](#run-aws-systems-manager-automation-tasks-synchronously-from-aws-step-functions-additional)一節。

## 先決條件和限制
<a name="run-aws-systems-manager-automation-tasks-synchronously-from-aws-step-functions-prereqs"></a>

**先決條件**
+ 作用中 AWS 的帳戶
+ AWS Identity and Access Management 存取 Step Functions 和 Systems Manager 的 (IAM) 許可
+ [執行個體](https://docs.aws.amazon.com/systems-manager/latest/userguide/sysman-install-ssm-agent.html)上安裝 Systems Manager Agent (SSM Agent) 的 EC2 執行個體
+ 連接至您計劃執行 Runbook [之執行個體的 Systems Manager IAM 執行個體描述](https://docs.aws.amazon.com/systems-manager/latest/userguide/setup-instance-profile.html)檔
+ 具有下列 IAM 許可的 Step Functions 角色 （遵循最低權限原則）：

```
{
             "Effect": "Allow",
             "Action": "ssm:StartAutomationExecution",
             "Resource": "*"
 }
```

**產品版本**
+ SSM 文件結構描述 0.3 版或更新版本
+ SSM Agent 2.3.672.0 版或更新版本

## Architecture
<a name="run-aws-systems-manager-automation-tasks-synchronously-from-aws-step-functions-architecture"></a>

**目標技術堆疊**
+ AWS Step Functions
+ AWS Systems Manager  自動化

**目標架構**

![\[從 Step Functions 同步執行 Systems Manager 自動化任務的架構\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/images/pattern-img/47c19e4f-d68d-4f91-bb68-202098757529/images/2d248aae-d858-4565-8af2-593cde0da780.png)


**自動化和擴展**
+ 此模式提供 AWS CloudFormation 範本，可用來在多個執行個體上部署 Runbook。（請參閱 GitHub [Step Functions 和 Systems Manager 實作](https://github.com/aws-samples/amazon-stepfunctions-ssm-waitfortasktoken)儲存庫。)

## 工具
<a name="run-aws-systems-manager-automation-tasks-synchronously-from-aws-step-functions-tools"></a>

**AWS 服務**
+ [AWS CloudFormation](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/Welcome.html) 可協助您設定 AWS 資源、快速且一致地佈建資源，以及在整個 AWS 帳戶 和 區域的生命週期中管理資源。
+ [AWS Identity and Access Management (IAM)](https://docs.aws.amazon.com/IAM/latest/UserGuide/introduction.html) 透過控制已驗證並獲授權使用的人員，協助您安全地管理對 AWS 資源的存取。
+ [AWS Step Functions](https://docs.aws.amazon.com/step-functions/latest/dg/welcome.html) 是一種無伺服器協同運作服務，可協助您結合 AWS Lambda 函數和其他 AWS 服務 來建置業務關鍵型應用程式。
+ [AWS Systems Manager](https://docs.aws.amazon.com/systems-manager/latest/userguide/what-is-systems-manager.html) 可協助您管理在 中執行的應用程式和基礎設施 AWS 雲端。它可簡化應用程式和資源管理、縮短偵測和解決操作問題的時間，並協助您大規模安全地管理 AWS 資源。

**Code**

此模式的程式碼可在 GitHub [Step Functions 和 Systems Manager 實作](https://github.com/aws-samples/amazon-stepfunctions-ssm-waitfortasktoken)儲存庫中使用。 

## 史詩
<a name="run-aws-systems-manager-automation-tasks-synchronously-from-aws-step-functions-epics"></a>

### 建立 Runbook
<a name="create-runbooks"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 下載 CloudFormation 範本。 | 從 GitHub 儲存庫的 `cloudformation `資料夾下載`ssm-automation-documents.cfn.json`範本。 | AWS DevOps | 
| 建立 Runbook。 | 登入 AWS 管理主控台，開啟 [CloudFormation 主控台](https://console.aws.amazon.com/cloudformation/)，然後部署 範本。如需部署 CloudFormation 範本的詳細資訊，請參閱 CloudFormation 文件中的[在 CloudFormation 主控台上建立堆疊](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/cfn-console-create-stack.html)。 CloudFormation 範本會部署三個資源：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/run-aws-systems-manager-automation-tasks-synchronously-from-aws-step-functions.html) | AWS DevOps | 

### 建立範例狀態機器
<a name="create-a-sample-state-machine"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 建立測試狀態機器。 | 遵循 [AWS Step Functions 開發人員指南](https://docs.aws.amazon.com/step-functions/latest/dg/getting-started-with-sfn.html)中的指示來建立和執行狀態機器。針對 定義，請使用下列程式碼。請務必使用帳戶中啟用 Systems Manager 之有效執行個體的 ID 來更新`InstanceIds`值。<pre>{<br />  "Comment": "A description of my state machine",<br />  "StartAt": "StartAutomationWaitForCallBack",<br />  "States": {<br />    "StartAutomationWaitForCallBack": {<br />      "Type": "Task",<br />      "Resource": "arn:aws:states:::aws-sdk:ssm:startAutomationExecution.waitForTaskToken",<br />      "Parameters": {<br />        "DocumentName": "SfnRunCommandByInstanceIds",<br />        "Parameters": {<br />          "InstanceIds": [<br />            "i-1234567890abcdef0"<br />          ],<br />          "taskToken.$": "States.Array($$.Task.Token)",<br />          "workingDirectory": [<br />            "/home/ssm-user/"<br />          ],<br />          "Commands": [<br />            "echo \"This is a test running automation waitForTaskToken\" >> automation.log",<br />            "sleep 100"<br />          ],<br />          "executionTimeout": [<br />              "10800"<br />          ],<br />          "deliveryTimeout": [<br />              "30"<br />          ],<br />          "shell": [<br />              "Shell"<br />          ]<br />            }<br />      },<br />      "End": true<br />    }<br />  }<br />}</pre>此程式碼會呼叫 Runbook 來執行兩個命令，以示範對 Systems Manager Automation 的`waitForTaskToken`呼叫。`shell` 參數值 (`Shell` 或 `PowerShell`) 會決定自動化文件是執行 `AWS-RunShellScript`還是 `AWS-RunPowerShellScript`。任務會將「這是執行自動化 waitForTaskToken」的測試寫入 `/home/ssm-user/automation.log` 檔案，然後休眠 100 秒，再以任務字符回應，並釋出工作流程中的下一個任務。如果您想要改為呼叫 `SfnRunCommandByTargets`Runbook，請將上一個程式碼的 `Parameters`區段取代為下列項目：<pre>"Parameters": {<br />          "Targets": [<br />            {<br />              "Key": "InstanceIds",<br />              "Values": [<br />                "i-02573cafcfEXAMPLE",<br />                "i-0471e04240EXAMPLE"<br />              ]<br />            }<br />          ],</pre> | AWS DevOps | 
| 更新狀態機器的 IAM 角色。 | 上一個步驟會自動為狀態機器建立專用 IAM 角色。不過，它不會授予呼叫 Runbook 的許可。透過新增下列許可來更新角色：<pre>{<br />      "Effect": "Allow",<br />      "Action": "ssm:StartAutomationExecution",<br />      "Resource": "*"<br /> }</pre> | AWS DevOps | 
| 驗證同步呼叫。 | 執行狀態機器以驗證 Step Functions 與 Systems Manager Automation 之間的同步呼叫。 如需範例輸出，請參閱[其他資訊](#run-aws-systems-manager-automation-tasks-synchronously-from-aws-step-functions-additional)一節。  | AWS DevOps | 

## 相關資源
<a name="run-aws-systems-manager-automation-tasks-synchronously-from-aws-step-functions-resources"></a>
+ [入門 AWS Step Functions](https://docs.aws.amazon.com/step-functions/latest/dg/getting-started-with-sfn.html)(*AWS Step Functions 開發人員指南*)
+ [使用任務字符等待回呼](https://docs.aws.amazon.com/step-functions/latest/dg/connect-to-resource.html#connect-wait-token) *AWS Step Functions （開發人員指南*，服務整合模式）
+ [send\$1task\$1success](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/stepfunctions/client/send_task_success.html) 和 [send\$1task\$1failure](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/stepfunctions/client/send_task_failure.html) API 呼叫 (Boto3 文件） 
+ [AWS Systems Manager 自動化](https://docs.aws.amazon.com/systems-manager/latest/userguide/systems-manager-automation.html) (*AWS Systems Manager 使用者指南*)

## 其他資訊
<a name="run-aws-systems-manager-automation-tasks-synchronously-from-aws-step-functions-additional"></a>

**實作詳細資訊**

此模式提供 CloudFormation 範本，可部署兩個 Systems Manager Runbook：
+ `SfnRunCommandByInstanceIds`會使用執行個體 IDs 執行 `AWS-RunShellScript`或 `AWS-RunPowerShellScript`命令。
+ `SfnRunCommandByTargets`使用目標執行 `AWS-RunShellScript`或 `AWS-RunPowerShellScript`命令。

每個 Runbook 都會實作四個步驟，以在 Step Functions 中使用 `.waitForTaskToken`選項時實現同步呼叫。


| 
| 
| 步驟 | Action | Description | 
| --- |--- |--- |
| **1** | `Branch` | 檢查`shell`參數值 (`Shell` 或 `PowerShell`)，以決定是否要`AWS-RunShellScript`針對 Linux 或 `AWS-RunPowerShellScript` Windows 執行 。 | 
| **2** | `RunCommand_Shell` 或 `RunCommand_PowerShell` | 接受數個輸入並執行 `RunShellScript`或 `RunPowerShellScript`命令。如需詳細資訊，請參閱 Systems Manager 主控台上 `RunCommand_Shell`或`RunCommand_PowerShell`自動化文件**的詳細資訊**索引標籤。 | 
| **3** | `SendTaskFailure` | 步驟 2 中止或取消時執行。它呼叫 Step Functions [send\$1task\$1failure](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/stepfunctions/client/send_task_failure.html) API，接受三個參數做為輸入：狀態機器傳遞的字符、失敗錯誤，以及失敗原因的描述。 | 
| **4** | `SendTaskSuccess` | 步驟 2 成功時執行。它呼叫 Step Functions [send\$1task\$1success](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/stepfunctions/client/send_task_success.html) API，該 API 接受狀態機器傳遞的字符作為輸入。 | 

**Runbook 參數**

`SfnRunCommandByInstanceIds` Runbook：


| 
| 
| 參數名稱 | Type | 選用或必要 | Description | 
| --- |--- |--- |--- |
| `shell` | String | 必要 | 執行個體 shell，用於決定是否`AWS-RunShellScript`要針對 Linux 或 Windows `AWS-RunPowerShellScript` 執行。 | 
| `deliveryTimeout` | Integer | 選用 | 等待命令交付至執行個體上 SSM 代理程式的時間，以秒為單位。此參數的最小值為 30 (0.5 分鐘），最大值為 2592000 (720 小時）。 | 
| `executionTimeout` | String | 選用 | 命令在被視為失敗之前完成的時間，以秒為單位。預設值為 3600 (1 小時）。最大值為 172800 (48 小時）。 | 
| `workingDirectory` | String | 選用 | 在您的執行個體上的工作目錄路徑。 | 
| `Commands` | StringList | 必要 | 要執行的 shell 指令碼或命令。 | 
| `InstanceIds` | StringList | 必要 | 您要執行命令之執行個體的 IDs。 | 
| `taskToken` | String | 必要 | 用於回呼回應的任務字符。 | 

`SfnRunCommandByTargets`Runbook：


| 
| 
| Name | 類型 | 選用或必要 | Description | 
| --- |--- |--- |--- |
| `shell` | String | 必要 | 執行個體 shell，以決定是否`AWS-RunShellScript`要針對 Linux 或 Windows `AWS-RunPowerShellScript` 執行。 | 
| `deliveryTimeout` | Integer | 選用 | 等待命令交付至執行個體上 SSM 代理程式的時間，以秒為單位。此參數的最小值為 30 (0.5 分鐘），最大值為 2592000 (720 小時）。 | 
| `executionTimeout` | Integer | 選用 | 命令在被視為失敗之前完成的時間，以秒為單位。預設值為 3600 (1 小時）。最大值為 172800 (48 小時）。 | 
| `workingDirectory` | String | 選用 | 在您的執行個體上的工作目錄路徑。 | 
| `Commands` | StringList | 必要 | 要執行的 shell 指令碼或命令。 | 
| `Targets` | MapList | 必要 | 使用您指定的鍵值對來識別執行個體的搜尋條件陣列。例如：`[{"Key":"InstanceIds","Values":["i-02573cafcfEXAMPLE","i-0471e04240EXAMPLE"]}]` | 
| `taskToken` | String | 必要 | 用於回呼回應的任務字符。 | 

**範例輸出**

下表提供 步驟函數的範例輸出。它顯示步驟 5 (`TaskSubmitted`) 和步驟 6 () 之間的總執行時間超過 100 秒`TaskSucceeded`。這會示範步驟函數等待`sleep 100`命令完成，然後再移至工作流程中的下一個任務。


| 
| 
| ID | Type | 步驟 | 資源 | 經過時間 （毫秒） | 時間戳記 | 
| --- |--- |--- |--- |--- |--- |
| **1** | `ExecutionStarted` |  | - | 0 | 2022 年 3 月 11 日下午 02：50：34.303 | 
| **2** | `TaskStateEntered` | `StartAutomationWaitForCallBack` | - | 40 | 2022 年 3 月 11 日下午 02：50：34.343 | 
| **3** | `TaskScheduled` | `StartAutomationWaitForCallBack` | - | 40 | 2022 年 3 月 11 日下午 02：50：34.343 | 
| **4** | `TaskStarted` | `StartAutomationWaitForCallBack` | - | 154 | 2022 年 3 月 11 日下午 02：50：34.457 | 
| **5** | `TaskSubmitted` | `StartAutomationWaitForCallBack` | - | 657 | 2022 年 3 月 11 日下午 02：50：34.960 | 
| **6** | `TaskSucceeded` | `StartAutomationWaitForCallBack` | - | 103835 | 2022 年 3 月 11 日下午 02：52：18.138 | 
| **7** | `TaskStateExited` | `StartAutomationWaitForCallBack` | - | 103860 | 2022 年 3 月 11 日下午 02：52：18.163 | 
| **8** | `ExecutionSucceeded` |  | - | 103897 | 2022 年 3 月 11 日下午 02：52：18：200 | 