

本文属于机器翻译版本。若本译文内容与英语原文存在差异，则一律以英文原文为准。

# 从 AWS Step Functions 同步运行 AWS Systems Manager Automation 任务
<a name="run-aws-systems-manager-automation-tasks-synchronously-from-aws-step-functions"></a>

*Elie El khoury，Amazon Web Services*

## Summary
<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 工具包服务集成的更多信息，请参阅[AWS Step Functions 开发者指南](https://docs.aws.amazon.com/step-functions/latest/dg/supported-services-awssdk.html)。

Step Function**** s 是一项低代码的可视化工作流服务，您可以使用它来构建分布式应用程序、自动执行 IT 和业务流程，以及使用 AWS 服务构建数据和机器学习管道。工作流程可以管理故障、重试、并行化、服务集成和可观测性，因此您可以专注于更高价值的业务逻辑。

自动化是一项功能，可简化亚马逊弹性计算云（亚马逊）、亚马逊关系数据库服务（Amazon RDS EC2）、Amazon Redshift和亚马逊简单存储服务（Amazon S3） AWS 服务 等的常见维护、部署和补救任务。 AWS Systems Manager自动化使您可以精确控制自动化的并发性。例如，您可以指定同时定位多少资源，以及在停止自动化之前可能发生的错误数。

有关实施的详细信息，包括运行手册步骤、参数和示例，请参阅[其他信息](#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 (IAM) 访问 Step Functions 和 Systems Manager 的权限
+  EC2 实例上[安装](https://docs.aws.amazon.com/systems-manager/latest/userguide/sysman-install-ssm-agent.html)了 Systems Manager 代理（SSM 代理）
+ [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 或更高版本

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

**目标技术堆栈**
+ AWS Step Functions
+ AWS Systems Manager  自动化

**目标架构**

![从 AWS Step Functions 同步运行 Systems Manager Automation 任务的架构](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/images/pattern-img/47c19e4f-d68d-4f91-bb68-202098757529/images/2d248aae-d858-4565-8af2-593cde0da780.png)


**自动化和扩展**
+ 此模式提供了一个 AWS CloudFormation 模板，您可以使用该模板在多个实例上部署运行手册。（请参阅 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 Cloud端运行的应用程序和基础设施。它简化了应用程序和资源管理，缩短了检测和解决操作问题的时间，并帮助您大规模安全地管理 AWS 资源。

**代码**

此模式的代码可在 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>

### 创建运行手册
<a name="create-runbooks"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 下载 CloudFormation 模板。 | 从 GitHub 存储库的`cloudformation `文件夹下载`ssm-automation-documents.cfn.json`模板。 | AWS DevOps | 
| 创建运行手册。 | 登录 AWS 管理控制台，打开[CloudFormation 控制台](https://console.aws.amazon.com/cloudformation/)，然后部署模板。有关部署 CloudFormation 模板的更多信息，请参阅 CloudFormation 文档中的在[CloudFormation 控制台上创建堆栈](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/cfn-console-create-stack.html)。 <br />该 CloudFormation 模板部署了三个资源：[See the AWS documentation website for more details](http://docs.aws.amazon.com/zh_cn/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>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 创建测试状态机。 | 按照 [AWS Step Functions 开发人员指南](https://docs.aws.amazon.com/step-functions/latest/dg/getting-started-with-sfn.html)中的说明创建和运行状态机。对于定义，请使用以下代码。请务必使用您账户中启用系统管理器的有效实例的 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><br />此代码调用运行手册来运行两个命令来演示对 Systems Manager Automation 的 `waitForTaskToken` 调用。<br />`shell` 参数值（`Shell` 或 `PowerShell`）决定了该自动化文档是运行 `AWS-RunShellScript` 还是 `AWS-RunPowerShellScript`。<br />该任务将 “这是测试运行自动化 waitForTask令牌” 写入`/home/ssm-user/automation.log`文件，然后休眠 100 秒，然后使用任务令牌进行响应并释放工作流程中的下一个任务。<br />如果要改为调用 `SfnRunCommandByTargets` 运行手册，请将前述代码的 `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 角色。但是，它不授予调用运行手册的权限。通过添加以下权限来更新角色：<pre>{<br />      "Effect": "Allow",<br />      "Action": "ssm:StartAutomationExecution",<br />      "Resource": "*"<br /> }</pre> | AWS DevOps | 
| 验证同步调用。 | 运行状态机以验证 Step Functions 和 Systems Manager Automation 之间的同步调用。 <br />有关示例输出，请参阅[其他信息](#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\_task\_success](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/stepfunctions/client/send_task_success.html) 和 [send\_task\_failure](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>

**实施详情**

此模式提供了一个部署两个 Systems Manager 运行手册的 CloudFormation 模板：
+ `SfnRunCommandByInstanceIds`使用实例运行`AWS-RunShellScript`或`AWS-RunPowerShellScript`命令 IDs。
+ `SfnRunCommandByTargets` 使用目标运行 `AWS-RunShellScript` 或 `AWS-RunPowerShellScript` 命令。

使用 Step Functions 中的 `.waitForTaskToken` 选项时，每个运行手册都实施四个步骤来实施同步调用。


| 
| 
| 步骤 | Action | 说明 | 
| --- |--- |--- |
| **1** | `Branch` | 检查 `shell` 参数值（`Shell` 或 `PowerShell`），以决定是运行适用于 Linux 的 `AWS-RunShellScript` 还是运行适用于 Windows 的 `AWS-RunPowerShellScript`。 | 
| **2** | `RunCommand_Shell` 或 `RunCommand_PowerShell` | 接受多个输入并运行 `RunShellScript` 或 `RunPowerShellScript` 命令。有关更多信息，请在 Systems Manager 控制台的**详细信息**选项卡中查看 `RunCommand_Shell` 或 `RunCommand_PowerShell` 自动化文档。 | 
| **3** | `SendTaskFailure` | 在步骤 2 中止或取消时运行。它调用 Step Functions [send\_task\_failure](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/stepfunctions/client/send_task_failure.html) API，该 API 接受三个参数作为输入：状态机传递的令牌、失败错误和对失败原因的描述。 | 
| **4** | `SendTaskSuccess` | 在步骤 2 成功时运行。它调用 Step Functions [send\_task\_success](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/stepfunctions/client/send_task_success.html) API，该 API 接受状态机传递的令牌作为输入。 | 

**运行手册参数**

`SfnRunCommandByInstanceIds` 运行手册：


| 
| 
| 参数名称 | Type | 必需或可选 | 说明 | 
| --- |--- |--- |--- |
| `shell` | 字符串 | 必需 | 实例 Shell，决定是运行适用于 Linux 的 `AWS-RunShellScript` 还是运行适用于 Windows 的 `AWS-RunPowerShellScript`。 | 
| `deliveryTimeout` | 整数 | 可选 | 等待命令传递到实例上的 SSM Agent 的时间（单位：秒）。此参数的最小值为 30（0.5 分钟），最大值为 2592000（720 小时）。 | 
| `executionTimeout` | 字符串 | 可选 | 在被视为已失败前命令将运行的时间（单位：秒）。默认值为 3600（1 小时）。最长值为 172800（48 小时）。 | 
| `workingDirectory` | 字符串 | 可选 | 实例上工作目录的路径。 | 
| `Commands` | StringList | 必需 | 要运行的 Shell 脚本或命令。 | 
| `InstanceIds` | StringList | 必需 | 您要在其中运行命令的实例。 IDs  | 
| `taskToken` | 字符串 | 必需 | 用于回调响应的任务令牌。 | 

`SfnRunCommandByTargets` 运行手册：


| 
| 
| Name | Type | 必需或可选 | 说明 | 
| --- |--- |--- |--- |
| `shell` | 字符串 | 必需 | 实例 Shell，决定是运行适用于 Linux 的 `AWS-RunShellScript` 还是运行适用于 Windows 的 `AWS-RunPowerShellScript`。 | 
| `deliveryTimeout` | 整数 | 可选 | 等待命令传递到实例上的 SSM Agent 的时间（单位：秒）。此参数的最小值为 30（0.5 分钟），最大值为 2592000（720 小时）。 | 
| `executionTimeout` | 整数 | 可选 | 在被视为已失败前命令将运行的时间（单位：秒）。默认值为 3600（1 小时）。最长值为 172800（48 小时）。 | 
| `workingDirectory` | 字符串 | 可选 | 实例上工作目录的路径。 | 
| `Commands` | StringList | 必需 | 要运行的 Shell 脚本或命令。 | 
| `Targets` | MapList | 必需 | 一组搜索条件，使用您指定的键值对来识别实例。例如：`[{"Key":"InstanceIds","Values":["i-02573cafcfEXAMPLE","i-0471e04240EXAMPLE"]}]` | 
| `taskToken` | 字符串 | 必需 | 用于回调响应的任务令牌。 | 

**示例输出**

下表提供了 Step 函数的示例输出。它显示步骤 5（`TaskSubmitted`）和步骤 6（`TaskSucceeded`）之间的总运行时间超过 100 秒。这表明 Step 函数在等待 `sleep 100` 命令完成后才进入工作流程中的下一个任务。


| 
| 
| ID | Type | 步骤 | 资源 | 运行时间 (ms) | Timestamp | 
| --- |--- |--- |--- |--- |--- |
| **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 | 