See: Description
| Interface | Description |
|---|---|
| ActivityProps |
(experimental) Properties for defining a new Step Functions Activity.
|
| AfterwardsOptions |
(experimental) Options for selecting the choice paths.
|
| CatchProps |
(experimental) Error handler details.
|
| CfnActivity.TagsEntryProperty | |
| CfnActivityProps |
Properties for defining a `AWS::StepFunctions::Activity`.
|
| CfnStateMachine.CloudWatchLogsLogGroupProperty | |
| CfnStateMachine.DefinitionProperty | |
| CfnStateMachine.LogDestinationProperty | |
| CfnStateMachine.LoggingConfigurationProperty | |
| CfnStateMachine.S3LocationProperty | |
| CfnStateMachine.TagsEntryProperty | |
| CfnStateMachine.TracingConfigurationProperty | |
| CfnStateMachineProps |
Properties for defining a `AWS::StepFunctions::StateMachine`.
|
| ChoiceProps |
(experimental) Properties for defining a Choice state.
|
| CustomStateProps |
(experimental) Properties for defining a custom state definition.
|
| FailProps |
(experimental) Properties for defining a Fail state.
|
| FindStateOptions |
(experimental) Options for finding reachable states.
|
| IActivity |
(experimental) Represents a Step Functions Activity https://docs.aws.amazon.com/step-functions/latest/dg/concepts-activities.html.
|
| IActivity.Jsii$Default |
Internal default implementation for
IActivity. |
| IChainable |
(experimental) Interface for objects that can be used in a Chain.
|
| IChainable.Jsii$Default |
Internal default implementation for
IChainable. |
| INextable |
(experimental) Interface for states that can have 'next' states.
|
| INextable.Jsii$Default |
Internal default implementation for
INextable. |
| IStateMachine |
(experimental) A State Machine.
|
| IStateMachine.Jsii$Default |
Internal default implementation for
IStateMachine. |
| LogOptions |
(experimental) Defines what execution history events are logged and where they are logged.
|
| MapProps |
(experimental) Properties for defining a Map state.
|
| ParallelProps |
(experimental) Properties for defining a Parallel state.
|
| PassProps |
(experimental) Properties for defining a Pass state.
|
| RetryProps |
(experimental) Retry details.
|
| SingleStateOptions |
(experimental) Options for creating a single state.
|
| StateMachineProps |
(experimental) Properties for defining a State Machine.
|
| StateProps |
(experimental) Properties shared by all states.
|
| SucceedProps |
(experimental) Properties for defining a Succeed state.
|
| TaskMetricsConfig |
(experimental) Task Metrics.
|
| TaskStateBaseProps |
(experimental) Props that are common to all tasks.
|
| WaitProps |
(experimental) Properties for defining a Wait state.
|
| Class | Description |
|---|---|
| Activity |
(experimental) Define a new Step Functions Activity.
|
| Activity.Builder |
(experimental) A fluent builder for
Activity. |
| ActivityProps.Builder |
A builder for
ActivityProps |
| ActivityProps.Jsii$Proxy |
An implementation for
ActivityProps |
| AfterwardsOptions.Builder |
A builder for
AfterwardsOptions |
| AfterwardsOptions.Jsii$Proxy |
An implementation for
AfterwardsOptions |
| CatchProps.Builder |
A builder for
CatchProps |
| CatchProps.Jsii$Proxy |
An implementation for
CatchProps |
| CfnActivity |
A CloudFormation `AWS::StepFunctions::Activity`.
|
| CfnActivity.Builder |
A fluent builder for
CfnActivity. |
| CfnActivity.TagsEntryProperty.Builder |
A builder for
CfnActivity.TagsEntryProperty |
| CfnActivity.TagsEntryProperty.Jsii$Proxy |
An implementation for
CfnActivity.TagsEntryProperty |
| CfnActivityProps.Builder |
A builder for
CfnActivityProps |
| CfnActivityProps.Jsii$Proxy |
An implementation for
CfnActivityProps |
| CfnStateMachine |
A CloudFormation `AWS::StepFunctions::StateMachine`.
|
| CfnStateMachine.Builder |
A fluent builder for
CfnStateMachine. |
| CfnStateMachine.CloudWatchLogsLogGroupProperty.Builder |
A builder for
CfnStateMachine.CloudWatchLogsLogGroupProperty |
| CfnStateMachine.CloudWatchLogsLogGroupProperty.Jsii$Proxy |
An implementation for
CfnStateMachine.CloudWatchLogsLogGroupProperty |
| CfnStateMachine.DefinitionProperty.Builder |
A builder for
CfnStateMachine.DefinitionProperty |
| CfnStateMachine.DefinitionProperty.Jsii$Proxy |
An implementation for
CfnStateMachine.DefinitionProperty |
| CfnStateMachine.LogDestinationProperty.Builder |
A builder for
CfnStateMachine.LogDestinationProperty |
| CfnStateMachine.LogDestinationProperty.Jsii$Proxy |
An implementation for
CfnStateMachine.LogDestinationProperty |
| CfnStateMachine.LoggingConfigurationProperty.Builder |
A builder for
CfnStateMachine.LoggingConfigurationProperty |
| CfnStateMachine.LoggingConfigurationProperty.Jsii$Proxy |
An implementation for
CfnStateMachine.LoggingConfigurationProperty |
| CfnStateMachine.S3LocationProperty.Builder |
A builder for
CfnStateMachine.S3LocationProperty |
| CfnStateMachine.S3LocationProperty.Jsii$Proxy |
An implementation for
CfnStateMachine.S3LocationProperty |
| CfnStateMachine.TagsEntryProperty.Builder |
A builder for
CfnStateMachine.TagsEntryProperty |
| CfnStateMachine.TagsEntryProperty.Jsii$Proxy |
An implementation for
CfnStateMachine.TagsEntryProperty |
| CfnStateMachine.TracingConfigurationProperty.Builder |
A builder for
CfnStateMachine.TracingConfigurationProperty |
| CfnStateMachine.TracingConfigurationProperty.Jsii$Proxy |
An implementation for
CfnStateMachine.TracingConfigurationProperty |
| CfnStateMachineProps.Builder |
A builder for
CfnStateMachineProps |
| CfnStateMachineProps.Jsii$Proxy |
An implementation for
CfnStateMachineProps |
| Chain |
(experimental) A collection of states to chain onto.
|
| Choice |
(experimental) Define a Choice in the state machine.
|
| Choice.Builder |
(experimental) A fluent builder for
Choice. |
| ChoiceProps.Builder |
A builder for
ChoiceProps |
| ChoiceProps.Jsii$Proxy |
An implementation for
ChoiceProps |
| Condition |
(experimental) A Condition for use in a Choice state branch.
|
| CustomState |
(experimental) State defined by supplying Amazon States Language (ASL) in the state machine.
|
| CustomState.Builder |
(experimental) A fluent builder for
CustomState. |
| CustomStateProps.Builder |
A builder for
CustomStateProps |
| CustomStateProps.Jsii$Proxy |
An implementation for
CustomStateProps |
| Errors |
(experimental) Predefined error strings Error names in Amazon States Language - https://states-language.net/spec.html#appendix-a Error handling in Step Functions - https://docs.aws.amazon.com/step-functions/latest/dg/concepts-error-handling.html.
|
| Fail |
(experimental) Define a Fail state in the state machine.
|
| Fail.Builder |
(experimental) A fluent builder for
Fail. |
| FailProps.Builder |
A builder for
FailProps |
| FailProps.Jsii$Proxy |
An implementation for
FailProps |
| FieldUtils |
(experimental) Helper functions to work with structures containing fields.
|
| FindStateOptions.Builder |
A builder for
FindStateOptions |
| FindStateOptions.Jsii$Proxy |
An implementation for
FindStateOptions |
| IActivity.Jsii$Proxy |
A proxy class which represents a concrete javascript instance of this type.
|
| IChainable.Jsii$Proxy |
A proxy class which represents a concrete javascript instance of this type.
|
| INextable.Jsii$Proxy |
A proxy class which represents a concrete javascript instance of this type.
|
| IStateMachine.Jsii$Proxy |
A proxy class which represents a concrete javascript instance of this type.
|
| JsonPath |
(experimental) Extract a field from the State Machine data or context that gets passed around between states.
|
| LogOptions.Builder |
A builder for
LogOptions |
| LogOptions.Jsii$Proxy |
An implementation for
LogOptions |
| Map |
(experimental) Define a Map state in the state machine.
|
| Map.Builder |
(experimental) A fluent builder for
Map. |
| MapProps.Builder |
A builder for
MapProps |
| MapProps.Jsii$Proxy |
An implementation for
MapProps |
| Parallel |
(experimental) Define a Parallel state in the state machine.
|
| Parallel.Builder |
(experimental) A fluent builder for
Parallel. |
| ParallelProps.Builder |
A builder for
ParallelProps |
| ParallelProps.Jsii$Proxy |
An implementation for
ParallelProps |
| Pass |
(experimental) Define a Pass in the state machine.
|
| Pass.Builder |
(experimental) A fluent builder for
Pass. |
| PassProps.Builder |
A builder for
PassProps |
| PassProps.Jsii$Proxy |
An implementation for
PassProps |
| Result |
(experimental) The result of a Pass operation.
|
| RetryProps.Builder |
A builder for
RetryProps |
| RetryProps.Jsii$Proxy |
An implementation for
RetryProps |
| SingleStateOptions.Builder |
A builder for
SingleStateOptions |
| SingleStateOptions.Jsii$Proxy |
An implementation for
SingleStateOptions |
| State |
(experimental) Base class for all other state classes.
|
| StateGraph |
(experimental) A collection of connected states.
|
| StateMachine |
(experimental) Define a StepFunctions State Machine.
|
| StateMachine.Builder |
(experimental) A fluent builder for
StateMachine. |
| StateMachineFragment |
(experimental) Base class for reusable state machine fragments.
|
| StateMachineProps.Builder |
A builder for
StateMachineProps |
| StateMachineProps.Jsii$Proxy |
An implementation for
StateMachineProps |
| StateProps.Builder |
A builder for
StateProps |
| StateProps.Jsii$Proxy |
An implementation for
StateProps |
| StateTransitionMetric |
(experimental) Metrics on the rate limiting performed on state machine execution.
|
| Succeed |
(experimental) Define a Succeed state in the state machine.
|
| Succeed.Builder |
(experimental) A fluent builder for
Succeed. |
| SucceedProps.Builder |
A builder for
SucceedProps |
| SucceedProps.Jsii$Proxy |
An implementation for
SucceedProps |
| TaskInput |
(experimental) Type union for task classes that accept multiple types of payload.
|
| TaskMetricsConfig.Builder |
A builder for
TaskMetricsConfig |
| TaskMetricsConfig.Jsii$Proxy |
An implementation for
TaskMetricsConfig |
| TaskStateBase |
(experimental) Define a Task state in the state machine.
|
| TaskStateBaseProps.Builder |
A builder for
TaskStateBaseProps |
| TaskStateBaseProps.Jsii$Proxy |
An implementation for
TaskStateBaseProps |
| Wait |
(experimental) Define a Wait state in the state machine.
|
| Wait.Builder |
(experimental) A fluent builder for
Wait. |
| WaitProps.Builder |
A builder for
WaitProps |
| WaitProps.Jsii$Proxy |
An implementation for
WaitProps |
| WaitTime |
(experimental) Represents the Wait state which delays a state machine from continuing for a specified time.
|
| Enum | Description |
|---|---|
| InputType |
(experimental) The type of task input.
|
| IntegrationPattern |
(experimental) AWS Step Functions integrates with services directly in the Amazon States Language.
|
| LogLevel |
(experimental) Defines which category of execution history events are logged.
|
| ServiceIntegrationPattern |
(experimental) Three ways to call an integrated service: Request Response, Run a Job and Wait for a Callback with Task Token.
|
| StateMachineType |
(experimental) Two types of state machines are available in AWS Step Functions: EXPRESS AND STANDARD.
|
---
The @aws-cdk/aws-stepfunctions package contains constructs for building
serverless workflows using objects. Use this in conjunction with the
@aws-cdk/aws-stepfunctions-tasks package, which contains classes used
to call other AWS services.
Defining a workflow looks like this (for the Step Functions Job Poller example):
// Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
import software.amazon.awscdk.aws_stepfunctions;
import software.amazon.awscdk.aws_stepfunctions_tasks;
import software.amazon.awscdk.aws_lambda;
Function submitLambda = new Function(this, "SubmitLambda", new FunctionProps()...);
Function getStatusLambda = new Function(this, "CheckLambda", new FunctionProps()...);
LambdaInvoke submitJob = new LambdaInvoke(this, "Submit Job", new LambdaInvokeProps()
.lambdaFunction(submitLambda)
// Lambda's result is in the attribute `Payload`
.outputPath("$.Payload"));
Wait waitX = new Wait(this, "Wait X Seconds", new WaitProps()
.time(sfn.WaitTime.secondsPath("$.waitSeconds")));
LambdaInvoke getStatus = new LambdaInvoke(this, "Get Job Status", new LambdaInvokeProps()
.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"));
Fail jobFailed = new Fail(this, "Job Failed", new FailProps()
.cause("AWS Batch Job Failed")
.error("DescribeJob returned FAILED"));
LambdaInvoke finalStatus = new LambdaInvoke(this, "Get Final Job Status", new LambdaInvokeProps()
.lambdaFunction(getStatusLambda)
// Use "guid" field as input
.inputPath("$.guid")
.outputPath("$.Payload"));
Chain 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 StateMachine(this, "StateMachine", new StateMachineProps()
.definition(definition)
.timeout(Duration.minutes(5)));
You can find more sample snippets and learn more about the service integrations
in the @aws-cdk/aws-stepfunctions-tasks package.
A stepfunctions.StateMachine is a resource that takes a state machine
definition. The definition is specified by its start state, and encompasses
all states reachable from the start state:
// Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
Object startState = new Pass(this, "StartState");
StateMachine.Builder.create(this, "StateMachine")
.definition(startState)
.build();
State machines execute using an IAM Role, which will automatically have all permissions added that are required to make all state machine tasks execute properly (for example, permissions to invoke any Lambda functions you add to your workflow). A role will be created by default, but you can supply an existing one as well.
This library comes with a set of classes that model the Amazon States Language. The following State classes are supported:
An arbitrary JSON object (specified at execution start) is passed from state to state and transformed during the execution of the workflow. For more information, see the States Language spec.
A Task represents some work that needs to be done. The exact work to be
done is determine by a class that implements IStepFunctionsTask, a collection
of which can be found in the @aws-cdk/aws-stepfunctions-tasks module.
The tasks in the @aws-cdk/aws-stepfunctions-tasks module support the
service integration pattern that integrates Step Functions with services
directly in the Amazon States language.
A Pass state passes its input to its output, without performing work.
Pass states are useful when constructing and debugging state machines.
The following example injects some fixed data into the state machine through
the result field. The result field will be added to the input and the result
will be passed as the state's output.
// Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
// Makes the current JSON state { ..., "subObject": { "hello": "world" } }
Object pass = Pass.Builder.create(this, "Add Hello World")
.result(sfn.Result.fromObject(Map.of("hello", "world")))
.resultPath("$.subObject")
.build();
// Set the next state
pass.next(nextState);
The Pass state also supports passing key-value pairs as input. Values can
be static, or selected from the input with a path.
The following example filters the greeting field from the state input
and also injects a field called otherData.
// Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
Object pass = Pass.Builder.create(this, "Filter input and inject data")
.parameters(Map.of(// input to the pass state
"input", sfn.JsonPath.stringAt("$.input.greeting"),
"otherData", "some-extra-stuff"))
.build();
The object specified in parameters will be the input of the Pass state.
Since neither Result nor ResultPath are supplied, the Pass state copies
its input through to its output.
Learn more about the Pass state
A Wait state waits for a given number of seconds, or until the current time
hits a particular time. The time to wait may be taken from the execution's JSON
state.
// Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
// Wait until it's the time mentioned in the the state object's "triggerTime"
// field.
Object wait = Wait.Builder.create(this, "Wait For Trigger Time")
.time(sfn.WaitTime.timestampPath("$.triggerTime"))
.build();
// Set the next state
wait.next(startTheWork);
A Choice state can take a different path through the workflow based on the
values in the execution's JSON state:
// Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
Object choice = new Choice(this, "Did it work?");
// Add conditions with .when()
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
choice.otherwise(tryAgainState);
If you want to temporarily branch your workflow based on a condition, but have
all branches come together and continuing as one (similar to how an if ... then ... else works in a programming language), use the .afterwards() method:
// Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
Object choice = new Choice(this, "What color is it?");
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
choice.afterwards().next(shipTheItem);
If your Choice doesn't have an otherwise() and none of the conditions match
the JSON state, a NoChoiceMatched error will be thrown. Wrap the state machine
in a Parallel state if you want to catch and recover from this.
see step function comparison operators
Condition.isPresent - matches if a json path is presentCondition.isNotPresent - matches if a json path is not presentCondition.isString - matches if a json path contains a stringCondition.isNotString - matches if a json path is not a stringCondition.isNumeric - matches if a json path is numericCondition.isNotNumeric - matches if a json path is not numericCondition.isBoolean - matches if a json path is booleanCondition.isNotBoolean - matches if a json path is not booleanCondition.isTimestamp - matches if a json path is a timestampCondition.isNotTimestamp - matches if a json path is not a timestampCondition.isNotNull - matches if a json path is not nullCondition.isNull - matches if a json path is nullCondition.booleanEquals - matches if a boolean field has a given valueCondition.booleanEqualsJsonPath - matches if a boolean field equals a value in a given mapping pathCondition.stringEqualsJsonPath - matches if a string field equals a given mapping pathCondition.stringEquals - matches if a field equals a string valueCondition.stringLessThan - matches if a string field sorts before a given valueCondition.stringLessThanJsonPath - matches if a string field sorts before a value at given mapping pathCondition.stringLessThanEquals - matches if a string field sorts equal to or before a given valueCondition.stringLessThanEqualsJsonPath - matches if a string field sorts equal to or before a given mappingCondition.stringGreaterThan - matches if a string field sorts after a given valueCondition.stringGreaterThanJsonPath - matches if a string field sorts after a value at a given mapping pathCondition.stringGreaterThanEqualsJsonPath - matches if a string field sorts after or equal to value at a given mapping pathCondition.stringGreaterThanEquals - matches if a string field sorts after or equal to a given valueCondition.numberEquals - matches if a numeric field has the given valueCondition.numberEqualsJsonPath - matches if a numeric field has the value in a given mapping pathCondition.numberLessThan - matches if a numeric field is less than the given valueCondition.numberLessThanJsonPath - matches if a numeric field is less than the value at the given mapping pathCondition.numberLessThanEquals - matches if a numeric field is less than or equal to the given valueCondition.numberLessThanEqualsJsonPath - matches if a numeric field is less than or equal to the numeric value at given mapping pathCondition.numberGreaterThan - matches if a numeric field is greater than the given valueCondition.numberGreaterThanJsonPath - matches if a numeric field is greater than the value at a given mapping pathCondition.numberGreaterThanEquals - matches if a numeric field is greater than or equal to the given valueCondition.numberGreaterThanEqualsJsonPath - matches if a numeric field is greater than or equal to the value at a given mapping pathCondition.timestampEquals - matches if a timestamp field is the same time as the given timestampCondition.timestampEqualsJsonPath - matches if a timestamp field is the same time as the timestamp at a given mapping pathCondition.timestampLessThan - matches if a timestamp field is before the given timestampCondition.timestampLessThanJsonPath - matches if a timestamp field is before the timestamp at a given mapping pathCondition.timestampLessThanEquals - matches if a timestamp field is before or equal to the given timestampCondition.timestampLessThanEqualsJsonPath - matches if a timestamp field is before or equal to the timestamp at a given mapping pathCondition.timestampGreaterThan - matches if a timestamp field is after the timestamp at a given mapping pathCondition.timestampGreaterThanJsonPath - matches if a timestamp field is after the timestamp at a given mapping pathCondition.timestampGreaterThanEquals - matches if a timestamp field is after or equal to the given timestampCondition.timestampGreaterThanEqualsJsonPath - matches if a timestamp field is after or equal to the timestamp at a given mapping pathCondition.stringMatches - matches if a field matches a string pattern that can contain a wild card () e.g: log-.txt or LATEST. No other characters other than "" have any special meaning - * can be escaped: \
A Parallel state executes one or more subworkflows in parallel. It can also
be used to catch and recover from errors in subworkflows.
// Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
Object parallel = new Parallel(this, "Do the work in parallel");
// Add branches to be executed in parallel
parallel.branch(shipItem);
parallel.branch(sendInvoice);
parallel.branch(restock);
// Retry the whole workflow if something goes wrong
parallel.addRetry(Map.of("maxAttempts", 1));
// How to recover from errors
parallel.addCatch(sendFailureNotification);
// What to do in case everything succeeded
parallel.next(closeOrder);
Reaching a Succeed state terminates the state machine execution with a
successful status.
// Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826 Object success = new Succeed(this, "We did it!");
Reaching a Fail state terminates the state machine execution with a
failure status. The fail state should report the reason for the failure.
Failures can be caught by encompassing Parallel states.
// Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
Object success = Fail.Builder.create(this, "Fail")
.error("WorkflowFailure")
.cause("Something went wrong")
.build();
A Map state can be used to run a set of steps for each element of an input array.
A Map state will execute the same steps for multiple entries of an array in the state input.
While the Parallel state executes multiple branches of steps using the same input, a Map state will
execute the same steps for multiple entries of an array in the state input.
// Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
Object map = Map.Builder.create(this, "Map State")
.maxConcurrency(1)
.itemsPath(sfn.JsonPath.stringAt("$.inputForMap"))
.build();
map.iterator(new Pass(this, "Pass State"));
It's possible that the high-level constructs for the states or stepfunctions-tasks do not have
the states or service integrations you are looking for. The primary reasons for this lack of
functionality are:
If a feature is not available, a CustomState can be used to supply any Amazon States Language
JSON-based object as the state definition.
Code Snippets are available and can be plugged in as the state definition.
Custom states can be chained together with any of the other states to create your state machine
definition. You will also need to provide any permissions that are required to the role that
the State Machine uses.
The following example uses the DynamoDB service integration to insert data into a DynamoDB table.
// Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
import software.amazon.awscdk.aws_dynamodb;
import software.amazon.awscdk.*;
import software.amazon.awscdk.aws_stepfunctions;
// create a table
Table table = new Table(this, "montable", new TableProps()
.partitionKey(new Attribute()
.name("id")
.type(ddb.AttributeType.getSTRING())));
Pass finalStatus = new Pass(stack, "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
__object stateJson = Map.of(
"Type", "Task",
"Resource", "arn:aws:states:::dynamodb:putItem",
"Parameters", Map.of(
"TableName", table.getTableName(),
"Item", Map.of(
"id", Map.of(
"S", "MyEntry"))),
"ResultPath", null);
// custom state which represents a task to insert data into DynamoDB
CustomState custom = new CustomState(this, "my custom task", new CustomStateProps()
.stateJson(stateJson));
Chain chain = sfn.Chain.start(custom).next(finalStatus);
StateMachine sm = new StateMachine(this, "StateMachine", new StateMachineProps()
.definition(chain)
.timeout(cdk.Duration.seconds(30)));
// don't forget permissions. You need to assign them
table.grantWriteData(sm);
To make defining work flows as convenient (and readable in a top-to-bottom way)
as writing regular programs, it is possible to chain most methods invocations.
In particular, the .next() method can be repeated. The result of a series of
.next() calls is called a Chain, and can be used when defining the jump
targets of Choice.on or Parallel.branch:
// Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
Object 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);
StateMachine.Builder.create(this, "StateMachine")
.definition(definition)
.build();
If you don't like the visual look of starting a chain directly off the first
step, you can use Chain.start:
// Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
Object definition = sfn.Chain
.start(step1)
.next(step2).next(step3);
It is possible to define reusable (or abstracted) mini-state machines by
defining a construct that implements IChainable, which requires you to define
two fields:
startState: State, representing the entry point into this state machine.endStates: INextable[], representing the (one or more) states that outgoing
transitions will be added to if you chain onto the fragment.Since states will be named after their construct IDs, you may need to prefix the IDs of states if you plan to instantiate the same state machine fragment multiples times (otherwise all states in every instantiation would have the same name).
The class StateMachineFragment contains some helper functions (like
prefixStates()) to make it easier for you to do this. If you define your state
machine as a subclass of this, it will be convenient to use:
// Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
public class MyJobProps {
private String jobFlavor;
public String getJobFlavor() {
return this.jobFlavor;
}
public MyJobProps jobFlavor(String jobFlavor) {
this.jobFlavor = jobFlavor;
return this;
}
}
public class MyJob extends StateMachineFragment {
public final Object startState;
public final Array endStates;
public MyJob(Construct parent, String id, MyJobProps props) {
super(parent, id);
Object first = Task.Builder.create(this, "First")....build();
// ...
Object last = Task.Builder.create(this, "Last")....build();
this.startState = first;
this.endStates = asList(last);
}
}
// Do 3 different variants of MyJob in 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());
A few utility functions are available to parse state machine fragments.
State.findReachableStates: Retrieve the list of states reachable from a given state.State.findReachableEndStates: Retrieve the list of end or terminal states reachable from a given state.
Activities represent work that is done on some non-Lambda worker pool. The Step Functions workflow will submit work to this Activity, and a worker pool that you run yourself, probably on EC2, will pull jobs from the Activity and submit the results of individual jobs back.
You need the ARN to do so, so if you use Activities be sure to pass the Activity ARN into your worker pool:
// Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826 Object activity = new Activity(this, "Activity"); // Read this CloudFormation Output from your application and use it to poll for work on // the activity. // Read this CloudFormation Output from your application and use it to poll for work on // the activity. CfnOutput.Builder.create(this, "ActivityArn").value(activity.getActivityArn()).build();
Granting IAM permissions to an activity can be achieved by calling the grant(principal, actions) API:
// Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
Object activity = new Activity(this, "Activity");
Role role = new Role(stack, "Role", new RoleProps()
.assumedBy(new ServicePrincipal("lambda.amazonaws.com")));
activity.grant(role, "states:SendTaskSuccess");
This will grant the IAM principal the specified actions onto the activity.
Task object expose various metrics on the execution of that particular task. For example,
to create an alarm on a particular task failing:
// Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
Alarm.Builder.create(this, "TaskAlarm")
.metric(task.metricFailed())
.threshold(1)
.evaluationPeriods(1)
.build();
There are also metrics on the complete state machine:
// Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
Alarm.Builder.create(this, "StateMachineAlarm")
.metric(stateMachine.metricFailed())
.threshold(1)
.evaluationPeriods(1)
.build();
And there are metrics on the capacity of all state machines in your account:
// Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
Alarm.Builder.create(this, "ThrottledAlarm")
.metric(StateTransitionMetrics.metricThrottledEvents())
.threshold(10)
.evaluationPeriods(2)
.build();
Enable logging to CloudWatch by passing a logging configuration with a destination LogGroup:
// Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
Object logGroup = new LogGroup(stack, "MyLogGroup");
StateMachine.Builder.create(stack, "MyStateMachine")
.definition(sfn.Chain.start(new Pass(stack, "Pass")))
.logs(Map.of(
"destination", logGroup,
"level", sfn.LogLevel.getALL()))
.build();
Enable X-Ray tracing for StateMachine:
// Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
Object logGroup = new LogGroup(stack, "MyLogGroup");
StateMachine.Builder.create(stack, "MyStateMachine")
.definition(sfn.Chain.start(new Pass(stack, "Pass")))
.tracingEnabled(true)
.build();
See the AWS documentation to learn more about AWS Step Functions's X-Ray support.
IAM roles, users, or groups which need to be able to work with a State Machine should be granted IAM permissions.
Any object that implements the IGrantable interface (has an associated principal) can be granted permissions by calling:
stateMachine.grantStartExecution(principal) - grants the principal the ability to execute the state machinestateMachine.grantRead(principal) - grants the principal read accessstateMachine.grantTaskResponse(principal) - grants the principal the ability to send task tokens to the state machinestateMachine.grantExecution(principal, actions) - grants the principal execution-level permissions for the IAM actions specifiedstateMachine.grant(principal, actions) - grants the principal state-machine-level permissions for the IAM actions specified
Grant permission to start an execution of a state machine by calling the grantStartExecution() API.
// Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
Role role = new Role(stack, "Role", new RoleProps()
.assumedBy(new ServicePrincipal("lambda.amazonaws.com")));
Object stateMachine = StateMachine.Builder.create(stack, "StateMachine")
.definition(definition)
.build();
// Give role permission to start execution of state machine
stateMachine.grantStartExecution(role);
The following permission is provided to a service principal by the grantStartExecution() API:
states:StartExecution - to state machine
Grant read access to a state machine by calling the grantRead() API.
// Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
Role role = new Role(stack, "Role", new RoleProps()
.assumedBy(new ServicePrincipal("lambda.amazonaws.com")));
Object stateMachine = StateMachine.Builder.create(stack, "StateMachine")
.definition(definition)
.build();
// Give role read access to state machine
stateMachine.grantRead(role);
The following read permissions are provided to a service principal by the grantRead() API:
states:ListExecutions - to state machinestates:ListStateMachines - to state machinestates:DescribeExecution - to executionsstates:DescribeStateMachineForExecution - to executionsstates:GetExecutionHistory - to executionsstates:ListActivities - to *states:DescribeStateMachine - to *states:DescribeActivity - to *
Grant permission to allow task responses to a state machine by calling the grantTaskResponse() API:
// Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
Role role = new Role(stack, "Role", new RoleProps()
.assumedBy(new ServicePrincipal("lambda.amazonaws.com")));
Object stateMachine = StateMachine.Builder.create(stack, "StateMachine")
.definition(definition)
.build();
// Give role task response permissions to the state machine
stateMachine.grantTaskResponse(role);
The following read permissions are provided to a service principal by the grantRead() API:
states:SendTaskSuccess - to state machinestates:SendTaskFailure - to state machinestates:SendTaskHeartbeat - to state machine
Grant execution-level permissions to a state machine by calling the grantExecution() API:
// Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
Role role = new Role(stack, "Role", new RoleProps()
.assumedBy(new ServicePrincipal("lambda.amazonaws.com")));
Object stateMachine = StateMachine.Builder.create(stack, "StateMachine")
.definition(definition)
.build();
// Give role permission to get execution history of ALL executions for the state machine
stateMachine.grantExecution(role, "states:GetExecutionHistory");
You can add any set of permissions to a state machine by calling the grant() API.
// Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
User user = new User(stack, "MyUser");
Object stateMachine = StateMachine.Builder.create(stack, "StateMachine")
.definition(definition)
.build();
//give user permission to send task success to the state machine
stateMachine.grant(user, "states:SendTaskSuccess");
Any Step Functions state machine that has been created outside the stack can be imported into your CDK stack.
State machines can be imported by their ARN via the StateMachine.fromStateMachineArn() API
// Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826 import aws.stepfunctions.*; Stack stack = new Stack(app, "MyStack"); sfn.StateMachine.fromStateMachineArn(stack, "ImportedStateMachine", "arn:aws:states:us-east-1:123456789012:stateMachine:StateMachine2E01A3A5-N5TJppzoevKQ");
Copyright © 2021. All rights reserved.