翻訳は機械翻訳により提供されています。提供された翻訳内容と英語版の間で齟齬、不一致または矛盾がある場合、英語版が優先します。
AWS CDK を使用して Step Functions で Express ワークフローを作成する
このチュートリアルでは、AWS Cloud Development Kit (AWS CDK) Infrastructure as Code (IaC) フレームワークを使用して、バックエンドの統合として同期高速ステートマシンで API Gateway REST API を作成する方法について説明します。
このチュートリアルでは、StepFunctionsRestApi
コンストラクトを使用してステートマシンを API Gateway に接続します。StepFunctionsRestApi
コンストラクトは、必要なアクセス許可と HTTP「ANY」メソッドを使用して、デフォルトの入出力マッピングと API Gateway REST API を設定します。
AWS CDK は、プログラミング言語を使用して、AWS インフラストラクチャを定義する Infrastructure as Code (IAC) フレームワークです。CDK がサポートする言語の 1 つでアプリケーションを定義し、コードを AWS CloudFormation テンプレートに合成してから、AWS アカウントにインフラストラクチャをデプロイします。
AWS CloudFormation を使用して API Gateway REST API を定義して、それをバックエンドとして同期高速ステートマシンと統合し、AWS Management Console を使用して実行を開始します。
このチュートリアルをスタートする前に、「AWS CDK の開始方法 - 前提条件」の説明にあるように、AWS CDK 開発環境を設定し、それから以下を発行することにより AWS CDK をインストールします。
npm install -g aws-cdk
ステップ 1:AWS CDK プロジェクトを設定する
まず、新しい AWS CDK アプリケーションのディレクトリを作成し、プロジェクトを初期化します。
- TypeScript
-
mkdir stepfunctions-rest-api
cd stepfunctions-rest-api
cdk init --language typescript
- JavaScript
-
mkdir stepfunctions-rest-api
cd stepfunctions-rest-api
cdk init --language javascript
- Python
-
mkdir stepfunctions-rest-api
cd stepfunctions-rest-api
cdk init --language python
プロジェクトが初期化されたら、プロジェクトの仮想環境をアクティブにし、AWS CDK のベースラインの依存関係をインストールします。
source .venv/bin/activate
python -m pip install -r requirements.txt
- Java
-
mkdir stepfunctions-rest-api
cd stepfunctions-rest-api
cdk init --language java
- C#
-
mkdir stepfunctions-rest-api
cd stepfunctions-rest-api
cdk init --language csharp
- Go
-
mkdir stepfunctions-rest-api
cd stepfunctions-rest-api
cdk init --language go
必ずディレクトリの名前はディレクトリ stepfunctions-rest-api
としてください。AWS CDK アプリケーションテンプレートは、ディレクトリ名を使用し、ソースファイルとクラスの名前を生成します。別の名前を使用する場合は、アプリはこのチュートリアルと一致しません。
ここで、AWS Step Functions と Amazon API Gateway のコンストラクトライブラリモジュールをインストールします。
- TypeScript
-
npm install @aws-cdk/aws-stepfunctions @aws-cdk/aws-apigateway
- JavaScript
-
npm install @aws-cdk/aws-stepfunctions @aws-cdk/aws-apigateway
- Python
-
python -m pip install aws-cdk.aws-stepfunctions
python -m pip install aws-cdk.aws-apigateway
- Java
-
プロジェクトの pom.xml
を編集し、既存の <dependencies>
コンテナ 内に、以下の依存関係を追加します。
<dependency>
<groupId>software.amazon.awscdk</groupId>
<artifactId>stepfunctions</artifactId>
<version>${cdk.version}</version>
</dependency>
<dependency>
<groupId>software.amazon.awscdk</groupId>
<artifactId>apigateway</artifactId>
<version>${cdk.version}</version>
</dependency>
Mavenは、次回アプリケーションを構築するときに、これらの依存関係を自動的にインストールします。構築するには、mvn compile
を使用するか、Java IDEの構築するコマンドを使用します。
- C#
-
dotnet add src/StepfunctionsRestApi package Amazon.CDK.AWS.Stepfunctions
dotnet add src/StepfunctionsRestApi package Amazon.CDK.AWS.APIGateway
また、Visual Studio NuGet GUIを使用して、示されたパッケージをインストールすることもできます。ツール > NuGet パッケージマネージャー > ソリューションの NuGet パッケージの管理の手順で可能です。
モジュールをインストールすると、次のパッケージをインポートして、AWS CDK アプリケーションでモジュールを使用できます。
- TypeScript
-
@aws-cdk/aws-stepfunctions
@aws-cdk/aws-apigateway
- JavaScript
-
@aws-cdk/aws-stepfunctions
@aws-cdk/aws-apigateway
- Python
-
aws_cdk.aws_stepfunctions
aws_cdk.aws_apigateway
- Java
-
software.amazon.awscdk.services.apigateway.StepFunctionsRestApi
software.amazon.awscdk.services.stepfunctions.Pass
software.amazon.awscdk.services.stepfunctions.StateMachine
software.amazon.awscdk.services.stepfunctions.StateMachineType
- C#
-
Amazon.CDK.AWS.StepFunctions
Amazon.CDK.AWS.APIGateway
- Go
-
stepfunctions-rest-api.go
内の import
に次のものを追加します。
"github.com/aws/aws-cdk-go/awscdk/awsapigateway"
"github.com/aws/aws-cdk-go/awscdk/awsstepfunctions"
ステップ 2: AWS CDK を使用して同期高速ステートマシンのバンクエンドの統合で API Gateway REST API を作成する方法について説明します。
最初に、同期高速ステートマシンと API Gateway REST API を定義する個々のコードを紹介し、それらを AWS CDK アプリケーションにまとめる方法を説明します。次に、これらのリソースを合成してデプロイする方法を見ていきます。
ここで紹介するステートマシンは、Pass
ステートのシンプルなステートマシンです。
高速ステートマシンを作成するには
これは、Pass
ステートのシンプルなステートマシンを定義する AWS CDK コードです。
- TypeScript
-
const machineDefinition = new stepfunctions.Pass(this, 'PassState', {
result: {value:"Hello!"},
})
const stateMachine = new stepfunctions.StateMachine(this, 'MyStateMachine', {
definition: machineDefinition,
stateMachineType: stepfunctions.StateMachineType.EXPRESS,
});
- JavaScript
-
const machineDefinition = new sfn.Pass(this, 'PassState', {
result: {value:"Hello!"},
})
const stateMachine = new sfn.StateMachine(this, 'MyStateMachine', {
definition: machineDefinition,
stateMachineType: stepfunctions.StateMachineType.EXPRESS,
});
- Python
-
machine_definition = sfn.Pass(self,"PassState",
result = sfn.Result("Hello"))
state_machine = sfn.StateMachine(self, 'MyStateMachine',
definition = machine_definition,
state_machine_type = sfn.StateMachineType.EXPRESS)
- Java
-
Pass machineDefinition = Pass.Builder.create(this, "PassState")
.result(Result.fromString("Hello"))
.build();
StateMachine stateMachine = StateMachine.Builder.create(this, "MyStateMachine")
.definition(machineDefinition)
.stateMachineType(StateMachineType.EXPRESS)
.build();
- C#
-
var machineDefinition = new Pass(this, "PassState", new PassProps
{
Result = Result.FromString("Hello")
});
var stateMachine = new StateMachine(this, "MyStateMachine", new StateMachineProps
{
Definition = machineDefinition,
StateMachineType = StateMachineType.EXPRESS
});
- Go
-
var machineDefinition = awsstepfunctions.NewPass(stack, jsii.String("PassState"), &awsstepfunctions.PassProps
{
Result: awsstepfunctions.NewResult(jsii.String("Hello")),
})
var stateMachine = awsstepfunctions.NewStateMachine(stack, jsii.String("StateMachine"), &awsstepfunctions.StateMachineProps
{
Definition: machineDefinition,
StateMachineType: awsstepfunctions.StateMachineType_EXPRESS,
})
この短いスニペットで見ることができます:
-
PassState
という名前のマシン定義 (Pass
ステート)。
-
ステートマシンの論理名、MyStateMachine
。
-
マシンの定義がステートマシン定義として使用されます。
-
StepFunctionsRestApi
は同期高速ステートマシンのみを許可するため、ステートマシンタイプは EXPRESS
に設定されています。
StepFunctionsRestApi
コンストラクトを使用して API Gateway REST API を作成するには
StepFunctionsRestApi
コンストラクトを使用して、必要なアクセス許可とデフォルトの入力/出力マッピングを持つ API Gateway REST API を作成します。
- TypeScript
-
const api = new apigateway.StepFunctionsRestApi(this,
'StepFunctionsRestApi', { stateMachine: stateMachine });
- JavaScript
-
const api = new apigateway.StepFunctionsRestApi(this,
'StepFunctionsRestApi', { stateMachine: stateMachine });
- Python
-
api = apigw.StepFunctionsRestApi(self, "StepFunctionsRestApi",
state_machine = state_machine)
- Java
-
StepFunctionsRestApi api = StepFunctionsRestApi.Builder.create(this, "StepFunctionsRestApi")
.stateMachine(stateMachine)
.build();
- C#
-
var api = new StepFunctionsRestApi(this, "StepFunctionsRestApi", new StepFunctionsRestApiProps
{
StateMachine = stateMachine
});
- Go
-
awsapigateway.NewStepFunctionsRestApi(stack, jsii.String("StepFunctionsRestApi"), &awsapigateway.StepFunctionsRestApiProps
{
StateMachine = stateMachine,
})
AWS CDK アプリケーションを構築してデプロイするには
作成したAWS CDKプロジェクトで、スタックの定義を含むファイルを編集して、以下のコードのようにします。Step Functions ステートマシンと API Gateway については上述されています。
- TypeScript
-
以下のように lib/stepfunctions-rest-api-stack.ts
を更新します。
import * as cdk from 'aws-cdk-lib';
import * as stepfunctions from 'aws-cdk-lib/aws-stepfunctions'
import * as apigateway from 'aws-cdk-lib/aws-apigateway';
export class StepfunctionsRestApiStack extends cdk.Stack {
constructor(scope: cdk.App, id: string, props?: cdk.StackProps) {
super(scope, id, props);
const machineDefinition = new stepfunctions.Pass(this, 'PassState', {
result: {value:"Hello!"},
});
const stateMachine = new stepfunctions.StateMachine(this, 'MyStateMachine', {
definition: machineDefinition,
stateMachineType: stepfunctions.StateMachineType.EXPRESS,
});
const api = new apigateway.StepFunctionsRestApi(this,
'StepFunctionsRestApi', { stateMachine: stateMachine });
- JavaScript
-
以下のように lib/stepfunctions-rest-api-stack.js
を更新します。
const cdk = require('@aws-cdk/core');
const stepfunctions = require('@aws-cdk/aws-stepfunctions');
const apigateway = require('@aws-cdk/aws-apigateway');
class StepfunctionsRestApiStack extends cdk.Stack {
constructor(scope: cdk.Construct, id: string, props?: cdk.StackProps) {
super(scope, id, props);
const machineDefinition = new stepfunctions.Pass(this, "PassState", {
result: {value:"Hello!"},
})
const stateMachine = new sfn.StateMachine(this, 'MyStateMachine', {
definition: machineDefinition,
stateMachineType: stepfunctions.StateMachineType.EXPRESS,
});
const api = new apigateway.StepFunctionsRestApi(this,
'StepFunctionsRestApi', { stateMachine: stateMachine });
}
}
module.exports = { StepStack }
- Python
-
以下のように stepfunctions_rest_api/stepfunctions_rest_api_stack.py
を更新します。
from aws_cdk import App, Stack
from constructs import Construct
from aws_cdk import aws_stepfunctions as sfn
from aws_cdk import aws_apigateway as apigw
class StepfunctionsRestApiStack(Stack):
def __init__(self, scope: Construct, construct_id: str, **kwargs) -> None:
super().__init__(scope, construct_id, **kwargs)
machine_definition = sfn.Pass(self,"PassState",
result = sfn.Result("Hello"))
state_machine = sfn.StateMachine(self, 'MyStateMachine',
definition = machine_definition,
state_machine_type = sfn.StateMachineType.EXPRESS)
api = apigw.StepFunctionsRestApi(self,
"StepFunctionsRestApi",
state_machine = state_machine)
- Java
-
以下のように src/main/java/com.myorg/StepfunctionsRestApiStack.java
を更新します。
package com.myorg;
import software.amazon.awscdk.core.Construct;
import software.amazon.awscdk.core.Stack;
import software.amazon.awscdk.core.StackProps;
import software.amazon.awscdk.services.stepfunctions.Pass;
import software.amazon.awscdk.services.stepfunctions.StateMachine;
import software.amazon.awscdk.services.stepfunctions.StateMachineType;
import software.amazon.awscdk.services.apigateway.StepFunctionsRestApi;
public class StepfunctionsRestApiStack extends Stack {
public StepfunctionsRestApiStack(final Construct scope, final String id) {
this(scope, id, null);
}
public StepfunctionsRestApiStack(final Construct scope, final String id, final StackProps props) {
super(scope, id, props);
Pass machineDefinition = Pass.Builder.create(this, "PassState")
.result(Result.fromString("Hello"))
.build();
StateMachine stateMachine = StateMachine.Builder.create(this, "MyStateMachine")
.definition(machineDefinition)
.stateMachineType(StateMachineType.EXPRESS)
.build();
StepFunctionsRestApi api = StepFunctionsRestApi.Builder.create(this, "StepFunctionsRestApi")
.stateMachine(stateMachine)
.build();
}
}
- C#
-
以下のように src/StepfunctionsRestApi/StepfunctionsRestApiStack.cs
を更新します。
using Amazon.CDK;
using Amazon.CDK.AWS.StepFunctions;
using Amazon.CDK.AWS.APIGateway;
namespace StepfunctionsRestApi
{
public class StepfunctionsRestApiStack : Stack
{
internal StepfunctionsRestApi(Construct scope, string id, IStackProps props = null) : base(scope, id, props)
{
var machineDefinition = new Pass(this, "PassState", new PassProps
{
Result = Result.FromString("Hello")
});
var stateMachine = new StateMachine(this, "MyStateMachine", new StateMachineProps
{
Definition = machineDefinition,
StateMachineType = StateMachineType.EXPRESS
});
var api = new StepFunctionsRestApi(this, "StepFunctionsRestApi", new StepFunctionsRestApiProps
{
StateMachine = stateMachine
});
}
}
}
- Go
-
以下のように stepfunctions-rest-api.go
を更新します。
package main
import (
"github.com/aws/aws-cdk-go/awscdk"
"github.com/aws/aws-cdk-go/awscdk/awsapigateway"
"github.com/aws/aws-cdk-go/awscdk/awsstepfunctions"
"github.com/aws/constructs-go/constructs/v3"
"github.com/aws/jsii-runtime-go"
)
type StepfunctionsRestApiGoStackProps struct {
awscdk.StackProps
}
func NewStepfunctionsRestApiGoStack(scope constructs.Construct, id string, props *StepfunctionsRestApiGoStackProps) awscdk.Stack {
var sprops awscdk.StackProps
if props != nil {
sprops = props.StackProps
}
stack := awscdk.NewStack(scope, &id, &sprops)
// The code that defines your stack goes here
var machineDefinition = awsstepfunctions.NewPass(stack, jsii.String("PassState"), &awsstepfunctions.PassProps
{
Result: awsstepfunctions.NewResult(jsii.String("Hello")),
})
var stateMachine = awsstepfunctions.NewStateMachine(stack, jsii.String("StateMachine"), &awsstepfunctions.StateMachineProps{
Definition: machineDefinition,
StateMachineType: awsstepfunctions.StateMachineType_EXPRESS,
});
awsapigateway.NewStepFunctionsRestApi(stack, jsii.String("StepFunctionsRestApi"), &awsapigateway.StepFunctionsRestApiProps{
StateMachine = stateMachine,
})
return stack
}
func main() {
app := awscdk.NewApp(nil)
NewStepfunctionsRestApiGoStack(app, "StepfunctionsRestApiGoStack", &StepfunctionsRestApiGoStackProps{
awscdk.StackProps{
Env: env(),
},
})
app.Synth(nil)
}
// env determines the AWS environment (account+region) in which our stack is to
// be deployed. For more information see: https://docs.aws.amazon.com/cdk/latest/guide/environments.html
func env() *awscdk.Environment {
// If unspecified, this stack will be "environment-agnostic".
// Account/Region-dependent features and context lookups will not work, but a
// single synthesized template can be deployed anywhere.
//---------------------------------------------------------------------------
return nil
// Uncomment if you know exactly what account and region you want to deploy
// the stack to. This is the recommendation for production stacks.
//---------------------------------------------------------------------------
// return &awscdk.Environment{
// Account: jsii.String("123456789012"),
// Region: jsii.String("us-east-1"),
// }
// Uncomment to specialize this stack for the AWS Account and Region that are
// implied by the current CLI configuration. This is recommended for dev
// stacks.
//---------------------------------------------------------------------------
// return &awscdk.Environment{
// Account: jsii.String(os.Getenv("CDK_DEFAULT_ACCOUNT")),
// Region: jsii.String(os.Getenv("CDK_DEFAULT_REGION")),
// }
}
ソースファイルを保存し、cdk synth
アプリケーションのメインディレクトリで発行します。AWS CDK でアプリケーションを実行し、そのアプリケーションから AWS CloudFormation テンプレートを合成し、テンプレートを表示します。
Amazon API Gateway と AWS Step Functions ステートマシンを実際に AWS アカウントにデプロイするには、cdk deploy
を発行します。AWS CDK が生成されたIAM ポリシーを承認するよう求められます。
ステップ 3: API Gateway をテストする
同期高速ステートマシンをバックエンド統合として使用して API Gateway REST API を作成したら、API Gateway をテストできます。
API Gateway を使用してデプロイされた API Gateway をテストするには
-
Amazon API Gateway コンソールを開き、サインインします。
-
StepFunctionsRestApi
という名前の REST API を選択します。
-
[リソース] ペインで、ANY
メソッドを選択します。
-
[テスト] タブを選択します。タブを表示するには、右矢印ボタンを選択する必要がある場合があります。
-
[Method (メソッド)] で [POST] を選択します。
-
[リクエスト本文] には、以下のリクエストパラメータをコピーします。
{
"key": "Hello"
}
-
[テスト] を選択します。次の情報が表示されます。
-
[リクエスト]: メソッド用に呼び出されたリソースのパスです。
-
[ステータス]: 応答の HTTP ステータスコードです。
-
[レイテンシー]: 発信者からリクエストを受信してから応答を返すまでの時間です。
-
[レスポンス本文] は HTTP レスポンスの本文です。
-
[レスポンスヘッダー] は HTTP レスポンスのヘッダーです。
-
[ログ] にはシミュレートされた Amazon CloudWatch Logs エントリが表示され、このメソッドが API Gateway コンソール外で呼び出された場合は書き込まれています。
CloudWatch Logs エントリはシミュレートされていますが、メソッドの呼び出しの結果は現実のものです。
[レスポンス本文] の出力は、次のようになります。
"Hello"
さまざまなメソッドと無効な入力で API Gateway を試して、エラー出力を確認してください。特定のキーを検索するステートマシンを変更し、テスト中に間違ったキーを指定してステートマシンの実行を失敗させ、[レスポンス本文] の出力にエラーメッセージを生成させる場合があります。
cURL を使用して デプロイされた API をテストするには
-
ターミナルウィンドウを開きます。
-
次の cURL コマンドをコピーしてターミナルウィンドウに貼り付け、<api-id>
を API の API ID に、<region>
を API がデプロイされているリージョンに置き換えます。
curl -X POST\
'https://<api-id>
.execute-api.<region>
.amazonaws.com/prod' \
-d '{"key":"Hello"}' \
-H 'Content-Type: application/json'
[レスポンス本文] の出力は、次のようになります。
"Hello"
さまざまなメソッドと無効な入力で API Gateway を試して、エラー出力を確認してください。特定のキーを検索するステートマシンを変更し、テスト中に間違ったキーを指定してステートマシンの実行を失敗させ、[レスポンス本文] の出力にエラーメッセージを生成させる場合があります。
ステップ 4: クリーンアップする
API Gateway の試行が完了したら、AWS CDK を使用してステートマシンと API Gateway の両方をティアダウンできます。アプリケーションのメインディレクトリで cdk destroy
を発行します。