

翻訳は機械翻訳により提供されています。提供された翻訳内容と英語版の間で齟齬、不一致または矛盾がある場合、英語版が優先します。

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

## 概要
<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、Amazon Elastic Compute Cloud (Amazon EC2)、Amazon Relational Database Service (Amazon RDS)、Amazon Redshift、Amazon Simple Storage Service (Amazon S3) AWS のサービス などの の一般的なメンテナンス、デプロイ、修復タスクを簡素化します。Amazon S3 オートメーションを使用すると、自動化の同時実行性をきめ細かく制御できます。例えば、同時実行のターゲットにするリソースの数や、オートメーションを停止する前に許容可能なエラーの発生数を指定することが可能です。

ランブックのステップ、パラメータ、例など、実装の詳細については、「[追加情報](#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) アクセス許可
+ Systems Manager Agent (SSM Agent) が[インストールされた](https://docs.aws.amazon.com/systems-manager/latest/userguide/sysman-install-ssm-agent.html) EC2 インスタンス
+ ランブックを実行する予定のインスタンスにアタッチされた [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 エージェントバージョン 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 Automation

**ターゲットアーキテクチャ**

![\[Systems Manager 自動化タスクを Step Functions から同期的に実行するためのアーキテクチャ\]](http://docs.aws.amazon.com/ja_jp/prescriptive-guidance/latest/patterns/images/pattern-img/47c19e4f-d68d-4f91-bb68-202098757529/images/2d248aae-d858-4565-8af2-593cde0da780.png)


**自動化とスケール**
+ このパターンは、ランブックを複数のインスタンスにデプロイするために使用できる AWS CloudFormation テンプレートを提供します。(GitHub [Step Functions and Systems Manager implementation](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 リソースを大規模に安全に管理できます。

**コード**

このパターンのコードは、GitHub 内の「[Step Functions and Systems Manager implementation](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>


| タスク | 説明 | 必要なスキル | 
| --- | --- | --- | 
| 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)」を参照してください。 CloudFormation  CloudFormation テンプレートは 3 つのリソースをデプロイします。[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ja_jp/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>


| タスク | 説明 | 必要なスキル | 
| --- | --- | --- | 
| テストステートマシンを作成します。 | [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>このコードはランブックを呼び出して、Systems Manager Automation への `waitForTaskToken` 呼び出しを示す 2 つのコマンドを実行します。`shell` パラメータ値 (`Shell` または `PowerShell`) は、オートメーションドキュメントが `AWS-RunShellScript` または `AWS-RunPowerShellScript` を実行するかどうかを決定します。タスクは `/home/ssm-user/automation.log` ファイルに「これはテスト実行オートメーションの WaitForTaskToken」と書き込み、100 秒間スリープしてからタスクトークンが返され、ワークフロー内の次のタスクがリリースされます。代わりに `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 オートメーション間の同期呼び出しを検証します。 出力例については、「[追加情報](#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>

**実装の詳細**

このパターンは、2 つの Systems Manager ランブックをデプロイする CloudFormation テンプレートを提供します。
+ `SfnRunCommandByInstanceIds` は、インスタンス ID を使用して `AWS-RunShellScript` または `AWS-RunPowerShellScript` コマンドを実行します。
+ `SfnRunCommandByTargets` は、ターゲットを使用して `AWS-RunShellScript` または `AWS-RunPowerShellScript` コマンドを実行します。

各ランブックには、Step Functions の `.waitForTaskToken` オプションを使用する際に同期呼び出しを実現するための 4 つのステップが実装されています。


| 
| 
| [ステップ] | [アクション] | 説明 | 
| --- |--- |--- |
| **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\$1task\$1failure](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/stepfunctions/client/send_task_failure.html) API を呼び出し、ステートマシンから渡されたトークン、障害エラー、障害の原因の説明の 3 つのパラメータを入力として受け入れます。 | 
| **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 を呼び出します。 | 

**ランブックパラメータ**

`SfnRunCommandByInstanceIds` ランブック:


| 
| 
| パラメータ名 | タイプ | オプションまたは必須 | 説明 | 
| --- |--- |--- |--- |
| `shell` | 文字列 | 必須 | Linux で `AWS-RunShellScript` を実行するか Windows で `AWS-RunPowerShellScript` を実行するかを決定するインスタンスシェル。 | 
| `deliveryTimeout` | 整数 | オプションです。 | インスタンスの SSM Agent にコマンドが配信されるまで待機する時間 (秒単位)。このパラメータの最小値は 30 (0.5 分)、最大値は 2,592,000 (720 時間) です。 | 
| `executionTimeout` | String | オプションです。 | コマンドが失敗したと見なされるまでに完了するまでの時間 (秒単位)。デフォルト値は 3,600 (1 時間) です。最大値は 172800 (48 時間) です。 | 
| `workingDirectory` | String | オプションです。 | インスタンスの作業ディレクトリへのパス。 | 
| `Commands` | StringList | 必須 | 実行するシェルスクリプトまたはコマンド。 | 
| `InstanceIds` | StringList | 必須 | コマンドを実行するインスタンス ID です。 | 
| `taskToken` | String | 必須 | コールバックレスポンスに使用するタスクトークン。 | 

`SfnRunCommandByTargets` ランブック:


| 
| 
| 名前 | 型 | オプションまたは必須 | 説明 | 
| --- |--- |--- |--- |
| `shell` | 文字列 | 必須 | Linux で `AWS-RunShellScript` を実行するか Windows で `AWS-RunPowerShellScript` を実行するかを決定するインスタンスシェル。 | 
| `deliveryTimeout` | 整数 | オプションです。 | インスタンスの SSM Agent にコマンドが配信されるまで待機する時間 (秒単位)。このパラメータの最小値は 30 (0.5 分)、最大値は 2,592,000 (720 時間) です。 | 
| `executionTimeout` | 整数 | オプションです。 | コマンドが失敗したと見なされるまでに完了するまでの時間 (秒単位)。デフォルト値は 3,600 (1 時間) です。最大値は 172800 (48 時間) です。 | 
| `workingDirectory` | String | オプションです。 | インスタンスの作業ディレクトリへのパス。 | 
| `Commands` | StringList | 必須 | 実行するシェルスクリプトまたはコマンド。 | 
| `Targets` | MapList | 必須 | 指定したキーと値のペアを使用してインスタンスを識別する検索条件の配列。例: `[{"Key":"InstanceIds","Values":["i-02573cafcfEXAMPLE","i-0471e04240EXAMPLE"]}]` | 
| `taskToken` | String | 必須 | コールバックレスポンスに使用するタスクトークン。 | 

**出力例**

次の表に、ステップ関数からの出力例を示します。ステップ 5 (`TaskSubmitted`) からステップ 6 (`TaskSucceeded`) までの合計実行時間が 100 秒を超えていることがわかります。これは、step 関数が `sleep 100` コマンドが終了するのを待ってから、ワークフロー内の次のタスクに移ったことを示しています。


| 
| 
| ID | タイプ | [ステップ] | [リソース] | 経過時間 (ミリ秒) | タイムスタンプ | 
| --- |--- |--- |--- |--- |--- |
| ** 1** | `ExecutionStarted` |  | - | 0 | 2022 年 3 月 11 日午後 2 時 50 分 34.303 秒 | 
| ** 2** | `TaskStateEntered` | `StartAutomationWaitForCallBack` | - | 40 | 2022 年 3 月 11 日午後 2 時 50 分 34.343 秒 | 
| ** 3** | `TaskScheduled` | `StartAutomationWaitForCallBack` | - | 40 | 2022 年 3 月 11 日午後 2 時 50 分 34.343 秒 | 
| ** 4** | `TaskStarted` | `StartAutomationWaitForCallBack` | - | 154 | 2022 年 3 月 11 日午後 2 時 50 分 34.457 秒 | 
| ** 5** | `TaskSubmitted` | `StartAutomationWaitForCallBack` | - | 657 | 2022 年 3 月 11 日午後 2 時 50 分 34.960 秒 | 
| ** 6** | `TaskSucceeded` | `StartAutomationWaitForCallBack` | - | 103835 | 2022 年 3 月 11 日午後 2 時 52 分 18.138 秒 | 
| ** 7** | `TaskStateExited` | `StartAutomationWaitForCallBack` | - | 103860 | 2022 年 3 月 11 日午後 2 時 52 分 18.163 秒 | 
| ** 8** | `ExecutionSucceeded` |  | - | 103897 | 2022 年 3 月 11 日午後 2 時 52 分 18.200 秒 | 