本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。
在 Step Functions 中使用 AWS CDK 创建快速工作流程
在本教程中,您将了解如何使用 AWS Cloud Development Kit (AWS CDK)基础设施即代码(IAC)框架创建一个 API Gateway REST API,来与同步快速状态机一起作为后端集成。
您将使用 StepFunctionsRestApi
构造来将状态机连接到 API Gateway。StepFunctionsRestApi
构造将设置默认的输入/输出映射和 API Gateway REST API,具有所需的权限和 HTTP “ANY” 方法。
通过 AWS CDK 这个基础设施即代码(IAC)框架,可以使用编程语言来定义 AWS 基础设施。您使用 CDK 的受支持语言之一定义应用程序,将代码合成到 AWS CloudFormation 模板中,然后将基础设施部署到您的 AWS 账户。
您将使用 AWS CloudFormation 来定义 API Gateway REST API,该 API 与同步快速状态机集成来作为后端,然后使用 AWS Management Console来启动执行。
在开始本教程之前,请按照 Getting Started With the AWS CDK - Prerequisites 中的说明设置 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 安装指定的程序包,可通过Tools > NuGet Package Manager > Manage NuGet Packages for Solution 实现。
安装模块后,您可以通过导入以下软件包在 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
状态的简单状态机。
创建快速状态机
下方是 AWS CDK 代码,它定义了一个具有带有Pass
状态的简单状态机。
- 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,
})
您可以在这个简短的片段中看到:
使用 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 Gateway
使用同步快速状态机创建 API Gateway REST API 作为后端集成后,您可以测试 API Gateway。
使用 API Gateway 控制台测试已部署的 API Gateway
-
打开 Amazon API Gateway 控制台并登录。
-
选择名为 StepFunctionsRestApi
的 REST API。
-
在资源窗格中,选择 ANY
方法。
-
选择测试选项卡。您可能需要选择右箭头按钮,以显示该选项卡。
-
对于方法,选择 POST。
-
在请求正文中,复制以下请求参数。
{
"key": "Hello"
}
-
选择测试。此时将显示以下信息:
响应正文输出应如下所示:
"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
。