@aws-cdk/aws-stepfunctions

中文文档
1.204.0发布于 2023/06/20Apache-2.0TypeScriptCommonJS近 30 天下载 14.9万

AWS: StepFuns 的 CDK 构建库

此软件包已被标记为弃用

AWS CDK v1 has reached End-of-Support on 2023-06-01. This package is no longer being updated, and users should migrate to AWS CDK v2. For more information on how to migrate, see https://docs.aws.amazon.com/cdk/v2/guide/migrating-v2.html

中文使用文档
文档目录28 节
  1. 示例
  2. 国家机器
  3. 接入状态(JsonPath类)
  4. 亚马逊州语言
  5. 任务
  6. 过
  7. 单单
  8. 选择
  9. 平行
  10. 已经成功
  11. 失败
  12. 地图
  13. 自定义国
  14. 任务链
  15. 国家机器碎片
  16. 活动
  17. 活动级别权限
  18. 计量
  19. 错误名称
  20. 日志
  21. X-Ray 追踪
  22. 国家机器许可赠款
  23. 开始执行权限
  24. 读取权限
  25. 任务响应权限
  26. 执行级别权限
  27. 自定义权限
  28. 导入

AWS 步函数构造库


End-of-Support

AWS CDK v1在2023-06-01上达到了支持结束. 此软件包不再更新,用户应该迁移到 AWS CDK v2.

关于如何移徙的更多信息,请参见: 移动到 AWS CDK v2 指南。 。 。 .


这个 @aws-cdk/aws-stepfunctions 软件包中包含建筑构件 使用对象的无服务器工作流程。 结合 @aws-cdk/aws-stepfunctions-tasks 软件包,包含所用的类 以呼叫其他 AWS 服务.

定义工作流程看起来是这样(对于 步骤函数 Poller 实例:

示例

import * as lambda from '@aws-cdk/aws-lambda';

declare const submitLambda: lambda.Function;
declare const getStatusLambda: lambda.Function;

const submitJob = new tasks.LambdaInvoke(this, 'Submit Job', {
  lambdaFunction: submitLambda,
  // Lambda's result is in the attribute `Payload`
  outputPath: '$.Payload',
});

const waitX = new sfn.Wait(this, 'Wait X Seconds', {
  time: sfn.WaitTime.secondsPath('$.waitSeconds'),
});

const getStatus = new tasks.LambdaInvoke(this, 'Get Job Status', {
  lambdaFunction: getStatusLambda,
  // Pass just the field named "guid" into the Lambda, put the
  // Lambda's result in a field called "status" in the response
  inputPath: '$.guid',
  outputPath: '$.Payload',
});

const jobFailed = new sfn.Fail(this, 'Job Failed', {
  cause: 'AWS Batch Job Failed',
  error: 'DescribeJob returned FAILED',
});

const finalStatus = new tasks.LambdaInvoke(this, 'Get Final Job Status', {
  lambdaFunction: getStatusLambda,
  // Use "guid" field as input
  inputPath: '$.guid',
  outputPath: '$.Payload',
});

const definition = submitJob
  .next(waitX)
  .next(getStatus)
  .next(new sfn.Choice(this, 'Job Complete?')
    // Look at the "status" field
    .when(sfn.Condition.stringEquals('$.status', 'FAILED'), jobFailed)
    .when(sfn.Condition.stringEquals('$.status', 'SUCCEEDED'), finalStatus)
    .otherwise(waitX));

new sfn.StateMachine(this, 'StateMachine', {
  definition,
  timeout: Duration.minutes(5),
});

您可以找到更多的样本片段, 并更多地了解服务集成 输入 @aws-cdk/aws-stepfunctions-tasks 软件包.

国家机器

A 类 stepfunctions.StateMachine 是使用状态机器的资源 定义。 定义由其起始状态指定,包括: 从起始状态可以到达的所有状态 :

const startState = new sfn.Pass(this, 'StartState');

new sfn.StateMachine(this, 'StateMachine', {
  definition: startState,
});

国家机器使用 IAM 角色执行,该角色将自动拥有全部 添加执行所有状态机器任务所需的权限 适当的(例如,可以引用您添加到 你的工作流程。 默认将创建一个角色, 但您可以提供 还有一个.

接入状态(JsonPath类)

每个州立机器的行刑 国家机器 数据数字 : 包含输入状态机器的密钥和值的 JSON 文件, 随着状态机器的推进而得到修改,最后作为输出而出.

您可以将国家机器数据的碎片传送到国家机器的任务中. 为此,使用静态方法 JsonPath 课。 例如,通过 数据密钥中的值 OrderId 用于您引用的 Lambda 函数 用这个 JsonPath.stringAt('$.OrderId'),像这样:

import * as lambda from '@aws-cdk/aws-lambda';

declare const orderFn: lambda.Function;

const submitJob = new tasks.LambdaInvoke(this, 'InvokeOrderProcessor', {
  lambdaFunction: orderFn,
  payload: sfn.TaskInput.fromObject({
    OrderId: sfn.JsonPath.stringAt('$.OrderId'),
  }),
});

现有方法如下:

方法目的
JsonPath.stringAt('$.Field')字段,返回类型为 string。 。 。 .
JsonPath.listAt('$.Field')引用字段,返回类型为字符串列表.
JsonPath.numberAt('$.Field')引用字段,返回类型为数字。 用于需要数字参数的函数 .
JsonPath.objectAt('$.Field')字段,返回类型为 IResolvable。用于需要对象参数的函数.
JsonPath.entirePayload引用整个数据对象(相当于 $) (中文(简体) ).
JsonPath.taskToken参考 任务托肯,用于需要长期运行的集成模式.

您也可以打电话 内在函数 使用方法 JsonPath数字 :

方法目的
JsonPath.array(JsonPath.stringAt('$.Field'), ...)从其他元素中创建数组.
JsonPath.format('The value is {}.', JsonPath.stringAt('$.Value'))在格式字符串中插入元素.
JsonPath.stringToJson(JsonPath.stringAt('$.ObjStr'))将 JSON 字符串分析到对象
JsonPath.jsonToString(JsonPath.objectAt('$.Obj'))将对象串入 JSON 字符串

亚马逊州语言

这个图书馆有一套课程 模拟 亚马逊州 语言. 下列国家班级 已支持:

任意的 JSON 对象( 执行时指定) 从状态传递到 状态和在工作流程执行过程中的转换。 为了更多 信息,见各州语言分类.

任务

A 类 Task 代表着一些需要完成的工作。 确切的工作是: 完成由执行的类决定 IStepFunctionsTask,一个收藏 其中,可在 @aws-cdk/aws-stepfunctions-tasks 模块.

任务 @aws-cdk/aws-stepfunctions-tasks 模块支持 服务整合模式 整合 Step 函数与服务 直接使用亚马逊州语言.

过

A 类 Pass 状态将输入传递到其输出,而不进行工作. 通过状态在构建和调试状态机器时有用.

以下示例通过 页:1 result 字段。 这个 result 字段将添加到输入和结果中 将作为州产出通过.

// Makes the current JSON state { ..., "subObject": { "hello": "world" } }
const pass = new sfn.Pass(this, 'Add Hello World', {
  result: sfn.Result.fromObject({ hello: 'world' }),
  resultPath: '$.subObject',
});

// Set the next state
const nextState = new sfn.Pass(this, 'NextState');
pass.next(nextState);

这个 Pass 状态还支持通过键值对作为输入。 值可以 静态,或从带有路径的输入中选择.

以下示例过滤 greeting 从状态输入字段 并同时插入一个名为 otherData。 。 。 .

const pass = new sfn.Pass(this, 'Filter input and inject data', {
  parameters: { // input to the pass state
    input: sfn.JsonPath.stringAt('$.input.greeting'),
    otherData: 'some-extra-stuff',
  },
});

指定对象 parameters 将输入 Pass 状态. 由于两个 Result 也没有 ResultPath 提供 Pass 状态副本 它的投入贯穿其产出.

学习更多关于 通行状态

单单

A 类 Wait 状态等待给定的秒数, 或直到当前时间 击中一个特定的时间。 等待的时间可能取自处决的JSON 状态.

// Wait until it's the time mentioned in the the state object's "triggerTime"
// field.
const wait = new sfn.Wait(this, 'Wait For Trigger Time', {
  time: sfn.WaitTime.timestampPath('$.triggerTime'),
});

// Set the next state
const startTheWork = new sfn.Pass(this, 'StartTheWork');
wait.next(startTheWork);

选择

A 类 Choice 状态可以在基于 执行状态中的值 :

const choice = new sfn.Choice(this, 'Did it work?');

// Add conditions with .when()
const successState = new sfn.Pass(this, 'SuccessState');
const failureState = new sfn.Pass(this, 'FailureState');
choice.when(sfn.Condition.stringEquals('$.status', 'SUCCESS'), successState);
choice.when(sfn.Condition.numberGreaterThan('$.attempts', 5), failureState);

// Use .otherwise() to indicate what should be done if none of the conditions match
const tryAgainState = new sfn.Pass(this, 'TryAgainState');
choice.otherwise(tryAgainState);

如果你想根据条件暂时分割工作流程,但有 所有分支合而为一并持续(类似于 if ... then ... else 使用 .afterwards() 方法 :

const choice = new sfn.Choice(this, 'What color is it?');
const handleBlueItem = new sfn.Pass(this, 'HandleBlueItem');
const handleRedItem = new sfn.Pass(this, 'HandleRedItem');
const handleOtherItemColor = new sfn.Pass(this, 'HanldeOtherItemColor');
choice.when(sfn.Condition.stringEquals('$.color', 'BLUE'), handleBlueItem);
choice.when(sfn.Condition.stringEquals('$.color', 'RED'), handleRedItem);
choice.otherwise(handleOtherItemColor);

// Use .afterwards() to join all possible paths back together and continue
const shipTheItem = new sfn.Pass(this, 'ShipTheItem');
choice.afterwards().next(shipTheItem);

狦 Choice 没有 otherwise() 条件都不符 jSON州,a NoChoiceMatched 错误将被丢弃 。 包装状态机器 在一个 Parallel 状态,如果你想抓住和从中恢复.

可用条件

见 步骤函数比较运算符

  • Condition.isPresent - 如果存在json路径, 匹配
  • Condition.isNotPresent - 匹配没有 json 路径
  • Condition.isString - 如果 json 路径包含字符串则匹配
  • Condition.isNotString - 如果 json 路径不是字符串, 匹配
  • Condition.isNumeric - 如果一个json路径是数字,则匹配
  • Condition.isNotNumeric - 如果一个json路径不是数字匹配
  • Condition.isBoolean - 匹配如果 json 路径布尔
  • Condition.isNotBoolean - 如果 json 路径不是布尔, 匹配
  • Condition.isTimestamp - 如果json路径是时间戳,则匹配
  • Condition.isNotTimestamp - 如果json路径不是时间戳,则匹配
  • Condition.isNotNull - 如果一个json路径不是无效,则匹配
  • Condition.isNull - 如果 json 路径无效, 匹配
  • Condition.booleanEquals - 如果布尔字段有给定值,则匹配
  • Condition.booleanEqualsJsonPath - 如果布尔字段等于给定映射路径中的值,则匹配
  • Condition.stringEqualsJsonPath - 如果字符串字段等于给定的映射路径,则匹配
  • Condition.stringEquals - 如果字段等于字符串值,则匹配
  • Condition.stringLessThan - 在给定值之前匹配字符串字段排序
  • Condition.stringLessThanJsonPath - 如果在给定映射路径的数值之前有字符串字段排序,则匹配
  • Condition.stringLessThanEquals - 如果字符串字段类型等于或超过给定值,则匹配
  • Condition.stringLessThanEqualsJsonPath - 如果字符串字段类型等于或超过给定映射,则匹配
  • Condition.stringGreaterThan - 如果在给定值后有字符串字段排序匹配
  • Condition.stringGreaterThanJsonPath - 如果在给定映射路径的值之后有字符串字段排序匹配
  • Condition.stringGreaterThanEqualsJsonPath - 如果一个字符串字段在给定映射路径后排序或等值,则匹配
  • Condition.stringGreaterThanEquals - 如果字符串字段排序在给定值之后或等于该值,则匹配
  • Condition.numberEquals - 如果数字字段有给定值,则匹配
  • Condition.numberEqualsJsonPath - 如果数字字段在给定映射路径中有值,则匹配
  • Condition.numberLessThan - 如果数字字段小于给定值,则匹配
  • Condition.numberLessThanJsonPath - 如果数值字段小于给定映射路径的值,则匹配
  • Condition.numberLessThanEquals - 如果数字字段小于或等于给定值,则匹配
  • Condition.numberLessThanEqualsJsonPath - 如果数字字段小于或等于给定映射路径上的数值,则匹配
  • Condition.numberGreaterThan - 如果数字字段大于给定值,则匹配
  • Condition.numberGreaterThanJsonPath - 如果数字字段大于给定映射路径的值,则匹配
  • Condition.numberGreaterThanEquals - 如果数字字段大于或等于给定值,则匹配
  • Condition.numberGreaterThanEqualsJsonPath - 如果数字字段大于或等于指定映射路径的值,则匹配
  • Condition.timestampEquals - 如果时间戳字段与给定的时间戳相同,则匹配
  • Condition.timestampEqualsJsonPath - 如果时间戳字段与特定绘图路径的时间戳相同,则匹配
  • Condition.timestampLessThan - 如果在给定的时间戳之前有一个时间戳字段匹配
  • Condition.timestampLessThanJsonPath - 如果一个时间戳字段在给定的映射路径的时间戳之前就匹配
  • Condition.timestampLessThanEquals - 如果时间戳字段在给定的时间戳之前或等于该时间戳,则匹配
  • Condition.timestampLessThanEqualsJsonPath - 如果时间戳字段在指定绘图路径之前或等于时间戳,则匹配
  • Condition.timestampGreaterThan - 如果时间戳字段是在给定的映射路径的时间戳之后,则匹配
  • Condition.timestampGreaterThanJsonPath - 如果时间戳字段是在给定的映射路径的时间戳之后,则匹配
  • Condition.timestampGreaterThanEquals - 如果时间戳字段在给定的时间戳之后或等于该时间戳,则匹配
  • Condition.timestampGreaterThanEqualsJsonPath - 如果时间戳字段在某个绘图路径之后或等于时间戳,则匹配
  • Condition.stringMatches - 如果字段匹配可以包含野牌(*)的字符串模式,例如:log- *.txt或 *LATEST*。 除了"*"之外,没有其他角色有特殊的含义 - *可以被逃脱: QQ

平行

A 类 Parallel 状态并行执行一个或多个子工作流程。 也可以这样 用于捕捉和从子工作流程中的错误中恢复.

const parallel = new sfn.Parallel(this, 'Do the work in parallel');

// Add branches to be executed in parallel
const shipItem = new sfn.Pass(this, 'ShipItem');
const sendInvoice = new sfn.Pass(this, 'SendInvoice');
const restock = new sfn.Pass(this, 'Restock');
parallel.branch(shipItem);
parallel.branch(sendInvoice);
parallel.branch(restock);

// Retry the whole workflow if something goes wrong
parallel.addRetry({ maxAttempts: 1 });

// How to recover from errors
const sendFailureNotification = new sfn.Pass(this, 'SendFailureNotification');
parallel.addCatch(sendFailureNotification);

// What to do in case everything succeeded
const closeOrder = new sfn.Pass(this, 'CloseOrder');
parallel.next(closeOrder);

已经成功

达到a Succeed 状态终止状态机器执行 成功状态.

const success = new sfn.Succeed(this, 'We did it!');

失败

达到a Fail 状态终止状态机器执行 失败状态 。 失职状态应当报告失职原因. 失败可以通过包括 Parallel 各州.

const success = new sfn.Fail(this, 'Fail', {
  error: 'WorkflowFailure',
  cause: "Something went wrong",
});

地图

A 类 Map 状态可用于为输入数组的每个元素运行一组步骤. A 类 Map 状态将在状态输入中执行数组多个条目的相同步骤.

虽然 Parallel 状态使用相同的输入执行多个步骤分支, a Map 状态 对状态输入中的数组多个条目执行相同的步骤.

const map = new sfn.Map(this, 'Map State', {
  maxConcurrency: 1,
  itemsPath: sfn.JsonPath.stringAt('$.inputForMap'),
});
map.iterator(new sfn.Pass(this, 'Pass State'));

自定义国

州高级建筑或 stepfunctions-tasks 没有 您所寻找的州或服务整合。 缺乏这种能力的主要原因 函数为:

  • A 类 服务整合 可通过亚马逊州提供 Langauge,但无法作为构件提供 课程.
  • 状态或状态属性通过 Step 函数可用, 但无法配置 通过构造

如果无法提供特性,则 a CustomState 可用于提供任何亚马逊州语言 基于JSON的对象作为状态定义.

代码片断 并可作为状态定义插入.

自定义状态可以与其他任何状态连在一起创建您的状态机器 定义。 您还需要为您提供您所需的权限 role 那个 国家机器使用.

以下示例使用了 DynamoDB 服务集成,将数据插入到DynamoDB表格.

import * as dynamodb from '@aws-cdk/aws-dynamodb';

// create a table
const table = new dynamodb.Table(this, 'montable', {
  partitionKey: {
    name: 'id',
    type: dynamodb.AttributeType.STRING,
  },
});

const finalStatus = new sfn.Pass(this, 'final step');

// States language JSON to put an item into DynamoDB
// snippet generated from https://docs.aws.amazon.com/step-functions/latest/dg/tutorial-code-snippet.html#tutorial-code-snippet-1
const stateJson = {
  Type: 'Task',
  Resource: 'arn:aws:states:::dynamodb:putItem',
  Parameters: {
    TableName: table.tableName,
    Item: {
      id: {
        S: 'MyEntry',
      },
    },
  },
  ResultPath: null,
};

// custom state which represents a task to insert data into DynamoDB
const custom = new sfn.CustomState(this, 'my custom task', {
  stateJson,
});

const chain = sfn.Chain.start(custom)
  .next(finalStatus);

const sm = new sfn.StateMachine(this, 'StateMachine', {
  definition: chain,
  timeout: Duration.seconds(30),
});

// don't forget permissions. You need to assign them
table.grantWriteData(sm);

任务链

将工作流程定义为方便(可自上而下地读取) 作为写正则程序,可以连载大多数方法引用. 特别是 .next() 方法可以重复。 一系列研究的结果 .next() 电话叫做 链条,用于定义跳跃 目标 Choice.on 或者说 Parallel.branch数字 :

const step1 = new sfn.Pass(this, 'Step1');
const step2 = new sfn.Pass(this, 'Step2');
const step3 = new sfn.Pass(this, 'Step3');
const step4 = new sfn.Pass(this, 'Step4');
const step5 = new sfn.Pass(this, 'Step5');
const step6 = new sfn.Pass(this, 'Step6');
const step7 = new sfn.Pass(this, 'Step7');
const step8 = new sfn.Pass(this, 'Step8');
const step9 = new sfn.Pass(this, 'Step9');
const step10 = new sfn.Pass(this, 'Step10');
const choice = new sfn.Choice(this, 'Choice');
const condition1 = sfn.Condition.stringEquals('$.status', 'SUCCESS');
const parallel = new sfn.Parallel(this, 'Parallel');
const finish = new sfn.Pass(this, 'Finish');

const definition = step1
  .next(step2)
  .next(choice
    .when(condition1, step3.next(step4).next(step5))
    .otherwise(step6)
    .afterwards())
  .next(parallel
    .branch(step7.next(step8))
    .branch(step9.next(step10)))
  .next(finish);

new sfn.StateMachine(this, 'StateMachine', {
  definition,
});

如果你不喜欢直接从第一根链子开始的视觉 步骤,可以使用 Chain.start数字 :

const step1 = new sfn.Pass(this, 'Step1');
const step2 = new sfn.Pass(this, 'Step2');
const step3 = new sfn.Pass(this, 'Step3');

const definition = sfn.Chain
  .start(step1)
  .next(step2)
  .next(step3)
  // ...

国家机器碎片

可以通过 定义执行的构造 IChainable,需要您定义 两个字段:

  • startState: State,代表此状态机器的切入点.
  • endStates: INextable[],代表(一个或多个)表示退出 如果链到碎片上,则会添加过渡.

由于状态会以其构造的ID命名,所以您可能需要前缀 如果计划用同一种状态机器碎片进行即时处理,则需要各州的身份证 倍数倍数(否则每一次即时反应中的所有状态都会有相同的 名称).

班级 StateMachineFragment 包含一些辅助函数( 如 prefixStates())以相取为方便. 如果您定义了状态 机器作为这个的子类,将方便使用:

import { Stack } from '@aws-cdk/core';
import { Construct } from 'constructs';
import * as sfn from '@aws-cdk/aws-stepfunctions';

interface MyJobProps {
  jobFlavor: string;
}

class MyJob extends sfn.StateMachineFragment {
  public readonly startState: sfn.State;
  public readonly endStates: sfn.INextable[];

  constructor(parent: Construct, id: string, props: MyJobProps) {
    super(parent, id);

    const choice = new sfn.Choice(this, 'Choice')
      .when(sfn.Condition.stringEquals('$.branch', 'left'), new sfn.Pass(this, 'Left Branch'))
      .when(sfn.Condition.stringEquals('$.branch', 'right'), new sfn.Pass(this, 'Right Branch'));

    // ...

    this.startState = choice;
    this.endStates = choice.afterwards().endStates;
  }
}

class MyStack extends Stack {
  constructor(scope: Construct, id: string) {
    super(scope, id);
    // Do 3 different variants of MyJob in parallel
    const parallel = new sfn.Parallel(this, 'All jobs')
      .branch(new MyJob(this, 'Quick', { jobFlavor: 'quick' }).prefixStates())
      .branch(new MyJob(this, 'Medium', { jobFlavor: 'medium' }).prefixStates())
      .branch(new MyJob(this, 'Slow', { jobFlavor: 'slow' }).prefixStates());

    new sfn.StateMachine(this, 'MyStateMachine', {
      definition: parallel,
    });
  }
}

有一些用于解析状态机器碎片的功能.

  • State.findReachableStates:从给定州取出可以到达的州列表.
  • State.findReachableEndStates:从给定状态获取可到达的结束状态或终端状态列表.

活动

活 动 代表在一些非兰巴达工人池上完成的工作。 这个 步骤功能工作流程将向本活动提交工作,并提供一个工人人才库 你运行自己, 很可能在EC2, 将调用工作 从活动 提交个人工作的结果.

您需要 ARN 这样做, 因此, 如果您使用活动 请确定通过活动 ARN进入你的工人池:

const activity = new sfn.Activity(this, 'Activity');

// Read this CloudFormation Output from your application and use it to poll for work on
// the activity.
new CfnOutput(this, 'ActivityArn', { value: activity.activityArn });

活动级别权限

向某项活动授予IAM许可可通过以下方式实现: grant(principal, actions) API : (英语)

const activity = new sfn.Activity(this, 'Activity');

const role = new iam.Role(this, 'Role', {
  assumedBy: new iam.ServicePrincipal('lambda.amazonaws.com'),
});

activity.grant(role, 'states:SendTaskSuccess');

这将使IAM本金能够对活动采取特定行动.

计量

Task 对象显示执行该特定任务的各种衡量标准。 譬如说, 创建一个针对特定任务的提醒失败 :

declare const task: sfn.Task;
new cloudwatch.Alarm(this, 'TaskAlarm', {
  metric: task.metricFailed(),
  threshold: 1,
  evaluationPeriods: 1,
});

完整的状态机器上也有测量标准:

declare const stateMachine: sfn.StateMachine;
new cloudwatch.Alarm(this, 'StateMachineAlarm', {
  metric: stateMachine.metricFailed(),
  threshold: 1,
  evaluationPeriods: 1,
});

你账户中所有国有机器的容量都有衡量标准:

new cloudwatch.Alarm(this, 'ThrottledAlarm', {
  metric: sfn.StateTransitionMetric.metricThrottledEvents(),
  threshold: 10,
  evaluationPeriods: 2,
});

错误名称

Step Functions在亚马逊州语言中使用对大小写敏感的字符串识别出错误,称为出错名. Amazon States Language定义了一组内置字符串,这些字符串命名了众所周知的错误,所有错误都始于 States. 前缀.

  • States.ALL - 匹配任何已知错误名称的通配符.
  • States.Runtime - 由于无法处理的例外情况,执行失败。 这些往往是运行时出错造成的,例如试图将IntentPath或OputPath应用到一个无效的JSON有效载荷上. A 类 States.Runtime 错误是无法回收的, 并且总是会导致执行失败 。 重试或抓取 States.ALL 它不会抓住国家。 运行时间错误 .
  • States.DataLimitExceeded - 一个州。 DataLimit 超限例外将丢弃如下:
    • 当连接器的输出大于有效载荷尺寸配额时.
    • 当一个状态的输出大于有效载荷尺寸配额时.
    • 当参数处理后,一个状态的输入大于有效载荷尺寸配额.
    • 见 aWS 文档 以了解更多 AWS 步骤函数配额.
  • States.HeartbeatTimeout - 一个任务状态未能发送一个心跳超过心跳秒值的时间.
  • States.Timeout - 任务状态要么运行时间长于超时秒值,要么在超时秒值的时间内未能发送心跳.
  • States.TaskFailed- 任务状态在执行过程中失败 。 当用在重试或捕获, States.TaskFailed 充当匹配任何已知错误名称的通配符,但 States.Timeout。 。 。 .

日志

通过通过一个带有“云表”的日志配置来启用记录到“云表” 目标日志组 :

import * as logs from '@aws-cdk/aws-logs';

const logGroup = new logs.LogGroup(this, 'MyLogGroup');

new sfn.StateMachine(this, 'MyStateMachine', {
  definition: sfn.Chain.start(new sfn.Pass(this, 'Pass')),
  logs: {
    destination: logGroup,
    level: sfn.LogLevel.ALL,
  },
});

X-Ray 追踪

启用 StateMachine 的 X- Ray 追踪 :

new sfn.StateMachine(this, 'MyStateMachine', {
  definition: sfn.Chain.start(new sfn.Pass(this, 'Pass')),
  tracingEnabled: true,
});

见 aWS 文档 以便更多地了解 AWS Step 函数的 X-Ray 支持.

国家机器许可赠款

需要与国家机器合作的IAM角色、用户或团体应获得IAM许可.

执行 IGrantable 接口(有相关主机)可以通过调用:

  • stateMachine.grantStartExecution(principal) - 赋予校长执行国家机器的能力
  • stateMachine.grantRead(principal) - 允许本金阅读访问
  • stateMachine.grantTaskResponse(principal) - 使校长能够向国家机器发送任务标志
  • stateMachine.grantExecution(principal, actions) - 为指定的IAM行动提供主要执行级别许可
  • stateMachine.grant(principal, actions) - 授予国家机器一级主要许可,以开展所指明的IAM行动

开始执行权限

允许通过调用 grantStartExecution() API (英语).

const role = new iam.Role(this, 'Role', {
  assumedBy: new iam.ServicePrincipal('lambda.amazonaws.com'),
});

declare const definition: sfn.IChainable;
const stateMachine = new sfn.StateMachine(this, 'StateMachine', {
  definition,
});

// Give role permission to start execution of state machine
stateMachine.grantStartExecution(role);

下列许可由服务负责人提供: grantStartExecution() API : (英语)

  • states:StartExecution - 到国家机器

读取权限

赠款 read 通过调用状态机器访问 grantRead() API (英语).

const role = new iam.Role(this, 'Role', {
  assumedBy: new iam.ServicePrincipal('lambda.amazonaws.com'),
});

declare const definition: sfn.IChainable;
const stateMachine = new sfn.StateMachine(this, 'StateMachine', {
  definition,
});

// Give role read access to state machine
stateMachine.grantRead(role);

下列阅读权限由服务负责人提供: grantRead() API : (英语)

  • states:ListExecutions - 到国家机器
  • states:ListStateMachines - 到国家机器
  • states:DescribeExecution - 死刑
  • states:DescribeStateMachineForExecution - 死刑
  • states:GetExecutionHistory - 死刑
  • states:ListActivities - 对 *
  • states:DescribeStateMachine - 对 *
  • states:DescribeActivity - 对 *

任务响应权限

通过调用 grantTaskResponse() API : (英语)

const role = new iam.Role(this, 'Role', {
  assumedBy: new iam.ServicePrincipal('lambda.amazonaws.com'),
});

declare const definition: sfn.IChainable;
const stateMachine = new sfn.StateMachine(this, 'StateMachine', {
  definition,
});

// Give role task response permissions to the state machine
stateMachine.grantTaskResponse(role);

下列阅读权限由服务负责人提供: grantRead() API : (英语)

  • states:SendTaskSuccess - 到国家机器
  • states:SendTaskFailure - 到国家机器
  • states:SendTaskHeartbeat - 到国家机器

执行级别权限

通过调用 grantExecution() API : (英语)

const role = new iam.Role(this, 'Role', {
  assumedBy: new iam.ServicePrincipal('lambda.amazonaws.com'),
});

declare const definition: sfn.IChainable;
const stateMachine = new sfn.StateMachine(this, 'StateMachine', {
  definition,
});

// Give role permission to get execution history of ALL executions for the state machine
stateMachine.grantExecution(role, 'states:GetExecutionHistory');

自定义权限

您可以通过调用 : grant() API (英语).

const user = new iam.User(this, 'MyUser');

declare const definition: sfn.IChainable;
const stateMachine = new sfn.StateMachine(this, 'StateMachine', {
  definition,
});

//give user permission to send task success to the state machine
stateMachine.grant(user, 'states:SendTaskSuccess');

导入

堆栈外已创建的任何步骤函数状态机都可以被导入 输入您的 CDK 堆栈.

国产机器可通过ARN进口 StateMachine.fromStateMachineArn() API 密码

const app = new App();
const stack = new Stack(app, 'MyStack');
sfn.StateMachine.fromStateMachineArn(
  stack,
  'ImportedStateMachine',
  'arn:aws:states:us-east-1:123456789012:stateMachine:StateMachine2E01A3A5-N5TJppzoevKQ',
);

版本与发布记录

@aws-cdk/aws-stepfunctions 共发布 288 个版本,首次发布于 2018/07/31;过去 12 个月发布了 0 个版本。

版本发布日期距今
1.204.0latest2023/06/203 年前
1.203.02023/06/013 年前
1.202.02023/05/223 年前
1.201.02023/05/113 年前
1.200.02023/04/273 年前
1.199.02023/04/213 年前

关于 @aws-cdk/aws-stepfunctions 的常见问题

@aws-cdk/aws-stepfunctions 是什么?

AWS: StepFuns 的 CDK 构建库注意:该包已被作者标记为弃用——AWS CDK v1 has reached End-of-Support on 2023-06-01. This package is no longer being updated, and users should migrate to AWS CDK v2. For more information on how to migrate, see https://docs.aws.amazon.com/cdk/v2/guide/migrating-v2.html

如何安装 @aws-cdk/aws-stepfunctions?

在项目目录运行 npm install @aws-cdk/aws-stepfunctions,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:@aws-cdk/aws-cloudwatch(1.204.0)、@aws-cdk/aws-events(1.204.0)、@aws-cdk/aws-iam(1.204.0)、@aws-cdk/aws-logs(1.204.0)、@aws-cdk/aws-s3(1.204.0)、@aws-cdk/core(1.204.0)、constructs(^3.3.69)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。

@aws-cdk/aws-stepfunctions 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@aws-cdk/aws-stepfunctions 支持 ESM 还是 CommonJS?

以 CommonJS 形式发布,可以直接 require();在 ES Module 项目中也可以用 import 引入(Node.js 会把 module.exports 作为默认导出)。

@aws-cdk/aws-stepfunctions 需要什么版本的 Node.js?

package.json 的 engines 字段要求 Node.js >= 14.15.0。版本不符时 npm 默认只给出警告,开启 engine-strict 后会拒绝安装。

@aws-cdk/aws-stepfunctions 可以商用吗?

@aws-cdk/aws-stepfunctions 使用 Apache-2.0 许可。宽松许可:允许商业使用、修改和再分发,并附带明确的专利授权;分发时需保留许可与 NOTICE 文件,修改过的文件要注明改动。以上为概括,不构成法律意见,请以许可原文为准。

@aws-cdk/aws-stepfunctions 的下载量有多少?

根据 npm 官方下载统计,@aws-cdk/aws-stepfunctions 在 2026/10/08 – 2026/11/06 这 30 天内被下载 148,531 次,日均约 4,951 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@aws-cdk/aws-stepfunctions 还在维护吗?

最新版本 1.204.0 发布于 2023/06/20(3 年前);至今共发布 288 个版本,其中过去 12 个月发布了 0 个;首次发布于 2018/07/31。作者已将其标记为弃用,新项目建议寻找替代方案。