

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

# CloudFormation を使用して Step Functions でワークフローを作成する
<a name="tutorial-lambda-state-machine-cloudformation"></a>

このチュートリアルでは、 を使用して AWS Lambda 関数を作成します AWS CloudFormation。 CloudFormation コンソールと YAML テンプレートを使用して*スタック* (IAM ロール、Lambda 関数、ステートマシン) を作成します。その後、Step Functions コンソールを使用してステートマシンの実行を開始します。

詳細については、*AWS CloudFormation ユーザーガイド*の [CloudFormation テンプレートの使用](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/template-guide.html)と `[AWS::StepFunctions::StateMachine](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-stepfunctions-statemachine.html)` リソースを参照してください。

## ステップ 1: CloudFormation テンプレートを設定する
<a name="lambda-state-machine-cfn-step-1"></a>

[サンプルテンプレート](#lambda-state-machine-cfn-step-2)を使用する前に、 CloudFormation テンプレートのさまざまな部分を宣言する方法を理解しておく必要があります。

### Lambda 用に IAM ロールを作成するには
<a name="lambda-state-machine-cfn-procedure-create-iam-role"></a>

Lambda 関数の IAM ロールに関連付けられた信頼ポリシーを定義します。以下の例では、YAML または JSON を使用して信頼ポリシーを定義しています。

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

```
LambdaExecutionRole:
    Type: "AWS::IAM::Role"
    Properties:
      AssumeRolePolicyDocument:
        Version: "2012-10-17"		 	 	 
        Statement:
          - Effect: Allow
            Principal:
              Service: lambda.amazonaws.com
            Action: "sts:AssumeRole"
```

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

```
          "LambdaExecutionRole": {
              "Type": "AWS::IAM::Role",
              "Properties": {
                  "AssumeRolePolicyDocument": {
                      "Version": "2012-10-17",		 	 	 
                      "Statement": [
                          {
                              "Effect": "Allow",
                              "Principal": {
                                  "Service": "lambda.amazonaws.com"
                              },
                              "Action": "sts:AssumeRole"
                          }
                      ]
                  }
              }
```

------

### Lambda 関数を作成するには
<a name="lambda-state-machine-cfn-create-function"></a>

`Hello World` というメッセージを印刷する Lambda 関数の以下のプロパティを定義します。

**重要**  
Lambda 関数が AWS リージョン ステートマシンと同じ AWS アカウントにあることを確認します。

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

```
MyLambdaFunction:
    Type: "AWS::Lambda::Function"
    Properties:
      Handler: "index.handler"
      Role: !GetAtt [ LambdaExecutionRole, Arn ]
      Code:
        ZipFile: |
          exports.handler = (event, context, callback) => {
              callback(null, "Hello World!");
          };
      Runtime: "nodejs12.x"
      Timeout: "25"
```

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

```
        "MyLambdaFunction": {
              "Type": "AWS::Lambda::Function",
              "Properties": {
                  "Handler": "index.handler",
                  "Role": {
                      "Fn::GetAtt": [
                          "LambdaExecutionRole",
                          "Arn"
                      ]
                  },
                  "Code": {
                      "ZipFile": "exports.handler = (event, context, callback) => {\n    callback(null, \"Hello World!\");\n};\n"
                  },
                  "Runtime": "nodejs12.x",
                  "Timeout": "25"
              }
          },
```

------

### ステートマシンの実行用の IAM ロールを作成するには
<a name="lambda-state-machine-cfn-create-role"></a>

ステートマシンの実行の IAM ロールに関連付けられた信頼ポリシーを定義します。

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

```
StatesExecutionRole:
    Type: "AWS::IAM::Role"
    Properties:
      AssumeRolePolicyDocument:
        Version: "2012-10-17"		 	 	 
        Statement:
          - Effect: "Allow"
            Principal:
              Service:
                - !Sub states.${AWS::Region}.amazonaws.com
            Action: "sts:AssumeRole"
      Path: "/"
      Policies:
        - PolicyName: StatesExecutionPolicy
          PolicyDocument:
            Version: "2012-10-17"		 	 	 
            Statement:
              - Effect: Allow
                Action:
                  - "lambda:InvokeFunction"
                Resource: "*"
```

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

```
        "StatesExecutionRole": {
              "Type": "AWS::IAM::Role",
              "Properties": {
                  "AssumeRolePolicyDocument": {
                      "Version": "2012-10-17",		 	 	 
                      "Statement": [
                          {
                              "Effect": "Allow",
                              "Principal": {
                                  "Service": [
                                      {
                                          "Fn::Sub": "states.${AWS::Region}.amazonaws.com"
                                      }
                                  ]
                              },
                              "Action": "sts:AssumeRole"
                          }
                      ]
                  },
                  "Path": "/",
                  "Policies": [
                      {
                          "PolicyName": "StatesExecutionPolicy",
                          "PolicyDocument": {
                              "Version": "2012-10-17",		 	 	 
                              "Statement": [
                                  {
                                      "Effect": "Allow",
                                      "Action": [
                                          "lambda:InvokeFunction"
                                      ],
                                      "Resource": "*"
                                  }
                              ]
                          }
                      }
                  ]
              }
          },
```

------

### Lambda ステートマシンを作成するには
<a name="lambda-state-machine-cfn-create"></a>

Lambda ステートマシンを定義します。

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

```
MyStateMachine:
    Type: "AWS::StepFunctions::StateMachine"
    Properties:
      DefinitionString:
        !Sub
          - |-
            {
              "Comment": "A Hello World example using an AWS Lambda function",
              "StartAt": "HelloWorld",
              "States": {
                "HelloWorld": {
                  "Type": "Task",
                  "Resource": "${lambdaArn}",
                  "End": true
                }
              }
            }
          - {lambdaArn: !GetAtt [ MyLambdaFunction, Arn ]}
      RoleArn: !GetAtt [ StatesExecutionRole, Arn ]
```

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

```
        "MyStateMachine": {
              "Type": "AWS::StepFunctions::StateMachine",
              "Properties": {
                  "DefinitionString": {
                      "Fn::Sub": [
                          "{\n  \"Comment\": \"A Hello World example using an AWS Lambda function\",\n  \"StartAt\": \"HelloWorld\",\n  \"States\": {\n    \"HelloWorld\": {\n      \"Type\": \"Task\",\n      \"Resource\": \"${lambdaArn}\",\n      \"End\": true\n    }\n  }\n}",
                          {
                              "lambdaArn": {
                                  "Fn::GetAtt": [
                                      "MyLambdaFunction",
                                      "Arn"
                                  ]
                              }
                          }
                      ]
                  },
                  "RoleArn": {
                      "Fn::GetAtt": [
                          "StatesExecutionRole",
                          "Arn"
                      ]
                  }
              }
          }
```

------

## ステップ 2: CloudFormation テンプレートを使用して Lambda ステートマシンを作成する
<a name="lambda-state-machine-cfn-step-2"></a>

 CloudFormation テンプレートのコンポーネントを理解したら、それらをまとめてテンプレートを使用して CloudFormation スタックを作成できます。

### Lambda ステートマシンを作成するには
<a name="to-create-the-lam-state-machine"></a>

1. 以下のサンプルデータを YAML 例の `MyStateMachine.yaml`、あるいは JSON の `MyStateMachine.json` という名前のファイルにコピーします。

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

   ```
   AWSTemplateFormatVersion: "2010-09-09"
     Description: "An example template with an IAM role for a Lambda state machine."
     Resources:
       LambdaExecutionRole:
         Type: "AWS::IAM::Role"
         Properties:
           AssumeRolePolicyDocument:
             Version: "2012-10-17"		 	 	 
             Statement:
               - Effect: Allow
                 Principal:
                   Service: lambda.amazonaws.com
                 Action: "sts:AssumeRole"
     
       MyLambdaFunction:
         Type: "AWS::Lambda::Function"
         Properties:
           Handler: "index.handler"
           Role: !GetAtt [ LambdaExecutionRole, Arn ]
           Code:
             ZipFile: |
               exports.handler = (event, context, callback) => {
                   callback(null, "Hello World!");
               };
           Runtime: "nodejs12.x"
           Timeout: "25"
     
       StatesExecutionRole:
         Type: "AWS::IAM::Role"
         Properties:
           AssumeRolePolicyDocument:
             Version: "2012-10-17"		 	 	 
             Statement:
               - Effect: "Allow"
                 Principal:
                   Service:
                     - !Sub states.${AWS::Region}.amazonaws.com
                 Action: "sts:AssumeRole"
           Path: "/"
           Policies:
             - PolicyName: StatesExecutionPolicy
               PolicyDocument:
                 Version: "2012-10-17"		 	 	 
                 Statement:
                   - Effect: Allow
                     Action:
                       - "lambda:InvokeFunction"
                     Resource: "*"
     
       MyStateMachine:
         Type: "AWS::StepFunctions::StateMachine"
         Properties:
           DefinitionString:
             !Sub
               - |-
                 {
                   "Comment": "A Hello World example using an AWS Lambda function",
                   "StartAt": "HelloWorld",
                   "States": {
                     "HelloWorld": {
                       "Type": "Task",
                       "Resource": "${lambdaArn}",
                       "End": true
                     }
                   }
                 }
               - {lambdaArn: !GetAtt [ MyLambdaFunction, Arn ]}
           RoleArn: !GetAtt [ StatesExecutionRole, Arn ]
   ```

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

   ```
   {
         "AWSTemplateFormatVersion": "2010-09-09",
         "Description": "An example template with an IAM role for a Lambda state machine.",
         "Resources": {
             "LambdaExecutionRole": {
                 "Type": "AWS::IAM::Role",
                 "Properties": {
                     "AssumeRolePolicyDocument": {
                         "Version": "2012-10-17",		 	 	 
                         "Statement": [
                             {
                                 "Effect": "Allow",
                                 "Principal": {
                                     "Service": "lambda.amazonaws.com"
                                 },
                                 "Action": "sts:AssumeRole"
                             }
                         ]
                     }
                 }
             },
             "MyLambdaFunction": {
                 "Type": "AWS::Lambda::Function",
                 "Properties": {
                     "Handler": "index.handler",
                     "Role": {
                         "Fn::GetAtt": [
                             "LambdaExecutionRole",
                             "Arn"
                         ]
                     },
                     "Code": {
                         "ZipFile": "exports.handler = (event, context, callback) => {\n    callback(null, \"Hello World!\");\n};\n"
                     },
                     "Runtime": "nodejs12.x",
                     "Timeout": "25"
                 }
             },
             "StatesExecutionRole": {
                 "Type": "AWS::IAM::Role",
                 "Properties": {
                     "AssumeRolePolicyDocument": {
                         "Version": "2012-10-17",		 	 	 
                         "Statement": [
                             {
                                 "Effect": "Allow",
                                 "Principal": {
                                     "Service": [
                                         {
                                             "Fn::Sub": "states.${AWS::Region}.amazonaws.com"
                                         }
                                     ]
                                 },
                                 "Action": "sts:AssumeRole"
                             }
                         ]
                     },
                     "Path": "/",
                     "Policies": [
                         {
                             "PolicyName": "StatesExecutionPolicy",
                             "PolicyDocument": {
                                 "Version": "2012-10-17",		 	 	 
                                 "Statement": [
                                     {
                                         "Effect": "Allow",
                                         "Action": [
                                             "lambda:InvokeFunction"
                                         ],
                                         "Resource": "*"
                                     }
                                 ]
                             }
                         }
                     ]
                 }
             },
             "MyStateMachine": {
                 "Type": "AWS::StepFunctions::StateMachine",
                 "Properties": {
                     "DefinitionString": {
                         "Fn::Sub": [
                             "{\n  \"Comment\": \"A Hello World example using an AWS Lambda function\",\n  \"StartAt\": \"HelloWorld\",\n  \"States\": {\n    \"HelloWorld\": {\n      \"Type\": \"Task\",\n      \"Resource\": \"${lambdaArn}\",\n      \"End\": true\n    }\n  }\n}",
                             {
                                 "lambdaArn": {
                                     "Fn::GetAtt": [
                                         "MyLambdaFunction",
                                         "Arn"
                                     ]
                                 }
                             }
                         ]
                     },
                     "RoleArn": {
                         "Fn::GetAtt": [
                             "StatesExecutionRole",
                             "Arn"
                         ]
                     }
                 }
             }
         }
     }
   ```

------

1. [CloudFormation コンソール](https://console.aws.amazon.com/cloudformation/home)を開き、**[Create Stack]** (スタックの作成) を選択します。

1. **[Select Template]** (テンプレートを選択) ページで、**[Upload a template to Amazon S3]** (Amazon S3 にテンプレートをアップロード) を選択します。`MyStateMachine` ファイルを選択し、**[Next]** (次へ) を選択します。

1. **[Specify Details]** (詳細の指定) ページで、**[Stack name]** (スタック名) に `MyStateMachine` を入力してから、**[Next]** (次へ) を選択します。

1. **[Options]** (オプション) ページで、**[Next]** (次へ) を選択します。

1. **[Review]** (レビュー) ページで、**[I acknowledge that CloudFormation might create resources]** ( によるIAM リソース作成の可能性があることを認める) を選択し、**[Create]** (作成) を選択します。

   CloudFormation は`MyStateMachine`スタックの作成を開始し、**CREATE\$1IN\$1PROGRESS** ステータスを表示します。プロセスが完了すると、 CloudFormation に **CREATE\$1COMPLETE** ステータスが表示されます。

1. (省略可能) スタックのリソースを表示するには、スタックを選択して **[Resources]** (リソース) タブを選択します。

## ステップ 3: ステートマシンの実行をスタートする
<a name="lambda-state-machine-cfn-step-3"></a>

Lambda ステートマシンの作成後、実行を開始できます。

### ステートマシンの実行をスタートするには
<a name="to-start-the-state-machine-execution"></a>

1. [Step Functions コンソール](https://console.aws.amazon.com/states/home)を開き、 を使用して作成したステートマシンの名前を選択します CloudFormation。

1. ***MyStateMachine-ABCDEFGHIJ1K*** ページで、**[New execution]** (新しい実行) を選択します。

   **[New execution]** (新しい実行) ページが表示されます。

1. (オプション) 生成されたデフォルトを上書きするカスタム実行名を入力します。
**非 ASCII 名とログ記録**  
Step Functions では、ステートマシン、実行、アクティビティ、ラベルに、ASCII 以外の文字を含む名前を使用できます。このような文字を使用すると Amazon CloudWatch がデータを記録できなくなるため、Step Functions のメトリクスを追跡できるように ASCII 文字のみを使用することをお勧めします。

1. **[実行のスタート]** を選択します。

   ステートマシンの新しい実行がスタートされ、実行中の実行が表示されている新しいページが表示されます。

1. (オプション) **[実行の詳細]** で、**[実行ステータス]**、および **[開始]** と **[終了]** のタイムスタンプを確認します。

1. 実行結果を表示するには、**[Output]** (出力) タブを選択します。