

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

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

AWS Cloud Development Kit (AWS CDK) Infrastructure as Code (IAC) フレームワークを使用して、AWS Lambda 関数を含む AWS Step Functions ステートマシンを作成できます。

CDKでサポートされている言語のいずれかを使用して AWS インフラストラクチャを定義します。インフラストラクチャを定義したら、アプリケーションをCloudFormationテンプレートに合成し、 AWS アカウントにデプロイします。

 この方法を使用して、Lambda 関数を含む Step Functions ステートマシンを定義し、Step Functions AWS マネジメントコンソールを使用してステートマシンを実行します。

このチュートリアルを開始する前に、「*AWS Cloud Development Kit (AWS CDK) デベロッパーガイド*」の「[AWS CDK の使用開始 - 前提条件](https://docs.aws.amazon.com/cdk/latest/guide/getting_started.html#getting_started_prerequisites)」の説明に従い、AWS CDK 開発環境をセットアップする必要があります。その後、AWS CLI で次のコマンドを使用して AWS CDK をインストールします。

```
npm install -g aws-cdk
```

このチュートリアルでは、[CloudFormation を使用して Step Functions でワークフローを作成する](tutorial-lambda-state-machine-cloudformation.md) と同じ結果になります。ただし、このチュートリアルでは、AWS CDK では IAM ロールの作成は必要なく、代わりに AWS CDK が作成します。AWS CDK バージョンには、ステートマシンにさらにステップを追加する方法を説明する [Succeed ワークフロー状態](state-succeed.md) ステップも含まれています。

**ヒント**  
TypeScript AWS CDKで を使用してStep Functionsワークフローを開始するサンプルサーバーレスアプリケーションをデプロイするには、*「 AWS Step Functions ワークショップ*」の[「 でデプロイするAWS CDK](https://catalog.workshops.aws/stepfunctions/iac/deploy-with-cdk)」を参照してください。

## ステップ 1:AWS CDK プロジェクトを設定する
<a name="lambda-state-machine-cdk-step-1"></a>

1. ホームディレクトリか、必要に応じて別のディレクトリで、次のコマンドを実行して、新しい AWS CDK アプリケーション用のディレクトリを作成します。
**重要**  
必ずディレクトリの名前はディレクトリ `step` としてください。AWS CDK アプリケーションテンプレートは、ディレクトリ名を使用し、ソースファイルとクラスの名前を生成します。別の名前を使用する場合は、アプリはこのチュートリアルと一致しません。

------
#### [ TypeScript ]

   ```
   mkdir step && cd step
   ```

------
#### [ JavaScript ]

   ```
   mkdir step && cd step
   ```

------
#### [ Python ]

   ```
   mkdir step && cd step
   ```

------
#### [ Java ]

   ```
   mkdir step && cd step
   ```

------
#### [ C\# ]

   .NET バージョン 6.0 以降がインストールされていることを確認してください。詳細については、「[ サポートされるバージョン](https://dotnet.microsoft.com/en-us/download/dotnet)」を参照してください。

   ```
   mkdir step && cd step
   ```

------

1. **cdk init** コマンドを使用してアプリケーションを初期化します。次の例に示すように、目的のテンプレート (「app」) とプログラミング言語を指定します。

------
#### [ TypeScript ]

   ```
   cdk init --language typescript
   ```

------
#### [ JavaScript ]

   ```
   cdk init --language javascript
   ```

------
#### [ Python ]

   ```
   cdk init --language python
   ```

   プロジェクトが初期化されたら、プロジェクトの仮想環境をアクティブにして、AWS CDK のベースラインの依存関係をインストールします。

   ```
   source .venv/bin/activate
   python -m pip install -r requirements.txt
   ```

------
#### [ Java ]

   ```
   cdk init --language java
   ```

------
#### [ C\# ]

   ```
   cdk init --language csharp
   ```

------

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

まず、Lambda 関数と Step Functions ステートマシンを定義する個々のコードを示します。次に、それらをまとめて AWS CDK アプリケーションに組み込む方法を説明します。最後に、これらのリソースを合成し、デプロイする方法を説明します。

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

次のものは、Lambda 関数を定義する AWS CDK コードで、ソースコードをインラインで提供します。

------
#### [ TypeScript ]

```
const helloFunction = new lambda.Function(this, 'MyLambdaFunction', {
    code: lambda.Code.fromInline(`
          exports.handler = (event, context, callback) => {
              callback(null, "Hello World!");
          };
      `),
    runtime: lambda.Runtime.NODEJS_18_X,
    handler: "index.handler",
    timeout: cdk.Duration.seconds(3)
});
```

------
#### [ JavaScript ]

```
const helloFunction = new lambda.Function(this, 'MyLambdaFunction', {
    code: lambda.Code.fromInline(`
          exports.handler = (event, context, callback) => {
              callback(null, "Hello World!");
          };
      `),
    runtime: lambda.Runtime.NODEJS_18_X,
    handler: "index.handler",
    timeout: cdk.Duration.seconds(3)
});
```

------
#### [ Python ]

```
hello_function = lambda_.Function(
            self, "MyLambdaFunction",
            code=lambda_.Code.from_inline("""
            exports.handler = (event, context, callback) => {
                callback(null, "Hello World!");
                }"""),
                runtime=lambda_.Runtime.NODEJS_18_X,
                handler="index.handler",
                timeout=Duration.seconds(25))
```

------
#### [ Java ]

```
final Function helloFunction = Function.Builder.create(this, "MyLambdaFunction")
        .code(Code.fromInline(
                "exports.handler = (event, context, callback) => { callback(null, 'Hello World!' );}"))
        .runtime(Runtime.NODEJS_18_X)
        .handler("index.handler")
        .timeout(Duration.seconds(25))
        .build();
```

------
#### [ C\# ]

```
var helloFunction = new Function(this, "MyLambdaFunction", new FunctionProps
{
    Code = Code.FromInline(@"`
      exports.handler = (event, context, callback) => {
        callback(null, 'Hello World!');
      }"),
    Runtime = Runtime.NODEJS_12_X,
    Handler = "index.handler",
    Timeout = Duration.Seconds(25)
});
```

------

以下に簡単なコード例を示します。
+ 関数の論理名 `MyLambdaFunction`。
+ AWS CDK アプリケーションのソースコードに文字列として埋め込まれている関数のソースコード。
+ 使用するランタイム (Node 18.x)、関数のエントリポイント、タイムアウトなど、その他の関数属性。

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

ステートマシンには、Lambda 関数タスクと [Succeed ワークフロー状態](state-succeed.md) 状態の 2 つの状態があります。この関数では、関数を呼び出す Step Functions [Task ワークフロー状態](state-task.md) を作成する必要があります。このタスク状態は、ステートマシンの最初のステップとして使用されます。成功状態は、そのタスク状態の `next()` メソッドを使用してステートマシンに追加されます。次のコードは、最初に `MyLambdaTask` という名前の関数を呼び出し、次に `next()` メソッドを使用して `GreetedWorld` という名前の成功状態を定義します。

------
#### [ TypeScript ]

```
const stateMachine = new sfn.StateMachine(this, 'MyStateMachine', {
  definition: new tasks.LambdaInvoke(this, "MyLambdaTask", {
    lambdaFunction: helloFunction
  }).next(new sfn.Succeed(this, "GreetedWorld"))
});
```

------
#### [ JavaScript ]

```
const stateMachine = new sfn.StateMachine(this, 'MyStateMachine', {
  definition: new tasks.LambdaInvoke(this, "MyLambdaTask", {
    lambdaFunction: helloFunction
  }).next(new sfn.Succeed(this, "GreetedWorld"))
});
```

------
#### [ Python ]

```
state_machine = sfn.StateMachine(
                                 self, "MyStateMachine",
                                 definition=tasks.LambdaInvoke(
                                 self, "MyLambdaTask",
                                 lambda_function=hello_function)
                                 .next(sfn.Succeed(self, "GreetedWorld")))
```

------
#### [ Java ]

```
final StateMachine stateMachine = StateMachine.Builder.create(this, "MyStateMachine")
        .definition(LambdaInvoke.Builder.create(this, "MyLambdaTask")
            .lambdaFunction(helloFunction)
            .build()
            .next(new Succeed(this, "GreetedWorld")))
        .build();
```

------
#### [ C\# ]

```
var stateMachine = new StateMachine(this, "MyStateMachine", new StateMachineProps {
    DefinitionBody = DefinitionBody.FromChainable(new LambdaInvoke(this, "MyLambdaTask", new LambdaInvokeProps
    {
        LambdaFunction = helloFunction
    })
    .Next(new Succeed(this, "GreetedWorld")))
});
```

------

### AWS CDK アプリケーションを構築してデプロイするには
<a name="lambda-state-machine-cdk-app"></a>

新規に作成した AWS CDK プロジェクトで、次のコード例のように、スタック定義を含むファイルを編集します。Lambda 関数と Step Functions ステートマシンの定義については、前のセクションで説明しています。

1. 次の例に示すように、スタックを更新します。

------
#### [ TypeScript ]

   次のコードを使用して、`lib/step-stack.ts` を更新します。

   ```
   import * as cdk from 'aws-cdk-lib';
   import * as lambda from 'aws-cdk-lib/aws-lambda';
   import * as sfn from 'aws-cdk-lib/aws-stepfunctions';
   import * as tasks from 'aws-cdk-lib/aws-stepfunctions-tasks';
   
   export class StepStack extends cdk.Stack {
     constructor(app: cdk.App, id: string) {
       super(app, id);
   
       const helloFunction = new lambda.Function(this, 'MyLambdaFunction', {
         code: lambda.Code.fromInline(`
             exports.handler = (event, context, callback) => {
                 callback(null, "Hello World!");
             };
         `),
         runtime: lambda.Runtime.NODEJS_18_X,
         handler: "index.handler",
         timeout: cdk.Duration.seconds(3)
       });
   
       const stateMachine = new sfn.StateMachine(this, 'MyStateMachine', {
         definition: new tasks.LambdaInvoke(this, "MyLambdaTask", {
           lambdaFunction: helloFunction
         }).next(new sfn.Succeed(this, "GreetedWorld"))
       });
     }
   }
   ```

------
#### [ JavaScript ]

   次のコードを使用して、`lib/step-stack.js` を更新します。

   ```
   import * as cdk from 'aws-cdk-lib';
   import * as lambda from 'aws-cdk-lib/aws-lambda';
   import * as sfn from 'aws-cdk-lib/aws-stepfunctions';
   import * as tasks from 'aws-cdk-lib/aws-stepfunctions-tasks';
   
   export class StepStack extends cdk.Stack {
     constructor(app, id) {
       super(app, id);
   
       const helloFunction = new lambda.Function(this, 'MyLambdaFunction', {
         code: lambda.Code.fromInline(`
             exports.handler = (event, context, callback) => {
                 callback(null, "Hello World!");
             };
         `),
         runtime: lambda.Runtime.NODEJS_18_X,
         handler: "index.handler",
         timeout: cdk.Duration.seconds(3)
       });
   
       const stateMachine = new sfn.StateMachine(this, 'MyStateMachine', {
         definition: new tasks.LambdaInvoke(this, "MyLambdaTask", {
           lambdaFunction: helloFunction
         }).next(new sfn.Succeed(this, "GreetedWorld"))
       });
     }
   }
   ```

------
#### [ Python ]

   次のコードを使用して、`step/step_stack.py` を更新します。

   ```
   from aws_cdk import (
       Duration,
       Stack,
       aws_stepfunctions as sfn,
       aws_stepfunctions_tasks as tasks,
       aws_lambda as lambda_
   )
   class StepStack(Stack):
   
       def __init__(self, scope: Construct, construct_id: str, **kwargs) -> None:
           super().__init__(scope, construct_id, **kwargs)
   
           hello_function = lambda_.Function(
               self, "MyLambdaFunction",
               code=lambda_.Code.from_inline("""
               exports.handler = (event, context, callback) => {
                   callback(null, "Hello World!");
                   }"""),
                   runtime=lambda_.Runtime.NODEJS_18_X,
                   handler="index.handler",
                   timeout=Duration.seconds(25))
   
           state_machine = sfn.StateMachine(
               self, "MyStateMachine",
               definition=tasks.LambdaInvoke(
               self, "MyLambdaTask",
               lambda_function=hello_function)
               .next(sfn.Succeed(self, "GreetedWorld")))
   ```

------
#### [ Java ]

   次のコードを使用して、`src/main/java/com.myorg/StepStack.java` を更新します。

   ```
   package com.myorg;
   
   import software.constructs.Construct;
   import software.amazon.awscdk.Stack;
   import software.amazon.awscdk.StackProps;
   import software.amazon.awscdk.Duration;
   import software.amazon.awscdk.services.lambda.Code;
   import software.amazon.awscdk.services.lambda.Function;
   import software.amazon.awscdk.services.lambda.Runtime;
   import software.amazon.awscdk.services.stepfunctions.StateMachine;
   import software.amazon.awscdk.services.stepfunctions.Succeed;
   import software.amazon.awscdk.services.stepfunctions.tasks.LambdaInvoke;
   
   public class StepStack extends Stack {
       public StepStack(final Construct scope, final String id) {
           this(scope, id, null);
       }
   
       public StepStack(final Construct scope, final String id, final StackProps props) {
           super(scope, id, props);
   
           final Function helloFunction = Function.Builder.create(this, "MyLambdaFunction")
                   .code(Code.fromInline(
                           "exports.handler = (event, context, callback) => { callback(null, 'Hello World!' );}"))
                   .runtime(Runtime.NODEJS_18_X)
                   .handler("index.handler")
                   .timeout(Duration.seconds(25))
                   .build();
   
           final StateMachine stateMachine = StateMachine.Builder.create(this, "MyStateMachine")
                   .definition(LambdaInvoke.Builder.create(this, "MyLambdaTask")
                           .lambdaFunction(helloFunction)
                           .build()
                           .next(new Succeed(this, "GreetedWorld")))
                   .build();
       }
   }
   ```

------
#### [ C\# ]

   次のコードを使用して、`src/Step/StepStack.cs` を更新します。

   ```
   using Amazon.CDK;
   using Constructs;
   using Amazon.CDK.AWS.Lambda;
   using Amazon.CDK.AWS.StepFunctions;
   using Amazon.CDK.AWS.StepFunctions.Tasks;
   
   namespace Step
   {
       public class StepStack : Stack
       {
           internal StepStack(Construct scope, string id, IStackProps props = null) : base(scope, id, props)
           {
               var helloFunction = new Function(this, "MyLambdaFunction", new FunctionProps
               {
                   Code = Code.FromInline(@"exports.handler = (event, context, callback) => {
                       callback(null, 'Hello World!');
                   }"),
                   Runtime = Runtime.NODEJS_18_X,
                   Handler = "index.handler",
                   Timeout = Duration.Seconds(25)
               });
   
               var stateMachine = new StateMachine(this, "MyStateMachine", new StateMachineProps
               {
                   DefinitionBody = DefinitionBody.FromChainable(new LambdaInvoke(this, "MyLambdaTask", new LambdaInvokeProps
                   {
                       LambdaFunction = helloFunction
                   })
                   .Next(new Succeed(this, "GreetedWorld")))
               });
           }
       }
   }
   ```

------

1. ソースファイルを保存し、アプリケーションのメインディレクトリで `cdk synth` コマンドを実行します。

   AWS CDK でアプリケーションを実行し、そのアプリケーションから CloudFormation テンプレートを合成し、AWS CDK によってテンプレートを表示します。
**注記**  
TypeScript を使用して AWS CDK プロジェクトを作成した場合、`cdk synth` コマンドを実行すると次のエラーが返されることがあります。  

   ```
   TSError: ⨯ Unable to compile TypeScript:
   bin/step.ts:7:33 - error TS2554: Expected 2 arguments, but got 3.
   ```
このエラーを解決するには、次の例に示すように `bin/step.ts` ファイルを変更します。  

   ```
   #!/usr/bin/env node
   import 'source-map-support/register';
   import * as cdk from 'aws-cdk-lib';
   import { StepStack } from '../lib/step-stack';
   
   const app = new cdk.App();
   new StepStack(app, 'StepStack');
   app.synth();
   ```

1. Lambda 関数と Step Functions ステートマシンを AWS アカウントにデプロイするには、`cdk deploy` を発行します。 AWS CDK が生成した IAM ポリシーを承認するように求められます。

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

ステートマシンを作成したら、実行を開始できます。

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

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

1. [ステートマシン] ページで、**[実行を開始]** を選択します。

   **[実行を開始]** ダイアログが表示されます。

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

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

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

1. Step Functions コンソールから実行 ID のタイトルが付いたページが表示されます。このページは、*[実行の詳細]* ページと呼ばれます。このページでは、実行の進行中または完了後に実行結果を確認できます。

   実行結果を確認するには、**[グラフビュー]** で個々の状態を選択し、[ステップの詳細](concepts-view-execution-details.md#exec-details-intf-step-details) ペインの個々のタブを選択すると、入力、出力、定義などの各状態の詳細がそれぞれ表示されます。*[実行の詳細]* ページに表示できる実行情報の詳細については、「[実行の詳細の概要](concepts-view-execution-details.md#exec-details-interface-overview)」を参照してください。

## ステップ 4: クリーンアップする
<a name="lambda-state-machine-cdk-step-4"></a>

ステートマシンをテストが完了したら、ステートマシンと関連する Lambda 関数の両方を削除して、 AWS アカウント内のリソースを解放することを推奨します。ステートマシンを削除するには、アプリケーションのメインディレクトリで `cdk destroy` コマンドを実行します。

## 次の手順
<a name="lambda-state-machine-cdk-next-steps"></a>

を使用した AWS インフラストラクチャの開発の詳細についてはAWS CDK、 [AWS CDKデベロッパーガイド](https://docs.aws.amazon.com/cdk/v2/guide/home.html)を参照してください。

お好みの言語で AWS CDK アプリケーションを書く方法についての情報は、以下を参照してください:

------
#### [ TypeScript ]

 [TypeScript で AWS CDK を使用する](https://docs.aws.amazon.com/cdk/v2/guide/work-with-cdk-typescript.html) 

------
#### [ JavaScript ]

 [JavaScript で AWS CDK を使用する](https://docs.aws.amazon.com/cdk/v2/guide/work-with-cdk-javascript.html) 

------
#### [ Python ]

 [Python で AWS CDK を使用する](https://docs.aws.amazon.com/cdk/v2/guide/work-with-cdk-python.html) 

------
#### [ Java ]

 [Java で AWS CDK を使用する](https://docs.aws.amazon.com/cdk/v2/guide/work-with-cdk-java.html) 

------
#### [ C\# ]

 [C\# で AWS CDK を使用する](https://docs.aws.amazon.com/cdk/v2/guide/work-with-cdk-csharp.html) 

------

このチュートリアルで使用される AWS コンストラクトライブラリモジュールの詳細については、次の AWS CDK API リファレンスの概要を参照してください。
+  [aws-lambda](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_lambda-readme.html) 
+  [aws-stepfunctions](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_stepfunctions-readme.html) 
+  [aws-stepfunctions-tasks](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_stepfunctions_tasks-readme.html) 