使用 AWS CDK 在 Step Functions 中建立標準工作流程 - AWS Step Functions

本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。

使用 AWS CDK 在 Step Functions 中建立標準工作流程

您可以使用 AWS Cloud Development Kit (AWS CDK) 基礎設施即代碼(IAC)框架,以創建 AWS Step Functions 狀態機包含 AWS Lambda 功能。

您將定義 AWS 使用其中一個的基礎架構 CDK支援的語言。定義基礎結構之後,您將會將您的應用程式合成 AWS CloudFormation 模板並將其部署到您的 AWS 帳戶。

您將使用此方法來定義包含 Lambda 函數的 Step Functions 函數狀態機,然後從使用 Step Functions 數運行狀態機 AWS Management Console.

在開始本自學課程之前,您必須先設定 AWS CDK 開發環境,如入門使用中所述 AWS CDK - 中的先決條件 AWS Cloud Development Kit (AWS CDK) 開發人員指南。然後,安裝 AWS CDK 使用以下命令 AWS CLI:

npm install -g aws-cdk

本自學課程產生的結果與使用 AWS CloudFormation 在 Step Functions 中建立工作流程. 但是,在本自學課程中,AWS CDK 不需要你創建任何 IAM 角色;AWS CDK 為你做。所以此 AWS CDK 版本還包括一個成功工作流狀態步驟來說明如何向狀態機添加其他步驟。

提示

若要部署啟動 Step Functions 工作流程: AWS CDK 與 TypeScript 您的 AWS 帳戶,請參閱模組 10-部署 AWS CDK的 AWS Step Functions 工作坊

步驟 1:設定 AWS CDK project

  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 或更高版本。如需資訊,請參閱支援的版本

    mkdir step && cd step
  2. 使用 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 建立狀態機

首先,我們將介紹定義 Lambda 功能和 Step Functions 狀態機。然後,我們將解釋如何將它們放在您的 AWS CDK 應用程式。最後,您將看到如何合成和部署這些資源。

若要建立 Lambda 函數

如下所示 AWS CDK 程式碼定義 Lambda 函數,內嵌提供其原始程式碼。

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 應用程式。

  • 其他函數屬性,例如要使用的執行階段 (節點 18.x)、函數的進入點和逾時。

建立 狀態機器

我們的狀態機有兩種狀態:a Lambda 功能任務和狀成功工作流狀態態。該函數要求我們創建一個 Step Functions 工作流程狀態調用我們的函數。此任務狀態用作狀態的狀態機的第一個步驟。成功狀態會使用工作狀態的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 應用程式

在您新創建的 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"))) }); } } }
  2. 保存源文件,然後在應用程序的主目錄中運行cdk synth命令。

    AWS CDK 運行應用程序並合成 AWS 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();
  3. 若要將 Lambda 函數和 Step Functions 數狀態機器部署到您的 AWS 帳戶,問題cdk deploy。系統會要求您核准 IAM AWS CDK 已經生成。

步驟 3:啟動狀態機執行

建立狀態機之後,您就可以開始執行它。

開始狀態機器執行

  1. 開啟 Step Functions 主控台,然後選擇您使用建立的狀態機器名稱 AWS CDK.

  2. 在 [狀態機器] 頁面上,選擇 [開始執行]。

    此時會顯示「開始執行」對話方塊。

  3. (選擇性) 輸入自訂執行名稱,以覆寫產生的預設值。

    非ASCII名稱和記錄

    Step Functions 接受包含非ASCII字元的狀態機器、執行項目、活動和標籤的名稱。由於此類字元不適用於 Amazon CloudWatch,因此我們建議您僅使用ASCII字元,以便在中追蹤指標 CloudWatch。

  4. 選擇 Start Execution (開始執行)

    您的狀態機的執行開始,並顯示一個顯示正在運行執行的新頁面。

  5. Step Functions 主控台會將您導向至標題為執行 ID 的頁面。此頁面稱為「執行詳細資訊」頁面。在此頁面上,您可以在執行進行時或完成之後複查執行結果。

    若要複查執行結果,請在「圖形」檢視中選擇個別狀態,然後選擇步驟詳情窗格上的個別索引標籤,分別檢視每個狀態的詳細資訊,包括輸入、輸出和定義。如需有關可在「執行詳細資訊」頁面檢視之執行資訊的詳細資訊,請參閱執行細節概述

步驟 4:清除

測試完狀態機之後,我們建議您移除狀態機和相關 Lambda 函數,以釋放您中的資源 AWS 帳戶。 在應用程序的主目錄中運行該cdk destroy命令以刪除狀態機。

後續步驟

若要進一步了解開發 AWS 基礎架構: AWS CDK,請參閱 AWS CDK 開發人員指南

有關寫作的信息 AWS CDK 使用您所選語言的應用程式,請參閱:

TypeScript

使用 AWS CDK 在 TypeScript

JavaScript

使用 AWS CDK 在 JavaScript

Python

使用 AWS CDK 在 Python

Java

使用 AWS CDK 在爪哇

C#

使用 AWS CDK 在 C# 中

如需有關的更多資訊 AWS 構建本教程中使用的庫模塊,請參閱以下內容 AWS CDK API參考概述: