Skip navigation links

Package software.amazon.awscdk.services.stepfunctions

AWS Step Functions Construct Library

See: Description

Package software.amazon.awscdk.services.stepfunctions Description

AWS Step Functions Construct Library

---

cfn-resources: Stable

cdk-constructs: Stable


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

 import software.amazon.awscdk.services.lambda.*;
 
 Function submitLambda;
 Function getStatusLambda;
 
 
 LambdaInvoke submitJob = LambdaInvoke.Builder.create(this, "Submit Job")
         .lambdaFunction(submitLambda)
         // Lambda's result is in the attribute `Payload`
         .outputPath("$.Payload")
         .build();
 
 Wait waitX = Wait.Builder.create(this, "Wait X Seconds")
         .time(WaitTime.secondsPath("$.waitSeconds"))
         .build();
 
 LambdaInvoke getStatus = LambdaInvoke.Builder.create(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")
         .build();
 
 Fail jobFailed = Fail.Builder.create(this, "Job Failed")
         .cause("AWS Batch Job Failed")
         .error("DescribeJob returned FAILED")
         .build();
 
 LambdaInvoke finalStatus = LambdaInvoke.Builder.create(this, "Get Final Job Status")
         .lambdaFunction(getStatusLambda)
         // Use "guid" field as input
         .inputPath("$.guid")
         .outputPath("$.Payload")
         .build();
 
 Chain definition = submitJob.next(waitX).next(getStatus).next(new Choice(this, "Job Complete?").when(Condition.stringEquals("$.status", "FAILED"), jobFailed).when(Condition.stringEquals("$.status", "SUCCEEDED"), finalStatus).otherwise(waitX));
 
 StateMachine.Builder.create(this, "StateMachine")
         .definition(definition)
         .timeout(Duration.minutes(5))
         .build();
 

You can find more sample snippets and learn more about the service integrations in the @aws-cdk/aws-stepfunctions-tasks package.

State Machine

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:

 Pass 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.

Amazon States Language

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.

Task

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.

Pass

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.

 // Makes the current JSON state { ..., "subObject": { "hello": "world" } }
 Pass pass = Pass.Builder.create(this, "Add Hello World")
         .result(Result.fromObject(Map.of("hello", "world")))
         .resultPath("$.subObject")
         .build();
 
 // Set the next state
 Pass nextState = new Pass(this, "NextState");
 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.

 Pass pass = Pass.Builder.create(this, "Filter input and inject data")
         .parameters(Map.of( // input to the pass state
                 "input", 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

Wait

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.

 // Wait until it's the time mentioned in the the state object's "triggerTime"
 // field.
 Wait wait = Wait.Builder.create(this, "Wait For Trigger Time")
         .time(WaitTime.timestampPath("$.triggerTime"))
         .build();
 
 // Set the next state
 Pass startTheWork = new Pass(this, "StartTheWork");
 wait.next(startTheWork);
 

Choice

A Choice state can take a different path through the workflow based on the values in the execution's JSON state:

 Choice choice = new Choice(this, "Did it work?");
 
 // Add conditions with .when()
 Pass successState = new Pass(this, "SuccessState");
 Pass failureState = new Pass(this, "FailureState");
 choice.when(Condition.stringEquals("$.status", "SUCCESS"), successState);
 choice.when(Condition.numberGreaterThan("$.attempts", 5), failureState);
 
 // Use .otherwise() to indicate what should be done if none of the conditions match
 Pass tryAgainState = new Pass(this, "TryAgainState");
 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:

 Choice choice = new Choice(this, "What color is it?");
 Pass handleBlueItem = new Pass(this, "HandleBlueItem");
 Pass handleRedItem = new Pass(this, "HandleRedItem");
 Pass handleOtherItemColor = new Pass(this, "HanldeOtherItemColor");
 choice.when(Condition.stringEquals("$.color", "BLUE"), handleBlueItem);
 choice.when(Condition.stringEquals("$.color", "RED"), handleRedItem);
 choice.otherwise(handleOtherItemColor);
 
 // Use .afterwards() to join all possible paths back together and continue
 Pass shipTheItem = new Pass(this, "ShipTheItem");
 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.

Available Conditions

see step function comparison operators

Parallel

A Parallel state executes one or more subworkflows in parallel. It can also be used to catch and recover from errors in subworkflows.

 Parallel parallel = new Parallel(this, "Do the work in parallel");
 
 // Add branches to be executed in parallel
 Pass shipItem = new Pass(this, "ShipItem");
 Pass sendInvoice = new Pass(this, "SendInvoice");
 Pass restock = new Pass(this, "Restock");
 parallel.branch(shipItem);
 parallel.branch(sendInvoice);
 parallel.branch(restock);
 
 // Retry the whole workflow if something goes wrong
 parallel.addRetry(RetryProps.builder().maxAttempts(1).build());
 
 // How to recover from errors
 Pass sendFailureNotification = new Pass(this, "SendFailureNotification");
 parallel.addCatch(sendFailureNotification);
 
 // What to do in case everything succeeded
 Pass closeOrder = new Pass(this, "CloseOrder");
 parallel.next(closeOrder);
 

Succeed

Reaching a Succeed state terminates the state machine execution with a successful status.

 Succeed success = new Succeed(this, "We did it!");
 

Fail

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.

 Fail success = Fail.Builder.create(this, "Fail")
         .error("WorkflowFailure")
         .cause("Something went wrong")
         .build();
 

Map

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.

 Map map = Map.Builder.create(this, "Map State")
         .maxConcurrency(1)
         .itemsPath(JsonPath.stringAt("$.inputForMap"))
         .build();
 map.iterator(new Pass(this, "Pass State"));
 

Custom 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.

 import software.amazon.awscdk.services.dynamodb.*;
 
 
 // create a table
 Table table = Table.Builder.create(this, "montable")
         .partitionKey(Attribute.builder()
                 .name("id")
                 .type(AttributeType.STRING)
                 .build())
         .build();
 
 Pass finalStatus = new 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
 Map<String, 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 = CustomState.Builder.create(this, "my custom task")
         .stateJson(stateJson)
         .build();
 
 Chain chain = Chain.start(custom).next(finalStatus);
 
 StateMachine sm = StateMachine.Builder.create(this, "StateMachine")
         .definition(chain)
         .timeout(Duration.seconds(30))
         .build();
 
 // don't forget permissions. You need to assign them
 table.grantWriteData(sm);
 

Task Chaining

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:

 Pass step1 = new Pass(this, "Step1");
 Pass step2 = new Pass(this, "Step2");
 Pass step3 = new Pass(this, "Step3");
 Pass step4 = new Pass(this, "Step4");
 Pass step5 = new Pass(this, "Step5");
 Pass step6 = new Pass(this, "Step6");
 Pass step7 = new Pass(this, "Step7");
 Pass step8 = new Pass(this, "Step8");
 Pass step9 = new Pass(this, "Step9");
 Pass step10 = new Pass(this, "Step10");
 Choice choice = new Choice(this, "Choice");
 Condition condition1 = Condition.stringEquals("$.status", "SUCCESS");
 Parallel parallel = new Parallel(this, "Parallel");
 Pass finish = new Pass(this, "Finish");
 
 Chain 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:

 Pass step1 = new Pass(this, "Step1");
 Pass step2 = new Pass(this, "Step2");
 Pass step3 = new Pass(this, "Step3");
 
 Chain definition = Chain.start(step1).next(step2).next(step3);
 

State Machine Fragments

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:

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:

 import software.amazon.awscdk.core.Construct;
 import software.amazon.awscdk.core.Stack;
 import software.amazon.awscdk.services.stepfunctions.*;
 import software.amazon.awscdk.services.stepfunctions.tasks.*;
 
 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 State startState;
     public final INextable[] endStates;
 
     public MyJob(Construct parent, String id, MyJobProps props) {
         super(parent, id);
 
         Choice choice = new Choice(this, "Choice").when(Condition.stringEquals("$.branch", "left"), new Pass(this, "Left Branch")).when(Condition.stringEquals("$.branch", "right"), new Pass(this, "Right Branch"));
 
         // ...
 
         this.startState = choice;
         this.endStates = choice.afterwards().getEndStates();
     }
 }
 
 public class MyStack extends Stack {
     public MyStack(Construct scope, String id) {
         super(scope, id);
         // Do 3 different variants of MyJob in parallel
         // Do 3 different variants of MyJob in parallel
         new Parallel(this, "All jobs").branch(new MyJob(this, "Quick", new MyJobProps().jobFlavor("quick")).prefixStates()).branch(new MyJob(this, "Medium", new MyJobProps().jobFlavor("medium")).prefixStates()).branch(new MyJob(this, "Slow", new MyJobProps().jobFlavor("slow")).prefixStates());
     }
 }
 

A few utility functions are available to parse state machine fragments.

Activity

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:

 Activity 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();
 

Activity-Level Permissions

Granting IAM permissions to an activity can be achieved by calling the grant(principal, actions) API:

 Activity activity = new Activity(this, "Activity");
 
 Role role = Role.Builder.create(this, "Role")
         .assumedBy(new ServicePrincipal("lambda.amazonaws.com"))
         .build();
 
 activity.grant(role, "states:SendTaskSuccess");
 

This will grant the IAM principal the specified actions onto the activity.

Metrics

Task object expose various metrics on the execution of that particular task. For example, to create an alarm on a particular task failing:

 Task task;
 
 Alarm.Builder.create(this, "TaskAlarm")
         .metric(task.metricFailed())
         .threshold(1)
         .evaluationPeriods(1)
         .build();
 

There are also metrics on the complete state machine:

 StateMachine stateMachine;
 
 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:

 Alarm.Builder.create(this, "ThrottledAlarm")
         .metric(StateTransitionMetric.metricThrottledEvents())
         .threshold(10)
         .evaluationPeriods(2)
         .build();
 

Error names

Step Functions identifies errors in the Amazon States Language using case-sensitive strings, known as error names. The Amazon States Language defines a set of built-in strings that name well-known errors, all beginning with the States. prefix.

Logging

Enable logging to CloudWatch by passing a logging configuration with a destination LogGroup:

 import software.amazon.awscdk.services.logs.*;
 
 
 LogGroup logGroup = new LogGroup(this, "MyLogGroup");
 
 StateMachine.Builder.create(this, "MyStateMachine")
         .definition(Chain.start(new Pass(this, "Pass")))
         .logs(LogOptions.builder()
                 .destination(logGroup)
                 .level(LogLevel.ALL)
                 .build())
         .build();
 

X-Ray tracing

Enable X-Ray tracing for StateMachine:

 StateMachine.Builder.create(this, "MyStateMachine")
         .definition(Chain.start(new Pass(this, "Pass")))
         .tracingEnabled(true)
         .build();
 

See the AWS documentation to learn more about AWS Step Functions's X-Ray support.

State Machine Permission Grants

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:

Start Execution Permission

Grant permission to start an execution of a state machine by calling the grantStartExecution() API.

 IChainable definition;
 Role role = Role.Builder.create(this, "Role")
         .assumedBy(new ServicePrincipal("lambda.amazonaws.com"))
         .build();
 StateMachine stateMachine = StateMachine.Builder.create(this, "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:

Read Permissions

Grant read access to a state machine by calling the grantRead() API.

 IChainable definition;
 Role role = Role.Builder.create(this, "Role")
         .assumedBy(new ServicePrincipal("lambda.amazonaws.com"))
         .build();
 StateMachine stateMachine = StateMachine.Builder.create(this, "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:

Task Response Permissions

Grant permission to allow task responses to a state machine by calling the grantTaskResponse() API:

 IChainable definition;
 Role role = Role.Builder.create(this, "Role")
         .assumedBy(new ServicePrincipal("lambda.amazonaws.com"))
         .build();
 StateMachine stateMachine = StateMachine.Builder.create(this, "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:

Execution-level Permissions

Grant execution-level permissions to a state machine by calling the grantExecution() API:

 IChainable definition;
 Role role = Role.Builder.create(this, "Role")
         .assumedBy(new ServicePrincipal("lambda.amazonaws.com"))
         .build();
 StateMachine stateMachine = StateMachine.Builder.create(this, "StateMachine")
         .definition(definition)
         .build();
 
 // Give role permission to get execution history of ALL executions for the state machine
 stateMachine.grantExecution(role, "states:GetExecutionHistory");
 

Custom Permissions

You can add any set of permissions to a state machine by calling the grant() API.

 IChainable definition;
 User user = new User(this, "MyUser");
 StateMachine stateMachine = StateMachine.Builder.create(this, "StateMachine")
         .definition(definition)
         .build();
 
 //give user permission to send task success to the state machine
 stateMachine.grant(user, "states:SendTaskSuccess");
 

Import

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

 App app = new App();
 Stack stack = new Stack(app, "MyStack");
 StateMachine.fromStateMachineArn(stack, "ImportedStateMachine", "arn:aws:states:us-east-1:123456789012:stateMachine:StateMachine2E01A3A5-N5TJppzoevKQ");
 
Skip navigation links