AWS Step Functions Construct Library
The aws-cdk-lib/aws-stepfunctions package contains constructs for building serverless workflows using objects. Use this in conjunction with the aws-cdk-lib/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):
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:
const startState = sfn.Pass.jsonata(this, 'StartState');
new sfn.StateMachine(this, 'StateMachine', {
definitionBody: sfn.DefinitionBody.fromChainable(startState),
});
start_state = sfn.Pass.jsonata(self, "StartState")
sfn.StateMachine(self, "StateMachine",
definition_body=sfn.DefinitionBody.from_chainable(start_state)
)
Pass startState = Pass.jsonata(this, "StartState");
StateMachine.Builder.create(this, "StateMachine")
.definitionBody(DefinitionBody.fromChainable(startState))
.build();
var startState = Pass.Jsonata(this, "StartState");
new StateMachine(this, "StateMachine", new StateMachineProps {
DefinitionBody = DefinitionBody.FromChainable(startState)
});
startState := sfn.Pass_Jsonata(this, jsii.String("StartState"))
sfn.NewStateMachine(this, jsii.String("StateMachine"), &StateMachineProps{
DefinitionBody: sfn.DefinitionBody_FromChainable(startState),
})
State machines are made up of a sequence of Steps, which represent different actions taken in sequence. Some of these steps represent control flow (like Choice, Map and Wait) while others represent calls made against other AWS services (like LambdaInvoke). The second category are called Tasks and they can all be found in the module aws-stepfunctions-tasks.
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.
Set the removalPolicy prop to RemovalPolicy.RETAIN if you want to retain the execution history when CloudFormation deletes your state machine.
Alternatively you can specify an existing step functions definition by providing a string or a file that contains the ASL JSON.
new sfn.StateMachine(this, 'StateMachineFromString', {
definitionBody: sfn.DefinitionBody.fromString('{"StartAt":"Pass","States":{"Pass":{"Type":"Pass","End":true}}}'),
});
new sfn.StateMachine(this, 'StateMachineFromFile', {
definitionBody: sfn.DefinitionBody.fromFile('./asl.json'),
});
sfn.StateMachine(self, "StateMachineFromString",
definition_body=sfn.DefinitionBody.from_string("{\"StartAt\":\"Pass\",\"States\":{\"Pass\":{\"Type\":\"Pass\",\"End\":true}}}")
)
sfn.StateMachine(self, "StateMachineFromFile",
definition_body=sfn.DefinitionBody.from_file("./asl.json")
)
StateMachine.Builder.create(this, "StateMachineFromString")
.definitionBody(DefinitionBody.fromString("{\"StartAt\":\"Pass\",\"States\":{\"Pass\":{\"Type\":\"Pass\",\"End\":true}}}"))
.build();
StateMachine.Builder.create(this, "StateMachineFromFile")
.definitionBody(DefinitionBody.fromFile("./asl.json"))
.build();
new StateMachine(this, "StateMachineFromString", new StateMachineProps {
DefinitionBody = DefinitionBody.FromString("{\"StartAt\":\"Pass\",\"States\":{\"Pass\":{\"Type\":\"Pass\",\"End\":true}}}")
});
new StateMachine(this, "StateMachineFromFile", new StateMachineProps {
DefinitionBody = DefinitionBody.FromFile("./asl.json")
});
sfn.NewStateMachine(this, jsii.String("StateMachineFromString"), &StateMachineProps{
DefinitionBody: sfn.DefinitionBody_FromString(jsii.String("{\"StartAt\":\"Pass\",\"States\":{\"Pass\":{\"Type\":\"Pass\",\"End\":true}}}")),
})
sfn.NewStateMachine(this, jsii.String("StateMachineFromFile"), &StateMachineProps{
DefinitionBody: sfn.DefinitionBody_FromFile(jsii.String("./asl.json")),
})
Query Language
Step Functions now provides the ability to select the QueryLanguage for the state machine or its states: JSONata or JSONPath.
For new state machines, we recommend using JSONata by specifying it at the state machine level. If you do not specify a QueryLanguage, the state machine will default to using JSONPath.
If a state contains a specified QueryLanguage, Step Functions will use the specified query language for that state. If the state does not specify a QueryLanguage, then it will use the query language specified in the state machine level, or JSONPath if none.
If the state machine level QueryLanguage is set to JSONPath, then any individual state-level QueryLanguage can be set to either JSONPath or JSONata to support incremental upgrades. If the state-level QueryLanguage is set to JSONata, then any individual state-level QueryLanguage can either be JSONata or not set.
const jsonata = sfn.Pass.jsonata(this, 'JSONata');
const jsonPath = sfn.Pass.jsonPath(this, 'JSONPath');
const definition = jsonata.next(jsonPath);
new sfn.StateMachine(this, 'MixedStateMachine', {
// queryLanguage: sfn.QueryLanguage.JSON_PATH, // default
definitionBody: sfn.DefinitionBody.fromChainable(definition),
});
// This throws an error. If JSONata is specified at the top level, JSONPath cannot be used in the state machine definition.
new sfn.StateMachine(this, 'JSONataOnlyStateMachine', {
queryLanguage: sfn.QueryLanguage.JSONATA,
definitionBody: sfn.DefinitionBody.fromChainable(definition),
});
jsonata = sfn.Pass.jsonata(self, "JSONata")
json_path = sfn.Pass.json_path(self, "JSONPath")
definition = jsonata.next(json_path)
sfn.StateMachine(self, "MixedStateMachine",
# queryLanguage: sfn.QueryLanguage.JSON_PATH, // default
definition_body=sfn.DefinitionBody.from_chainable(definition)
)
# This throws an error. If JSONata is specified at the top level, JSONPath cannot be used in the state machine definition.
sfn.StateMachine(self, "JSONataOnlyStateMachine",
query_language=sfn.QueryLanguage.JSONATA,
definition_body=sfn.DefinitionBody.from_chainable(definition)
)
Pass jsonata = Pass.jsonata(this, "JSONata");
Pass jsonPath = Pass.jsonPath(this, "JSONPath");
Chain definition = jsonata.next(jsonPath);
StateMachine.Builder.create(this, "MixedStateMachine")
// queryLanguage: sfn.QueryLanguage.JSON_PATH, // default
.definitionBody(DefinitionBody.fromChainable(definition))
.build();
// This throws an error. If JSONata is specified at the top level, JSONPath cannot be used in the state machine definition.
// This throws an error. If JSONata is specified at the top level, JSONPath cannot be used in the state machine definition.
StateMachine.Builder.create(this, "JSONataOnlyStateMachine")
.queryLanguage(QueryLanguage.JSONATA)
.definitionBody(DefinitionBody.fromChainable(definition))
.build();
var jsonata = Pass.Jsonata(this, "JSONata");
var jsonPath = Pass.JsonPath(this, "JSONPath");
var definition = jsonata.Next(jsonPath);
new StateMachine(this, "MixedStateMachine", new StateMachineProps {
// queryLanguage: sfn.QueryLanguage.JSON_PATH, // default
DefinitionBody = DefinitionBody.FromChainable(definition)
});
// This throws an error. If JSONata is specified at the top level, JSONPath cannot be used in the state machine definition.
// This throws an error. If JSONata is specified at the top level, JSONPath cannot be used in the state machine definition.
new StateMachine(this, "JSONataOnlyStateMachine", new StateMachineProps {
QueryLanguage = QueryLanguage.JSONATA,
DefinitionBody = DefinitionBody.FromChainable(definition)
});
jsonata := sfn.Pass_Jsonata(this, jsii.String("JSONata"))
jsonPath := sfn.Pass_JsonPath(this, jsii.String("JSONPath"))
definition := jsonata.Next(jsonPath)
sfn.NewStateMachine(this, jsii.String("MixedStateMachine"), &StateMachineProps{
// queryLanguage: sfn.QueryLanguage.JSON_PATH, // default
DefinitionBody: sfn.DefinitionBody_FromChainable(definition),
})
// This throws an error. If JSONata is specified at the top level, JSONPath cannot be used in the state machine definition.
// This throws an error. If JSONata is specified at the top level, JSONPath cannot be used in the state machine definition.
sfn.NewStateMachine(this, jsii.String("JSONataOnlyStateMachine"), &StateMachineProps{
QueryLanguage: sfn.QueryLanguage_JSONATA,
DefinitionBody: sfn.DefinitionBody_*FromChainable(definition),
})
The AWS CDK defines state constructs, and there are 3 ways to initialize them.
| Method | Query Language | Description |
|---|---|---|
State.jsonata() | JSONata | Use this method to specify a state definition using JSONata only fields. |
State.jsonPath() | JSONPath | Use this method to specify a state definition using JSONPath only fields. |
new State() | JSONata or JSONPath | This is a legacy pattern. Since fields for both JSONata and JSONPath can be used, it is recommended to use State.jsonata() or State.jsonPath() for better type safety and clarity. |
Code examples for initializing a Pass State with each pattern are shown below.
// JSONata Pattern
sfn.Pass.jsonata(this, 'JSONata Pattern', {
outputs: { foo: 'bar' },
// The outputPath does not exist in the props type
// outputPath: '$.status',
});
// JSONPath Pattern
sfn.Pass.jsonPath(this, 'JSONPath Pattern', {
// The outputs does not exist in the props type
// outputs: { foo: 'bar' },
outputPath: '$.status',
});
// Constructor (Legacy) Pattern
new sfn.Pass(this, 'Constructor Pattern', {
queryLanguage: sfn.QueryLanguage.JSONATA, // or JSON_PATH
// Both outputs and outputPath exist as prop types.
outputs: { foo: 'bar' }, // For JSONata
// or
outputPath: '$.status', // For JSONPath
});
# JSONata Pattern
sfn.Pass.jsonata(self, "JSONata Pattern",
outputs={"foo": "bar"}
)
# JSONPath Pattern
sfn.Pass.json_path(self, "JSONPath Pattern",
# The outputs does not exist in the props type
# outputs: { foo: 'bar' },
output_path="$.status"
)
# Constructor (Legacy) Pattern
sfn.Pass(self, "Constructor Pattern",
query_language=sfn.QueryLanguage.JSONATA, # or JSON_PATH
# Both outputs and outputPath exist as prop types.
outputs={"foo": "bar"}, # For JSONata
# or
output_path="$.status"
)
// JSONata Pattern
Pass.jsonata(this, "JSONata Pattern", PassJsonataProps.builder()
.outputs(Map.of("foo", "bar"))
.build());
// JSONPath Pattern
Pass.jsonPath(this, "JSONPath Pattern", PassJsonPathProps.builder()
// The outputs does not exist in the props type
// outputs: { foo: 'bar' },
.outputPath("$.status")
.build());
// Constructor (Legacy) Pattern
// Constructor (Legacy) Pattern
Pass.Builder.create(this, "Constructor Pattern")
.queryLanguage(QueryLanguage.JSONATA) // or JSON_PATH
// Both outputs and outputPath exist as prop types.
.outputs(Map.of("foo", "bar")) // For JSONata
// or
.outputPath("$.status")
.build();
// JSONata Pattern
Pass.Jsonata(this, "JSONata Pattern", new PassJsonataProps {
Outputs = new Dictionary<string, string> { { "foo", "bar" } }
});
// JSONPath Pattern
Pass.JsonPath(this, "JSONPath Pattern", new PassJsonPathProps {
// The outputs does not exist in the props type
// outputs: { foo: 'bar' },
OutputPath = "$.status"
});
// Constructor (Legacy) Pattern
// Constructor (Legacy) Pattern
new Pass(this, "Constructor Pattern", new PassProps {
QueryLanguage = QueryLanguage.JSONATA, // or JSON_PATH
// Both outputs and outputPath exist as prop types.
Outputs = new Dictionary<string, string> { { "foo", "bar" } }, // For JSONata
// or
OutputPath = "$.status"
});
// JSONata Pattern
sfn.Pass_Jsonata(this, jsii.String("JSONata Pattern"), &PassJsonataProps{
Outputs: map[string]*string{
"foo": jsii.String("bar"),
},
})
// JSONPath Pattern
sfn.Pass_JsonPath(this, jsii.String("JSONPath Pattern"), &PassJsonPathProps{
// The outputs does not exist in the props type
// outputs: { foo: 'bar' },
OutputPath: jsii.String("$.status"),
})
// Constructor (Legacy) Pattern
// Constructor (Legacy) Pattern
sfn.NewPass(this, jsii.String("Constructor Pattern"), &PassProps{
QueryLanguage: sfn.QueryLanguage_JSONATA,
// or JSON_PATH
// Both outputs and outputPath exist as prop types.
Outputs: map[string]*string{
"foo": jsii.String("bar"),
},
// For JSONata
// or
OutputPath: jsii.String("$.status"),
})
Learn more in the blog post Simplifying developer experience with variables and JSONata in AWS Step Functions.
JSONata example
The following example defines a state machine in JSONata that calls a fictional service API to update issue labels.
import * as events from 'aws-cdk-lib/aws-events';
declare const connection: events.Connection;
const getIssue = tasks.HttpInvoke.jsonata(this, 'Get Issue', {
connection,
apiRoot: "{% 'https://' & $states.input.hostname %}",
apiEndpoint: sfn.TaskInput.fromText("{% 'issues/' & $states.input.issue.id %}"),
method: sfn.TaskInput.fromText('GET'),
// Parse the API call result to object and set to the variables
assign: {
hostname: '{% $states.input.hostname %}',
issue: '{% $parse($states.result.ResponseBody) %}',
},
});
const updateLabels = tasks.HttpInvoke.jsonata(this, 'Update Issue Labels', {
connection,
apiRoot: "{% 'https://' & $states.input.hostname %}",
apiEndpoint: sfn.TaskInput.fromText("{% 'issues/' & $states.input.issue.id & 'labels' %}"),
method: sfn.TaskInput.fromText('POST'),
body: sfn.TaskInput.fromObject({
labels: '{% [$type, $component] %}',
}),
});
const notMatchTitleTemplate = sfn.Pass.jsonata(this, 'Not Match Title Template');
const definition = getIssue
.next(sfn.Choice.jsonata(this, 'Match Title Template?')
// Look at the "title" field of issue in variables using Regex
.when(sfn.Condition.jsonata('{% $contains($issue.title, /(feat)|(fix)|(chore)\(\w*\):.*/) %}'), updateLabels, {
assign: {
type: '{% $match($states.input.title, /(\w*)\((.*)\)/).groups[0] %}',
component: '{% $match($states.input.title, /(\w*)\((.*)\)/).groups[1] %}',
}
})
.otherwise(notMatchTitleTemplate));
new sfn.StateMachine(this, 'StateMachine', {
definitionBody: sfn.DefinitionBody.fromChainable(definition),
timeout: Duration.minutes(5),
comment: 'automate issue labeling state machine',
});
import aws_cdk.aws_events as events
# connection: events.Connection
get_issue = tasks.HttpInvoke.jsonata(self, "Get Issue",
connection=connection,
api_root="{% 'https://' & $states.input.hostname %}",
api_endpoint=sfn.TaskInput.from_text("{% 'issues/' & $states.input.issue.id %}"),
method=sfn.TaskInput.from_text("GET"),
# Parse the API call result to object and set to the variables
assign={
"hostname": "{% $states.input.hostname %}",
"issue": "{% $parse($states.result.ResponseBody) %}"
}
)
update_labels = tasks.HttpInvoke.jsonata(self, "Update Issue Labels",
connection=connection,
api_root="{% 'https://' & $states.input.hostname %}",
api_endpoint=sfn.TaskInput.from_text("{% 'issues/' & $states.input.issue.id & 'labels' %}"),
method=sfn.TaskInput.from_text("POST"),
body=sfn.TaskInput.from_object({
"labels": "{% [$type, $component] %}"
})
)
not_match_title_template = sfn.Pass.jsonata(self, "Not Match Title Template")
definition = get_issue.next(sfn.Choice.jsonata(self, "Match Title Template?").when(sfn.Condition.jsonata("{% $contains($issue.title, /(feat)|(fix)|(chore)(w*):.*/) %}"), update_labels,
assign={
"type": "{% $match($states.input.title, /(w*)((.*))/).groups[0] %}",
"component": "{% $match($states.input.title, /(w*)((.*))/).groups[1] %}"
}
).otherwise(not_match_title_template))
sfn.StateMachine(self, "StateMachine",
definition_body=sfn.DefinitionBody.from_chainable(definition),
timeout=Duration.minutes(5),
comment="automate issue labeling state machine"
)
import software.amazon.awscdk.services.events.*;
Connection connection;
HttpInvoke getIssue = HttpInvoke.jsonata(this, "Get Issue", HttpInvokeJsonataProps.builder()
.connection(connection)
.apiRoot("{% 'https://' & $states.input.hostname %}")
.apiEndpoint(TaskInput.fromText("{% 'issues/' & $states.input.issue.id %}"))
.method(TaskInput.fromText("GET"))
// Parse the API call result to object and set to the variables
.assign(Map.of(
"hostname", "{% $states.input.hostname %}",
"issue", "{% $parse($states.result.ResponseBody) %}"))
.build());
HttpInvoke updateLabels = HttpInvoke.jsonata(this, "Update Issue Labels", HttpInvokeJsonataProps.builder()
.connection(connection)
.apiRoot("{% 'https://' & $states.input.hostname %}")
.apiEndpoint(TaskInput.fromText("{% 'issues/' & $states.input.issue.id & 'labels' %}"))
.method(TaskInput.fromText("POST"))
.body(TaskInput.fromObject(Map.of(
"labels", "{% [$type, $component] %}")))
.build());
Pass notMatchTitleTemplate = Pass.jsonata(this, "Not Match Title Template");
Chain definition = getIssue.next(Choice.jsonata(this, "Match Title Template?").when(Condition.jsonata("{% $contains($issue.title, /(feat)|(fix)|(chore)(w*):.*/) %}"), updateLabels, ChoiceTransitionOptions.builder()
.assign(Map.of(
"type", "{% $match($states.input.title, /(w*)((.*))/).groups[0] %}",
"component", "{% $match($states.input.title, /(w*)((.*))/).groups[1] %}"))
.build()).otherwise(notMatchTitleTemplate));
StateMachine.Builder.create(this, "StateMachine")
.definitionBody(DefinitionBody.fromChainable(definition))
.timeout(Duration.minutes(5))
.comment("automate issue labeling state machine")
.build();
using Amazon.CDK.AWS.Events;
Connection connection;
var getIssue = HttpInvoke.Jsonata(this, "Get Issue", new HttpInvokeJsonataProps {
Connection = connection,
ApiRoot = "{% 'https://' & $states.input.hostname %}",
ApiEndpoint = TaskInput.FromText("{% 'issues/' & $states.input.issue.id %}"),
Method = TaskInput.FromText("GET"),
// Parse the API call result to object and set to the variables
Assign = new Dictionary<string, object> {
{ "hostname", "{% $states.input.hostname %}" },
{ "issue", "{% $parse($states.result.ResponseBody) %}" }
}
});
var updateLabels = HttpInvoke.Jsonata(this, "Update Issue Labels", new HttpInvokeJsonataProps {
Connection = connection,
ApiRoot = "{% 'https://' & $states.input.hostname %}",
ApiEndpoint = TaskInput.FromText("{% 'issues/' & $states.input.issue.id & 'labels' %}"),
Method = TaskInput.FromText("POST"),
Body = TaskInput.FromObject(new Dictionary<string, object> {
{ "labels", "{% [$type, $component] %}" }
})
});
var notMatchTitleTemplate = Pass.Jsonata(this, "Not Match Title Template");
var definition = getIssue.Next(Choice.Jsonata(this, "Match Title Template?").When(Condition.Jsonata("{% $contains($issue.title, /(feat)|(fix)|(chore)(w*):.*/) %}"), updateLabels, new ChoiceTransitionOptions {
Assign = new Dictionary<string, object> {
{ "type", "{% $match($states.input.title, /(w*)((.*))/).groups[0] %}" },
{ "component", "{% $match($states.input.title, /(w*)((.*))/).groups[1] %}" }
}
}).Otherwise(notMatchTitleTemplate));
new StateMachine(this, "StateMachine", new StateMachineProps {
DefinitionBody = DefinitionBody.FromChainable(definition),
Timeout = Duration.Minutes(5),
Comment = "automate issue labeling state machine"
});
import events "github.com/aws/aws-cdk-go/awscdk"
var connection Connection
getIssue := tasks.HttpInvoke_Jsonata(this, jsii.String("Get Issue"), &HttpInvokeJsonataProps{
Connection: Connection,
ApiRoot: jsii.String("{% 'https://' & $states.input.hostname %}"),
ApiEndpoint: sfn.TaskInput_FromText(jsii.String("{% 'issues/' & $states.input.issue.id %}")),
Method: sfn.TaskInput_*FromText(jsii.String("GET")),
// Parse the API call result to object and set to the variables
Assign: map[string]interface{}{
"hostname": jsii.String("{% $states.input.hostname %}"),
"issue": jsii.String("{% $parse($states.result.ResponseBody) %}"),
},
})
updateLabels := tasks.HttpInvoke_Jsonata(this, jsii.String("Update Issue Labels"), &HttpInvokeJsonataProps{
Connection: Connection,
ApiRoot: jsii.String("{% 'https://' & $states.input.hostname %}"),
ApiEndpoint: sfn.TaskInput_*FromText(jsii.String("{% 'issues/' & $states.input.issue.id & 'labels' %}")),
Method: sfn.TaskInput_*FromText(jsii.String("POST")),
Body: sfn.TaskInput_FromObject(map[string]interface{}{
"labels": jsii.String("{% [$type, $component] %}"),
}),
})
notMatchTitleTemplate := sfn.Pass_Jsonata(this, jsii.String("Not Match Title Template"))
definition := getIssue.Next(sfn.Choice_Jsonata(this, jsii.String("Match Title Template?")).When(sfn.Condition_Jsonata(jsii.String("{% $contains($issue.title, /(feat)|(fix)|(chore)(w*):.*/) %}")), updateLabels, &ChoiceTransitionOptions{
Assign: map[string]interface{}{
"type": jsii.String("{% $match($states.input.title, /(w*)((.*))/).groups[0] %}"),
"component": jsii.String("{% $match($states.input.title, /(w*)((.*))/).groups[1] %}"),
},
}).Otherwise(notMatchTitleTemplate))
sfn.NewStateMachine(this, jsii.String("StateMachine"), &StateMachineProps{
DefinitionBody: sfn.DefinitionBody_FromChainable(definition),
Timeout: awscdk.Duration_Minutes(jsii.Number(5)),
Comment: jsii.String("automate issue labeling state machine"),
})
JSONPath (Legacy pattern) example
Defining a workflow looks like this (for the Step Functions Job Poller example):
import * as lambda from 'aws-cdk-lib/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 `guid`
outputPath: '$.guid',
});
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: '$.status',
});
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', {
definitionBody: sfn.DefinitionBody.fromChainable(definition),
timeout: Duration.minutes(5),
comment: 'a super cool state machine',
});
import aws_cdk.aws_lambda as lambda_
# submit_lambda: lambda.Function
# get_status_lambda: lambda.Function
submit_job = tasks.LambdaInvoke(self, "Submit Job",
lambda_function=submit_lambda,
# Lambda's result is in the attribute `guid`
output_path="$.guid"
)
wait_x = sfn.Wait(self, "Wait X Seconds",
time=sfn.WaitTime.seconds_path("$.waitSeconds")
)
get_status = tasks.LambdaInvoke(self, "Get Job Status",
lambda_function=get_status_lambda,
# Pass just the field named "guid" into the Lambda, put the
# Lambda's result in a field called "status" in the response
input_path="$.guid",
output_path="$.status"
)
job_failed = sfn.Fail(self, "Job Failed",
cause="AWS Batch Job Failed",
error="DescribeJob returned FAILED"
)
final_status = tasks.LambdaInvoke(self, "Get Final Job Status",
lambda_function=get_status_lambda,
# Use "guid" field as input
input_path="$.guid",
output_path="$.Payload"
)
definition = submit_job.next(wait_x).next(get_status).next(sfn.Choice(self, "Job Complete?").when(sfn.Condition.string_equals("$.status", "FAILED"), job_failed).when(sfn.Condition.string_equals("$.status", "SUCCEEDED"), final_status).otherwise(wait_x))
sfn.StateMachine(self, "StateMachine",
definition_body=sfn.DefinitionBody.from_chainable(definition),
timeout=Duration.minutes(5),
comment="a super cool state machine"
)
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 `guid`
.outputPath("$.guid")
.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("$.status")
.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")
.definitionBody(DefinitionBody.fromChainable(definition))
.timeout(Duration.minutes(5))
.comment("a super cool state machine")
.build();
using Amazon.CDK.AWS.Lambda;
Function submitLambda;
Function getStatusLambda;
var submitJob = new LambdaInvoke(this, "Submit Job", new LambdaInvokeProps {
LambdaFunction = submitLambda,
// Lambda's result is in the attribute `guid`
OutputPath = "$.guid"
});
var waitX = new Wait(this, "Wait X Seconds", new WaitProps {
Time = WaitTime.SecondsPath("$.waitSeconds")
});
var 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 = "$.status"
});
var jobFailed = new Fail(this, "Job Failed", new FailProps {
Cause = "AWS Batch Job Failed",
Error = "DescribeJob returned FAILED"
});
var finalStatus = new LambdaInvoke(this, "Get Final Job Status", new LambdaInvokeProps {
LambdaFunction = getStatusLambda,
// Use "guid" field as input
InputPath = "$.guid",
OutputPath = "$.Payload"
});
var 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));
new StateMachine(this, "StateMachine", new StateMachineProps {
DefinitionBody = DefinitionBody.FromChainable(definition),
Timeout = Duration.Minutes(5),
Comment = "a super cool state machine"
});
import lambda "github.com/aws/aws-cdk-go/awscdk"
var submitLambda Function
var getStatusLambda Function
submitJob := tasks.NewLambdaInvoke(this, jsii.String("Submit Job"), &LambdaInvokeProps{
LambdaFunction: submitLambda,
// Lambda's result is in the attribute `guid`
OutputPath: jsii.String("$.guid"),
})
waitX := sfn.NewWait(this, jsii.String("Wait X Seconds"), &WaitProps{
Time: sfn.WaitTime_SecondsPath(jsii.String("$.waitSeconds")),
})
getStatus := tasks.NewLambdaInvoke(this, jsii.String("Get Job Status"), &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: jsii.String("$.guid"),
OutputPath: jsii.String("$.status"),
})
jobFailed := sfn.NewFail(this, jsii.String("Job Failed"), &FailProps{
Cause: jsii.String("AWS Batch Job Failed"),
Error: jsii.String("DescribeJob returned FAILED"),
})
finalStatus := tasks.NewLambdaInvoke(this, jsii.String("Get Final Job Status"), &LambdaInvokeProps{
LambdaFunction: getStatusLambda,
// Use "guid" field as input
InputPath: jsii.String("$.guid"),
OutputPath: jsii.String("$.Payload"),
})
definition := submitJob.Next(waitX).Next(getStatus).Next(sfn.NewChoice(this, jsii.String("Job Complete?")).When(sfn.Condition_StringEquals(jsii.String("$.status"), jsii.String("FAILED")), jobFailed).When(sfn.Condition_StringEquals(jsii.String("$.status"), jsii.String("SUCCEEDED")), finalStatus).Otherwise(waitX))
sfn.NewStateMachine(this, jsii.String("StateMachine"), &StateMachineProps{
DefinitionBody: sfn.DefinitionBody_FromChainable(definition),
Timeout: awscdk.Duration_Minutes(jsii.Number(5)),
Comment: jsii.String("a super cool state machine"),
})
You can find more sample snippets and learn more about the service integrations in the aws-cdk-lib/aws-stepfunctions-tasks package.
State Machine Data
With variables and state output, you can pass data between the steps of your workflow.
Using workflow variables, you can store data in a step and retrieve that data in future steps. For example, you could store an API response that contains data you might need later. Conversely, state output can only be used as input to the very next step.
Variable
With workflow variables, you can store data to reference later. For example, Step 1 might store the result from an API request so a part of that request can be re-used later in Step 5.
In the following scenario, the state machine fetches data from an API once. In Step 1, the workflow stores the returned API data (up to 256 KiB per state) in a variable ‘x’ to use in later steps.
Without variables, you would need to pass the data through output from Step 1 to Step 2 to Step 3 to Step 4 to use it in Step 5. What if those intermediate steps do not need the data? Passing data from state to state through outputs and input would be unnecessary effort.
With variables, you can store data and use it in any future step. You can also modify, rearrange, or add steps without disrupting the flow of your data. Given the flexibility of variables, you might only need to use output to return data from Parallel and Map sub-workflows, and at the end of your state machine execution.
(Start)
↓
[Step 1]→[Return from API]
↓ ↓
[Step 2] [Assign data to $x]
↓ │
[Step 3] │
↓ │
[Step 4] │
↓ │
[Step 5]←────────┘
↓ Use variable $x
(End)
Use assign to express the above example in AWS CDK. You can use both JSONata and JSONPath to assign.
import * as lambda from 'aws-cdk-lib/aws-lambda';
declare const callApiFunc: lambda.Function;
declare const useVariableFunc: lambda.Function;
const step1 = tasks.LambdaInvoke.jsonata(this, 'Step 1', {
lambdaFunction: callApiFunc,
assign: {
x: '{% $states.result.Payload.x %}', // JSONata
// x: sfn.JsonPath.stringAt('$.Payload.x'), // When use JSONPath
},
});
const step2 = sfn.Pass.jsonata(this, 'Step 2');
const step3 = sfn.Pass.jsonata(this, 'Step 3');
const step4 = sfn.Pass.jsonata(this, 'Step 4');
const step5 = tasks.LambdaInvoke.jsonata(this, 'Step 5', {
lambdaFunction: useVariableFunc,
payload: sfn.TaskInput.fromObject({
x: '{% $x %}', // JSONata
// x: sfn.JsonPath.stringAt('$x'), // When use JSONPath
}),
});
import aws_cdk.aws_lambda as lambda_
# call_api_func: lambda.Function
# use_variable_func: lambda.Function
step1 = tasks.LambdaInvoke.jsonata(self, "Step 1",
lambda_function=call_api_func,
assign={
"x": "{% $states.result.Payload.x %}"
}
)
step2 = sfn.Pass.jsonata(self, "Step 2")
step3 = sfn.Pass.jsonata(self, "Step 3")
step4 = sfn.Pass.jsonata(self, "Step 4")
step5 = tasks.LambdaInvoke.jsonata(self, "Step 5",
lambda_function=use_variable_func,
payload=sfn.TaskInput.from_object({
"x": "{% $x %}"
})
)
import software.amazon.awscdk.services.lambda.*;
Function callApiFunc;
Function useVariableFunc;
LambdaInvoke step1 = LambdaInvoke.jsonata(this, "Step 1", LambdaInvokeJsonataProps.builder()
.lambdaFunction(callApiFunc)
.assign(Map.of(
"x", "{% $states.result.Payload.x %}"))
.build());
Pass step2 = Pass.jsonata(this, "Step 2");
Pass step3 = Pass.jsonata(this, "Step 3");
Pass step4 = Pass.jsonata(this, "Step 4");
LambdaInvoke step5 = LambdaInvoke.jsonata(this, "Step 5", LambdaInvokeJsonataProps.builder()
.lambdaFunction(useVariableFunc)
.payload(TaskInput.fromObject(Map.of(
"x", "{% $x %}")))
.build());
using Amazon.CDK.AWS.Lambda;
Function callApiFunc;
Function useVariableFunc;
var step1 = LambdaInvoke.Jsonata(this, "Step 1", new LambdaInvokeJsonataProps {
LambdaFunction = callApiFunc,
Assign = new Dictionary<string, object> {
{ "x", "{% $states.result.Payload.x %}" }
}
});
var step2 = Pass.Jsonata(this, "Step 2");
var step3 = Pass.Jsonata(this, "Step 3");
var step4 = Pass.Jsonata(this, "Step 4");
var step5 = LambdaInvoke.Jsonata(this, "Step 5", new LambdaInvokeJsonataProps {
LambdaFunction = useVariableFunc,
Payload = TaskInput.FromObject(new Dictionary<string, object> {
{ "x", "{% $x %}" }
})
});
import lambda "github.com/aws/aws-cdk-go/awscdk"
var callApiFunc Function
var useVariableFunc Function
step1 := tasks.LambdaInvoke_Jsonata(this, jsii.String("Step 1"), &LambdaInvokeJsonataProps{
LambdaFunction: callApiFunc,
Assign: map[string]interface{}{
"x": jsii.String("{% $states.result.Payload.x %}"),
},
})
step2 := sfn.Pass_Jsonata(this, jsii.String("Step 2"))
step3 := sfn.Pass_Jsonata(this, jsii.String("Step 3"))
step4 := sfn.Pass_Jsonata(this, jsii.String("Step 4"))
step5 := tasks.LambdaInvoke_Jsonata(this, jsii.String("Step 5"), &LambdaInvokeJsonataProps{
LambdaFunction: useVariableFunc,
Payload: sfn.TaskInput_FromObject(map[string]interface{}{
"x": jsii.String("{% $x %}"),
}),
})
For more details, see the official documentation
State Output
An Execution represents each time the State Machine is run. Every Execution has State Machine Data: a JSON document containing keys and values that is fed into the state machine, gets modified by individual steps as the state machine progresses, and finally is produced as output.
By default, the entire Data object is passed into every state, and the return data of the step becomes new the new Data object. You can change this behavior, but the way you specify it differs depending on the query language you use.
JSONata
To change the default behavior of using a JSONata, supplying values for outputs. When a string in the value of an ASL field, a JSON object field, or a JSON array element is surrounded by {% %} characters, that string will be evaluated as JSONata . Note, the string must start with {% with no leading spaces, and must end with %} with no trailing spaces. Improperly opening or closing the expression will result in a validation error.
The following example uses JSONata expressions for outputs and time.
sfn.Wait.jsonata(this, 'Wait', {
time: sfn.WaitTime.timestamp('{% $timestamp %}'),
outputs: {
stringArgument: 'inital-task',
numberArgument: 123,
booleanArgument: true,
arrayArgument: [1, '{% $number %}', 3],
intrinsicFunctionsArgument: "{% $join($each($obj, function($v) { $v }), ', ') %}",
},
});
sfn.Wait.jsonata(self, "Wait",
time=sfn.WaitTime.timestamp("{% $timestamp %}"),
outputs={
"string_argument": "inital-task",
"number_argument": 123,
"boolean_argument": True,
"array_argument": [1, "{% $number %}", 3],
"intrinsic_functions_argument": "{% $join($each($obj, function($v) { $v }), ', ') %}"
}
)
Wait.jsonata(this, "Wait", WaitJsonataProps.builder()
.time(WaitTime.timestamp("{% $timestamp %}"))
.outputs(Map.of(
"stringArgument", "inital-task",
"numberArgument", 123,
"booleanArgument", true,
"arrayArgument", List.of(1, "{% $number %}", 3),
"intrinsicFunctionsArgument", "{% $join($each($obj, function($v) { $v }), ', ') %}"))
.build());
Wait.Jsonata(this, "Wait", new WaitJsonataProps {
Time = WaitTime.Timestamp("{% $timestamp %}"),
Outputs = new Dictionary<string, object> {
{ "stringArgument", "inital-task" },
{ "numberArgument", 123 },
{ "booleanArgument", true },
{ "arrayArgument", new [] { 1, "{% $number %}", 3 } },
{ "intrinsicFunctionsArgument", "{% $join($each($obj, function($v) { $v }), ', ') %}" }
}
});
sfn.Wait_Jsonata(this, jsii.String("Wait"), &WaitJsonataProps{
Time: sfn.WaitTime_Timestamp(jsii.String("{% $timestamp %}")),
Outputs: map[string]interface{}{
"stringArgument": jsii.String("inital-task"),
"numberArgument": jsii.Number(123),
"booleanArgument": jsii.Boolean(true),
"arrayArgument": []interface{}{
jsii.Number(1),
jsii.String("{% $number %}"),
jsii.Number(3),
},
"intrinsicFunctionsArgument": jsii.String("{% $join($each($obj, function($v) { $v }), ', ') %}"),
},
})
For a brief introduction and complete JSONata reference, see JSONata.org documentation.
Reserved variable : $states
Step Functions defines a single reserved variable called $states. In JSONata states, the following structures are assigned to $states for use in JSONata expressions:
// Reserved $states variable in JSONata states
const $states = {
"input": // Original input to the state
"result": // API or sub-workflow's result (if successful)
"errorOutput":// Error Output in a Catch
"context": // Context object
}
The structure is as follows when expressed as a type.
interface JsonataStates {
input: any;
result?: any;
errorOutput?: {
Error: string;
Cause: string;
};
context: {
Execution: {
Id: string;
Input: any;
Name: string;
RoleArn: string;
StartTime: string; // Format: ISO 8601;
RedriveCount: number;
RedriveTime: string; // Format: ISO 8601
};
State: {
EnteredTime: string; // Format: ISO 8601;
Name: string;
RetryCount: number;
};
StateMachine: {
Id: string;
Name: string;
};
Task: {
Token: string;
};
};
}
public class JsonataStates {
private Object input;
public Object getInput() {
return this.input;
}
public JsonataStates input(Object input) {
this.input = input;
return this;
}
private Object result;
public Object getResult() {
return this.result;
}
public JsonataStates result(Object result) {
this.result = result;
return this;
}
private Map<String, Object> errorOutput;
public Map<String, Object> getErrorOutput() {
return this.errorOutput;
}
public JsonataStates errorOutput(Map<String, Object> errorOutput) {
this.errorOutput = errorOutput;
return this;
}
private Map<String, Object> context;
public Map<String, Object> getContext() {
return this.context;
}
public JsonataStates context(Map<String, Object> context) {
this.context = context;
return this;
}
}
class JsonataStates
{
public object Input { get; set; }
public object? Result { get; set; }
public IDictionary<string, object>? ErrorOutput { get; set; }
public IDictionary<string, object> Context { get; set; }
}
type jsonataStates struct {
input interface{}
result interface{}
errorOutput map[string]interface{}
context map[string]interface{}
}
You can access reserved variables as follows:
sfn.Pass.jsonata(this, 'Pass', {
outputs: {
foo: '{% $states.input.foo %}',
},
});
sfn.Pass.jsonata(self, "Pass",
outputs={
"foo": "{% $states.input.foo %}"
}
)
Pass.jsonata(this, "Pass", PassJsonataProps.builder()
.outputs(Map.of(
"foo", "{% $states.input.foo %}"))
.build());
Pass.Jsonata(this, "Pass", new PassJsonataProps {
Outputs = new Dictionary<string, string> {
{ "foo", "{% $states.input.foo %}" }
}
});
sfn.Pass_Jsonata(this, jsii.String("Pass"), &PassJsonataProps{
Outputs: map[string]*string{
"foo": jsii.String("{% $states.input.foo %}"),
},
})
JSONPath
To change the default behavior of using a JSON path, supplying values for inputPath, resultSelector, resultPath, and outputPath.
Manipulating state machine data using inputPath, resultSelector, resultPath and outputPath
These properties impact how each individual step interacts with the state machine data:
stateName: the name of the state in the state machine definition. If not supplied, defaults to the construct id.inputPath: the part of the data object that gets passed to the step (itemsPathforMapstates)resultSelector: the part of the step result that should be added to the state machine dataresultPath: where in the state machine data the step result should be insertedoutputPath: what part of the state machine data should be retainederrorPath: the part of the data object that gets returned as the step errorcausePath: the part of the data object that gets returned as the step cause
Their values should be a string indicating a JSON path into the State Machine Data object (like "$.MyKey"). If absent, the values are treated as if they were "$", which means the entire object.
The following pseudocode shows how AWS Step Functions uses these parameters when executing a step:
// Schematically show how Step Functions evaluates functions.
// [] represents indexing into an object by a using JSON path.
input = state[inputPath]
result = invoke_step(select_parameters(input))
state[resultPath] = result[resultSelector]
state = state[outputPath]
Instead of a JSON path string, each of these paths can also have the special value JsonPath.DISCARD, which causes the corresponding indexing expression to return an empty object ({}). Effectively, that means there will be an empty input object, an empty result object, no effect on the state, or an empty state, respectively.
Some steps (mostly Tasks) have Parameters, which are selected differently. See the next section.
See the official documentation on input and output processing in Step Functions.
Passing Parameters to Tasks
Tasks take parameters, whose values can be taken from the State Machine Data object. For example, your workflow may want to start a CodeBuild with an environment variable that is taken from the State Machine data, or pass part of the State Machine Data into an AWS Lambda Function.
In the original JSON-based states language used by AWS Step Functions, you would add .$ to the end of a key to indicate that a value needs to be interpreted as a JSON path. In the CDK API you do not change the names of any keys. Instead, you pass special values. There are 3 types of task inputs to consider:
- Tasks that accept a "payload" type of input (like AWS Lambda invocations, or posting messages to SNS topics or SQS queues), will take an object of type
TaskInput, likeTaskInput.fromObject()orTaskInput.fromJsonPathAt(). - When tasks expect individual string or number values to customize their behavior, you can also pass a value constructed by
JsonPath.stringAt()orJsonPath.numberAt(). - When tasks expect strongly-typed resources and you want to vary the resource that is referenced based on a name from the State Machine Data, reference the resource as if it was external (using
JsonPath.stringAt()). For example, for a Lambda function:Function.fromFunctionName(this, 'ReferencedFunction', JsonPath.stringAt('$.MyFunctionName')).
For example, to pass the value that's in the data key of OrderId to a Lambda function as you invoke it, use JsonPath.stringAt('$.OrderId'), like so:
import * as lambda from 'aws-cdk-lib/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'),
}),
});
import aws_cdk.aws_lambda as lambda_
# order_fn: lambda.Function
submit_job = tasks.LambdaInvoke(self, "InvokeOrderProcessor",
lambda_function=order_fn,
payload=sfn.TaskInput.from_object({
"OrderId": sfn.JsonPath.string_at("$.OrderId")
})
)
import software.amazon.awscdk.services.lambda.*;
Function orderFn;
LambdaInvoke submitJob = LambdaInvoke.Builder.create(this, "InvokeOrderProcessor")
.lambdaFunction(orderFn)
.payload(TaskInput.fromObject(Map.of(
"OrderId", JsonPath.stringAt("$.OrderId"))))
.build();
using Amazon.CDK.AWS.Lambda;
Function orderFn;
var submitJob = new LambdaInvoke(this, "InvokeOrderProcessor", new LambdaInvokeProps {
LambdaFunction = orderFn,
Payload = TaskInput.FromObject(new Dictionary<string, object> {
{ "OrderId", JsonPath.StringAt("$.OrderId") }
})
});
import lambda "github.com/aws/aws-cdk-go/awscdk"
var orderFn Function
submitJob := tasks.NewLambdaInvoke(this, jsii.String("InvokeOrderProcessor"), &LambdaInvokeProps{
LambdaFunction: orderFn,
Payload: sfn.TaskInput_FromObject(map[string]interface{}{
"OrderId": sfn.JsonPath_stringAt(jsii.String("$.OrderId")),
}),
})
The following methods are available:
| Method | Purpose |
|---|---|
JsonPath.stringAt('$.Field') | reference a field, return the type as a string. |
JsonPath.listAt('$.Field') | reference a field, return the type as a list of strings. |
JsonPath.numberAt('$.Field') | reference a field, return the type as a number. Use this for functions that expect a number argument. |
JsonPath.objectAt('$.Field') | reference a field, return the type as an IResolvable. Use this for functions that expect an object argument. |
JsonPath.entirePayload | reference the entire data object (equivalent to a path of $). |
JsonPath.taskToken | reference the Task Token, used for integration patterns that need to run for a long time. |
JsonPath.executionId | reference the Execution Id field of the context object. |
JsonPath.executionInput | reference the Execution Input object of the context object. |
JsonPath.executionName | reference the Execution Name field of the context object. |
JsonPath.executionRoleArn | reference the Execution RoleArn field of the context object. |
JsonPath.executionStartTime | reference the Execution StartTime field of the context object. |
JsonPath.stateEnteredTime | reference the State EnteredTime field of the context object. |
JsonPath.stateName | reference the State Name field of the context object. |
JsonPath.stateRetryCount | reference the State RetryCount field of the context object. |
JsonPath.stateMachineId | reference the StateMachine Id field of the context object. |
JsonPath.stateMachineName | reference the StateMachine Name field of the context object. |
You can also call intrinsic functions using the methods on JsonPath:
| Method | Purpose |
|---|---|
JsonPath.array(JsonPath.stringAt('$.Field'), ...) | make an array from other elements. |
JsonPath.arrayPartition(JsonPath.listAt('$.inputArray'), 4) | partition an array. |
JsonPath.arrayContains(JsonPath.listAt('$.inputArray'), 5) | determine if a specific value is present in an array. |
JsonPath.arrayRange(1, 9, 2) | create a new array containing a specific range of elements. |
JsonPath.arrayGetItem(JsonPath.listAt('$.inputArray'), 5) | get a specified index's value in an array. |
JsonPath.arrayLength(JsonPath.listAt('$.inputArray')) | get the length of an array. |
JsonPath.arrayUnique(JsonPath.listAt('$.inputArray')) | remove duplicate values from an array. |
JsonPath.base64Encode(JsonPath.stringAt('$.input')) | encode data based on MIME Base64 encoding scheme. |
JsonPath.base64Decode(JsonPath.stringAt('$.base64')) | decode data based on MIME Base64 decoding scheme. |
JsonPath.hash(JsonPath.objectAt('$.Data'), JsonPath.stringAt('$.Algorithm')) | calculate the hash value of a given input. |
JsonPath.jsonMerge(JsonPath.objectAt('$.Obj1'), JsonPath.objectAt('$.Obj2')) | merge two JSON objects into a single object. |
JsonPath.stringToJson(JsonPath.stringAt('$.ObjStr')) | parse a JSON string to an object |
JsonPath.jsonToString(JsonPath.objectAt('$.Obj')) | stringify an object to a JSON string |
JsonPath.mathRandom(1, 999) | return a random number. |
JsonPath.mathAdd(JsonPath.numberAt('$.value1'), JsonPath.numberAt('$.step')) | return the sum of two numbers. |
JsonPath.stringSplit(JsonPath.stringAt('$.inputString'), JsonPath.stringAt('$.splitter')) | split a string into an array of values. |
JsonPath.uuid() | return a version 4 universally unique identifier (v4 UUID). |
JsonPath.format('The value is {}.', JsonPath.stringAt('$.Value')) | insert elements into a format string. |
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. Do not use the Task class directly.
Instead, use one of the classes in the aws-cdk-lib/aws-stepfunctions-tasks module, which provide a much more ergonomic way to integrate with various AWS services.
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" } }
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);
# Makes the current JSON state { ..., "subObject": { "hello": "world" } }
pass = sfn.Pass(self, "Add Hello World",
result=sfn.Result.from_object({"hello": "world"}),
result_path="$.subObject"
)
# Set the next state
next_state = sfn.Pass(self, "NextState")
pass.next(next_state)
// 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);
// Makes the current JSON state { ..., "subObject": { "hello": "world" } }
var pass = new Pass(this, "Add Hello World", new PassProps {
Result = Result.FromObject(new Dictionary<string, object> { { "hello", "world" } }),
ResultPath = "$.subObject"
});
// Set the next state
var nextState = new Pass(this, "NextState");
pass.Next(nextState);
// Makes the current JSON state { ..., "subObject": { "hello": "world" } }
pass := sfn.NewPass(this, jsii.String("Add Hello World"), &PassProps{
Result: sfn.Result_FromObject(map[string]interface{}{
"hello": jsii.String("world"),
}),
ResultPath: jsii.String("$.subObject"),
})
// Set the next state
nextState := sfn.NewPass(this, jsii.String("NextState"))
pass.Next(nextState)
When using JSONata, you can use only outputs.
const pass = new sfn.Pass(this, 'Add Hello World', {
outputs: {
subObject: { hello: 'world' }
},
});
pass = sfn.Pass(self, "Add Hello World",
outputs={
"sub_object": {"hello": "world"}
}
)
Pass pass = Pass.Builder.create(this, "Add Hello World")
.outputs(Map.of(
"subObject", Map.of("hello", "world")))
.build();
var pass = new Pass(this, "Add Hello World", new PassProps {
Outputs = new Dictionary<string, IDictionary<string, string>> {
{ "subObject", new Struct { Hello = "world" } }
}
});
pass := sfn.NewPass(this, jsii.String("Add Hello World"), &PassProps{
Outputs: map[string]map[string]*string{
"subObject": map[string]*string{
"hello": jsii.String("world"),
},
},
})
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.
const pass = new sfn.Pass(this, 'Filter input and inject data', {
stateName: 'my-pass-state', // the custom state name for the Pass state, defaults to 'Filter input and inject data' as the state name
parameters: { // input to the pass state
input: sfn.JsonPath.stringAt('$.input.greeting'),
otherData: 'some-extra-stuff',
},
});
pass = sfn.Pass(self, "Filter input and inject data",
state_name="my-pass-state", # the custom state name for the Pass state, defaults to 'Filter input and inject data' as the state name
parameters={ # input to the pass state
"input": sfn.JsonPath.string_at("$.input.greeting"),
"other_data": "some-extra-stuff"}
)
Pass pass = Pass.Builder.create(this, "Filter input and inject data")
.stateName("my-pass-state") // the custom state name for the Pass state, defaults to 'Filter input and inject data' as the state name
.parameters(Map.of( // input to the pass state
"input", JsonPath.stringAt("$.input.greeting"),
"otherData", "some-extra-stuff"))
.build();
var pass = new Pass(this, "Filter input and inject data", new PassProps {
StateName = "my-pass-state", // the custom state name for the Pass state, defaults to 'Filter input and inject data' as the state name
Parameters = new Dictionary<string, object> { // input to the pass state
{ "input", JsonPath.StringAt("$.input.greeting") },
{ "otherData", "some-extra-stuff" } }
});
pass := sfn.NewPass(this, jsii.String("Filter input and inject data"), &PassProps{
StateName: jsii.String("my-pass-state"),
// the custom state name for the Pass state, defaults to 'Filter input and inject data' as the state name
Parameters: map[string]interface{}{
// input to the pass state
"input": sfn.JsonPath_stringAt(jsii.String("$.input.greeting")),
"otherData": jsii.String("some-extra-stuff"),
},
})
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 state object's "triggerTime"
// field.
const wait = new sfn.Wait(this, 'Wait For Trigger Time', {
time: sfn.WaitTime.timestampPath('$.triggerTime'),
});
// When using JSONata
// const wait = sfn.Wait.jsonata(this, 'Wait For Trigger Time', {
// time: sfn.WaitTime.timestamp('{% $triggerTime %}'),
// });
// Set the next state
const startTheWork = new sfn.Pass(this, 'StartTheWork');
wait.next(startTheWork);
# Wait until it's the time mentioned in the state object's "triggerTime"
# field.
wait = sfn.Wait(self, "Wait For Trigger Time",
time=sfn.WaitTime.timestamp_path("$.triggerTime")
)
# When using JSONata
# const wait = sfn.Wait.jsonata(this, 'Wait For Trigger Time', {
# time: sfn.WaitTime.timestamp('{% $triggerTime %}'),
# });
# Set the next state
start_the_work = sfn.Pass(self, "StartTheWork")
wait.next(start_the_work)
// Wait until it's the time mentioned in the state object's "triggerTime"
// field.
Wait wait = Wait.Builder.create(this, "Wait For Trigger Time")
.time(WaitTime.timestampPath("$.triggerTime"))
.build();
// When using JSONata
// const wait = sfn.Wait.jsonata(this, 'Wait For Trigger Time', {
// time: sfn.WaitTime.timestamp('{% $triggerTime %}'),
// });
// Set the next state
Pass startTheWork = new Pass(this, "StartTheWork");
wait.next(startTheWork);
// Wait until it's the time mentioned in the state object's "triggerTime"
// field.
var wait = new Wait(this, "Wait For Trigger Time", new WaitProps {
Time = WaitTime.TimestampPath("$.triggerTime")
});
// When using JSONata
// const wait = sfn.Wait.jsonata(this, 'Wait For Trigger Time', {
// time: sfn.WaitTime.timestamp('{% $triggerTime %}'),
// });
// Set the next state
var startTheWork = new Pass(this, "StartTheWork");
wait.Next(startTheWork);
// Wait until it's the time mentioned in the state object's "triggerTime"
// field.
wait := sfn.NewWait(this, jsii.String("Wait For Trigger Time"), &WaitProps{
Time: sfn.WaitTime_TimestampPath(jsii.String("$.triggerTime")),
})
// When using JSONata
// const wait = sfn.Wait.jsonata(this, 'Wait For Trigger Time', {
// time: sfn.WaitTime.timestamp('{% $triggerTime %}'),
// });
// Set the next state
startTheWork := sfn.NewPass(this, jsii.String("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:
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);
// When using JSONata
// choice.when(sfn.Condition.jsonata("{% $status = 'SUCCESS'"), successState);
// choice.when(sfn.Condition.jsonata('{% $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);
choice = sfn.Choice(self, "Did it work?")
# Add conditions with .when()
success_state = sfn.Pass(self, "SuccessState")
failure_state = sfn.Pass(self, "FailureState")
choice.when(sfn.Condition.string_equals("$.status", "SUCCESS"), success_state)
choice.when(sfn.Condition.number_greater_than("$.attempts", 5), failure_state)
# When using JSONata
# choice.when(sfn.Condition.jsonata("{% $status = 'SUCCESS'"), successState);
# choice.when(sfn.Condition.jsonata('{% $attempts > 5 %}'), failureState);
# Use .otherwise() to indicate what should be done if none of the conditions match
try_again_state = sfn.Pass(self, "TryAgainState")
choice.otherwise(try_again_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);
// When using JSONata
// choice.when(sfn.Condition.jsonata("{% $status = 'SUCCESS'"), successState);
// choice.when(sfn.Condition.jsonata('{% $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);
var choice = new Choice(this, "Did it work?");
// Add conditions with .when()
var successState = new Pass(this, "SuccessState");
var failureState = new Pass(this, "FailureState");
choice.When(Condition.StringEquals("$.status", "SUCCESS"), successState);
choice.When(Condition.NumberGreaterThan("$.attempts", 5), failureState);
// When using JSONata
// choice.when(sfn.Condition.jsonata("{% $status = 'SUCCESS'"), successState);
// choice.when(sfn.Condition.jsonata('{% $attempts > 5 %}'), failureState);
// Use .otherwise() to indicate what should be done if none of the conditions match
var tryAgainState = new Pass(this, "TryAgainState");
choice.Otherwise(tryAgainState);
choice := sfn.NewChoice(this, jsii.String("Did it work?"))
// Add conditions with .when()
successState := sfn.NewPass(this, jsii.String("SuccessState"))
failureState := sfn.NewPass(this, jsii.String("FailureState"))
choice.When(sfn.Condition_StringEquals(jsii.String("$.status"), jsii.String("SUCCESS")), successState)
choice.When(sfn.Condition_NumberGreaterThan(jsii.String("$.attempts"), jsii.Number(5)), failureState)
// When using JSONata
// choice.when(sfn.Condition.jsonata("{% $status = 'SUCCESS'"), successState);
// choice.when(sfn.Condition.jsonata('{% $attempts > 5 %}'), failureState);
// Use .otherwise() to indicate what should be done if none of the conditions match
tryAgainState := sfn.NewPass(this, jsii.String("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:
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 = sfn.Choice(self, "What color is it?")
handle_blue_item = sfn.Pass(self, "HandleBlueItem")
handle_red_item = sfn.Pass(self, "HandleRedItem")
handle_other_item_color = sfn.Pass(self, "HanldeOtherItemColor")
choice.when(sfn.Condition.string_equals("$.color", "BLUE"), handle_blue_item)
choice.when(sfn.Condition.string_equals("$.color", "RED"), handle_red_item)
choice.otherwise(handle_other_item_color)
# Use .afterwards() to join all possible paths back together and continue
ship_the_item = sfn.Pass(self, "ShipTheItem")
choice.afterwards().next(ship_the_item)
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);
var choice = new Choice(this, "What color is it?");
var handleBlueItem = new Pass(this, "HandleBlueItem");
var handleRedItem = new Pass(this, "HandleRedItem");
var 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
var shipTheItem = new Pass(this, "ShipTheItem");
choice.Afterwards().Next(shipTheItem);
choice := sfn.NewChoice(this, jsii.String("What color is it?"))
handleBlueItem := sfn.NewPass(this, jsii.String("HandleBlueItem"))
handleRedItem := sfn.NewPass(this, jsii.String("HandleRedItem"))
handleOtherItemColor := sfn.NewPass(this, jsii.String("HanldeOtherItemColor"))
choice.When(sfn.Condition_StringEquals(jsii.String("$.color"), jsii.String("BLUE")), handleBlueItem)
choice.When(sfn.Condition_StringEquals(jsii.String("$.color"), jsii.String("RED")), handleRedItem)
choice.Otherwise(handleOtherItemColor)
// Use .afterwards() to join all possible paths back together and continue
shipTheItem := sfn.NewPass(this, jsii.String("ShipTheItem"))
choice.Afterwards().Next(shipTheItem)
You can add comments to Choice states as well as conditions that use choice.when.
const choice = new sfn.Choice(this, 'What color is it?', {
comment: 'color comment',
});
const handleBlueItem = new sfn.Pass(this, 'HandleBlueItem');
const handleOtherItemColor = new sfn.Pass(this, 'HanldeOtherItemColor');
choice.when(sfn.Condition.stringEquals('$.color', 'BLUE'), handleBlueItem, {
comment: 'blue item comment',
});
choice.otherwise(handleOtherItemColor);
choice = sfn.Choice(self, "What color is it?",
comment="color comment"
)
handle_blue_item = sfn.Pass(self, "HandleBlueItem")
handle_other_item_color = sfn.Pass(self, "HanldeOtherItemColor")
choice.when(sfn.Condition.string_equals("$.color", "BLUE"), handle_blue_item,
comment="blue item comment"
)
choice.otherwise(handle_other_item_color)
Choice choice = Choice.Builder.create(this, "What color is it?")
.comment("color comment")
.build();
Pass handleBlueItem = new Pass(this, "HandleBlueItem");
Pass handleOtherItemColor = new Pass(this, "HanldeOtherItemColor");
choice.when(Condition.stringEquals("$.color", "BLUE"), handleBlueItem, ChoiceTransitionOptions.builder()
.comment("blue item comment")
.build());
choice.otherwise(handleOtherItemColor);
var choice = new Choice(this, "What color is it?", new ChoiceProps {
Comment = "color comment"
});
var handleBlueItem = new Pass(this, "HandleBlueItem");
var handleOtherItemColor = new Pass(this, "HanldeOtherItemColor");
choice.When(Condition.StringEquals("$.color", "BLUE"), handleBlueItem, new ChoiceTransitionOptions {
Comment = "blue item comment"
});
choice.Otherwise(handleOtherItemColor);
choice := sfn.NewChoice(this, jsii.String("What color is it?"), &ChoiceProps{
Comment: jsii.String("color comment"),
})
handleBlueItem := sfn.NewPass(this, jsii.String("HandleBlueItem"))
handleOtherItemColor := sfn.NewPass(this, jsii.String("HanldeOtherItemColor"))
choice.When(sfn.Condition_StringEquals(jsii.String("$.color"), jsii.String("BLUE")), handleBlueItem, &ChoiceTransitionOptions{
Comment: jsii.String("blue item comment"),
})
choice.Otherwise(handleOtherItemColor)
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
JSONata
When you're using JSONata, use the jsonata function to specify the condition using a JSONata expression:
sfn.Condition.jsonata('{% 1+1 = 2 %}'); // true
sfn.Condition.jsonata('{% 1+1 != 3 %}'); // true
sfn.Condition.jsonata("{% 'world' in ['hello', 'world'] %}"); // true
sfn.Condition.jsonata("{% $contains('abracadabra', /a.*a/) %}"); // true
sfn.Condition.jsonata("{% 1+1 = 2 %}") # true
sfn.Condition.jsonata("{% 1+1 != 3 %}") # true
sfn.Condition.jsonata("{% 'world' in ['hello', 'world'] %}") # true
sfn.Condition.jsonata("{% $contains('abracadabra', /a.*a/) %}")
Condition.jsonata("{% 1+1 = 2 %}"); // true
Condition.jsonata("{% 1+1 != 3 %}"); // true
Condition.jsonata("{% 'world' in ['hello', 'world'] %}"); // true
Condition.jsonata("{% $contains('abracadabra', /a.*a/) %}");
Condition.Jsonata("{% 1+1 = 2 %}"); // true
Condition.Jsonata("{% 1+1 != 3 %}"); // true
Condition.Jsonata("{% 'world' in ['hello', 'world'] %}"); // true
Condition.Jsonata("{% $contains('abracadabra', /a.*a/) %}");
sfn.Condition_Jsonata(jsii.String("{% 1+1 = 2 %}")) // true
sfn.Condition_Jsonata(jsii.String("{% 1+1 != 3 %}")) // true
sfn.Condition_Jsonata(jsii.String("{% 'world' in ['hello', 'world'] %}")) // true
sfn.Condition_Jsonata(jsii.String("{% $contains('abracadabra', /a.*a/) %}"))
See the JSONata comparison operators to find more operators.
JSONPath
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: \\*
Parallel
A Parallel state executes one or more subworkflows in parallel. It can also be used to catch and recover from errors in subworkflows. The parameters property can be used to transform the input that is passed to each branch of the parallel execution.
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 with exponential backoff
parallel.addRetry({
maxAttempts: 1,
maxDelay: Duration.seconds(5),
jitterStrategy: sfn.JitterType.FULL,
});
// 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);
parallel = sfn.Parallel(self, "Do the work in parallel")
# Add branches to be executed in parallel
ship_item = sfn.Pass(self, "ShipItem")
send_invoice = sfn.Pass(self, "SendInvoice")
restock = sfn.Pass(self, "Restock")
parallel.branch(ship_item)
parallel.branch(send_invoice)
parallel.branch(restock)
# Retry the whole workflow if something goes wrong with exponential backoff
parallel.add_retry(
max_attempts=1,
max_delay=Duration.seconds(5),
jitter_strategy=sfn.JitterType.FULL
)
# How to recover from errors
send_failure_notification = sfn.Pass(self, "SendFailureNotification")
parallel.add_catch(send_failure_notification)
# What to do in case everything succeeded
close_order = sfn.Pass(self, "CloseOrder")
parallel.next(close_order)
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 with exponential backoff
parallel.addRetry(RetryProps.builder()
.maxAttempts(1)
.maxDelay(Duration.seconds(5))
.jitterStrategy(JitterType.FULL)
.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);
var parallel = new Parallel(this, "Do the work in parallel");
// Add branches to be executed in parallel
var shipItem = new Pass(this, "ShipItem");
var sendInvoice = new Pass(this, "SendInvoice");
var restock = new Pass(this, "Restock");
parallel.Branch(shipItem);
parallel.Branch(sendInvoice);
parallel.Branch(restock);
// Retry the whole workflow if something goes wrong with exponential backoff
parallel.AddRetry(new RetryProps {
MaxAttempts = 1,
MaxDelay = Duration.Seconds(5),
JitterStrategy = JitterType.FULL
});
// How to recover from errors
var sendFailureNotification = new Pass(this, "SendFailureNotification");
parallel.AddCatch(sendFailureNotification);
// What to do in case everything succeeded
var closeOrder = new Pass(this, "CloseOrder");
parallel.Next(closeOrder);
parallel := sfn.NewParallel(this, jsii.String("Do the work in parallel"))
// Add branches to be executed in parallel
shipItem := sfn.NewPass(this, jsii.String("ShipItem"))
sendInvoice := sfn.NewPass(this, jsii.String("SendInvoice"))
restock := sfn.NewPass(this, jsii.String("Restock"))
parallel.Branch(shipItem)
parallel.Branch(sendInvoice)
parallel.Branch(restock)
// Retry the whole workflow if something goes wrong with exponential backoff
parallel.AddRetry(&RetryProps{
MaxAttempts: jsii.Number(1),
MaxDelay: awscdk.Duration_Seconds(jsii.Number(5)),
JitterStrategy: sfn.JitterType_FULL,
})
// How to recover from errors
sendFailureNotification := sfn.NewPass(this, jsii.String("SendFailureNotification"))
parallel.AddCatch(sendFailureNotification)
// What to do in case everything succeeded
closeOrder := sfn.NewPass(this, jsii.String("CloseOrder"))
parallel.Next(closeOrder)
Succeed
Reaching a Succeed state terminates the state machine execution with a successful status.
const success = new sfn.Succeed(this, 'We did it!');
success = sfn.Succeed(self, "We did it!")
Succeed success = new Succeed(this, "We did it!");
var success = new Succeed(this, "We did it!");
success := sfn.NewSucceed(this, jsii.String("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.
const fail = new sfn.Fail(this, 'Fail', {
error: 'WorkflowFailure',
cause: "Something went wrong",
});
fail = sfn.Fail(self, "Fail",
error="WorkflowFailure",
cause="Something went wrong"
)
Fail fail = Fail.Builder.create(this, "Fail")
.error("WorkflowFailure")
.cause("Something went wrong")
.build();
var fail = new Fail(this, "Fail", new FailProps {
Error = "WorkflowFailure",
Cause = "Something went wrong"
});
fail := sfn.NewFail(this, jsii.String("Fail"), &FailProps{
Error: jsii.String("WorkflowFailure"),
Cause: jsii.String("Something went wrong"),
})
The Fail state also supports returning dynamic values as the error and cause that are selected from the input with a path.
const fail = new sfn.Fail(this, 'Fail', {
errorPath: sfn.JsonPath.stringAt('$.someError'),
causePath: sfn.JsonPath.stringAt('$.someCause'),
});
fail = sfn.Fail(self, "Fail",
error_path=sfn.JsonPath.string_at("$.someError"),
cause_path=sfn.JsonPath.string_at("$.someCause")
)
Fail fail = Fail.Builder.create(this, "Fail")
.errorPath(JsonPath.stringAt("$.someError"))
.causePath(JsonPath.stringAt("$.someCause"))
.build();
var fail = new Fail(this, "Fail", new FailProps {
ErrorPath = JsonPath.StringAt("$.someError"),
CausePath = JsonPath.StringAt("$.someCause")
});
fail := sfn.NewFail(this, jsii.String("Fail"), &FailProps{
ErrorPath: sfn.JsonPath_StringAt(jsii.String("$.someError")),
CausePath: sfn.JsonPath_*StringAt(jsii.String("$.someCause")),
})
You can also use an intrinsic function that returns a string to specify CausePath and ErrorPath. The available functions include States.Format, States.JsonToString, States.ArrayGetItem, States.Base64Encode, States.Base64Decode, States.Hash, and States.UUID.
const fail = new sfn.Fail(this, 'Fail', {
errorPath: sfn.JsonPath.format('error: {}.', sfn.JsonPath.stringAt('$.someError')),
causePath: "States.Format('cause: {}.', $.someCause)",
});
fail = sfn.Fail(self, "Fail",
error_path=sfn.JsonPath.format("error: {}.", sfn.JsonPath.string_at("$.someError")),
cause_path="States.Format('cause: {}.', $.someCause)"
)
Fail fail = Fail.Builder.create(this, "Fail")
.errorPath(JsonPath.format("error: {}.", JsonPath.stringAt("$.someError")))
.causePath("States.Format('cause: {}.', $.someCause)")
.build();
var fail = new Fail(this, "Fail", new FailProps {
ErrorPath = JsonPath.Format("error: {}.", JsonPath.StringAt("$.someError")),
CausePath = "States.Format('cause: {}.', $.someCause)"
});
fail := sfn.NewFail(this, jsii.String("Fail"), &FailProps{
ErrorPath: sfn.JsonPath_Format(jsii.String("error: {}."), sfn.JsonPath_StringAt(jsii.String("$.someError"))),
CausePath: jsii.String("States.Format('cause: {}.', $.someCause)"),
})
When you use JSONata, you can use JSONata expression in the error or cause properties.
const fail = new sfn.Fail(this, 'Fail', {
error: "{% 'error:' & $someError & '.' %}",
cause: "{% 'cause:' & $someCause & '.' %}",
});
fail = sfn.Fail(self, "Fail",
error="{% 'error:' & $someError & '.' %}",
cause="{% 'cause:' & $someCause & '.' %}"
)
Fail fail = Fail.Builder.create(this, "Fail")
.error("{% 'error:' & $someError & '.' %}")
.cause("{% 'cause:' & $someCause & '.' %}")
.build();
var fail = new Fail(this, "Fail", new FailProps {
Error = "{% 'error:' & $someError & '.' %}",
Cause = "{% 'cause:' & $someCause & '.' %}"
});
fail := sfn.NewFail(this, jsii.String("Fail"), &FailProps{
Error: jsii.String("{% 'error:' & $someError & '.' %}"),
Cause: jsii.String("{% 'cause:' & $someCause & '.' %}"),
})
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.
const map = new sfn.Map(this, 'Map State', {
maxConcurrency: 1,
itemsPath: sfn.JsonPath.stringAt('$.inputForMap'),
itemSelector: {
item: sfn.JsonPath.stringAt('$$.Map.Item.Value'),
},
resultPath: '$.mapOutput',
});
// The Map iterator can contain a IChainable, which can be an individual or multiple steps chained together.
// Below example is with a Choice and Pass step
const choice = new sfn.Choice(this, 'Choice');
const condition1 = sfn.Condition.stringEquals('$.item.status', 'SUCCESS');
const step1 = new sfn.Pass(this, 'Step1');
const step2 = new sfn.Pass(this, 'Step2');
const finish = new sfn.Pass(this, 'Finish');
const definition = choice
.when(condition1, step1)
.otherwise(step2)
.afterwards()
.next(finish);
map.itemProcessor(definition);
map = sfn.Map(self, "Map State",
max_concurrency=1,
items_path=sfn.JsonPath.string_at("$.inputForMap"),
item_selector={
"item": sfn.JsonPath.string_at("$.Map.Item.Value")
},
result_path="$.mapOutput"
)
# The Map iterator can contain a IChainable, which can be an individual or multiple steps chained together.
# Below example is with a Choice and Pass step
choice = sfn.Choice(self, "Choice")
condition1 = sfn.Condition.string_equals("$.item.status", "SUCCESS")
step1 = sfn.Pass(self, "Step1")
step2 = sfn.Pass(self, "Step2")
finish = sfn.Pass(self, "Finish")
definition = choice.when(condition1, step1).otherwise(step2).afterwards().next(finish)
map.item_processor(definition)
Map map = Map.Builder.create(this, "Map State")
.maxConcurrency(1)
.itemsPath(JsonPath.stringAt("$.inputForMap"))
.itemSelector(Map.of(
"item", JsonPath.stringAt("$.Map.Item.Value")))
.resultPath("$.mapOutput")
.build();
// The Map iterator can contain a IChainable, which can be an individual or multiple steps chained together.
// Below example is with a Choice and Pass step
Choice choice = new Choice(this, "Choice");
Condition condition1 = Condition.stringEquals("$.item.status", "SUCCESS");
Pass step1 = new Pass(this, "Step1");
Pass step2 = new Pass(this, "Step2");
Pass finish = new Pass(this, "Finish");
Chain definition = choice.when(condition1, step1).otherwise(step2).afterwards().next(finish);
map.itemProcessor(definition);
var map = new Map(this, "Map State", new MapProps {
MaxConcurrency = 1,
ItemsPath = JsonPath.StringAt("$.inputForMap"),
ItemSelector = new Dictionary<string, object> {
{ "item", JsonPath.StringAt("$.Map.Item.Value") }
},
ResultPath = "$.mapOutput"
});
// The Map iterator can contain a IChainable, which can be an individual or multiple steps chained together.
// Below example is with a Choice and Pass step
var choice = new Choice(this, "Choice");
var condition1 = Condition.StringEquals("$.item.status", "SUCCESS");
var step1 = new Pass(this, "Step1");
var step2 = new Pass(this, "Step2");
var finish = new Pass(this, "Finish");
var definition = choice.When(condition1, step1).Otherwise(step2).Afterwards().Next(finish);
map.ItemProcessor(definition);
map := sfn.NewMap(this, jsii.String("Map State"), &MapProps{
MaxConcurrency: jsii.Number(1),
ItemsPath: sfn.JsonPath_StringAt(jsii.String("$.inputForMap")),
ItemSelector: map[string]interface{}{
"item": sfn.JsonPath_*StringAt(jsii.String("$.Map.Item.Value")),
},
ResultPath: jsii.String("$.mapOutput"),
})
// The Map iterator can contain a IChainable, which can be an individual or multiple steps chained together.
// Below example is with a Choice and Pass step
choice := sfn.NewChoice(this, jsii.String("Choice"))
condition1 := sfn.Condition_StringEquals(jsii.String("$.item.status"), jsii.String("SUCCESS"))
step1 := sfn.NewPass(this, jsii.String("Step1"))
step2 := sfn.NewPass(this, jsii.String("Step2"))
finish := sfn.NewPass(this, jsii.String("Finish"))
definition := choice.When(condition1, step1).Otherwise(step2).Afterwards().Next(finish)
map.ItemProcessor(definition)
When using JSONata, the itemSelector property in a Map state can be specified in one of two ways. You can provide a valid JSON object containing JSONata expressions for each value:
const map = new sfn.Map(this, 'Map State', {
maxConcurrency: 1,
itemSelector: {
id: '{% $states.context.Map.Item.Value.id %}',
status: '{% $states.context.Map.Item.Value.status %}',
}
});
map = sfn.Map(self, "Map State",
max_concurrency=1,
item_selector={
"id": "{% $states.context.Map.Item.Value.id %}",
"status": "{% $states.context.Map.Item.Value.status %}"
}
)
Map map = Map.Builder.create(this, "Map State")
.maxConcurrency(1)
.itemSelector(Map.of(
"id", "{% $states.context.Map.Item.Value.id %}",
"status", "{% $states.context.Map.Item.Value.status %}"))
.build();
var map = new Map(this, "Map State", new MapProps {
MaxConcurrency = 1,
ItemSelector = new Dictionary<string, object> {
{ "id", "{% $states.context.Map.Item.Value.id %}" },
{ "status", "{% $states.context.Map.Item.Value.status %}" }
}
});
map := sfn.NewMap(this, jsii.String("Map State"), &MapProps{
MaxConcurrency: jsii.Number(1),
ItemSelector: map[string]interface{}{
"id": jsii.String("{% $states.context.Map.Item.Value.id %}"),
"status": jsii.String("{% $states.context.Map.Item.Value.status %}"),
},
})
Alternatively, you can use the jsonataItemSelector field to directly supply a JSONata string that evaluates to a complete JSON object:
const map = new sfn.Map(this, 'Map State', {
maxConcurrency: 1,
jsonataItemSelector: '{% {\"id\": $states.input.id, \"status\": $states.input.status} %}'
});
map = sfn.Map(self, "Map State",
max_concurrency=1,
jsonata_item_selector="{% {\"id\": $states.input.id, \"status\": $states.input.status} %}"
)
Map map = Map.Builder.create(this, "Map State")
.maxConcurrency(1)
.jsonataItemSelector("{% {\"id\": $states.input.id, \"status\": $states.input.status} %}")
.build();
var map = new Map(this, "Map State", new MapProps {
MaxConcurrency = 1,
JsonataItemSelector = "{% {\"id\": $states.input.id, \"status\": $states.input.status} %}"
});
map := sfn.NewMap(this, jsii.String("Map State"), &MapProps{
MaxConcurrency: jsii.Number(1),
JsonataItemSelector: jsii.String("{% {\"id\": $states.input.id, \"status\": $states.input.status} %}"),
})
When using JSONata, you can also specify the maxConcurrency dynamically using a JSONata expression with the jsonataMaxConcurrency property. This allows you to determine the concurrency limit based on state input or other runtime values:
const map = new sfn.Map(this, 'Map State', {
jsonataMaxConcurrency: '{% $states.input.maxConcurrency %}',
itemSelector: {
item: '{% $states.context.Map.Item.Value %}',
}
});
map = sfn.Map(self, "Map State",
jsonata_max_concurrency="{% $states.input.maxConcurrency %}",
item_selector={
"item": "{% $states.context.Map.Item.Value %}"
}
)
Map map = Map.Builder.create(this, "Map State")
.jsonataMaxConcurrency("{% $states.input.maxConcurrency %}")
.itemSelector(Map.of(
"item", "{% $states.context.Map.Item.Value %}"))
.build();
var map = new Map(this, "Map State", new MapProps {
JsonataMaxConcurrency = "{% $states.input.maxConcurrency %}",
ItemSelector = new Dictionary<string, object> {
{ "item", "{% $states.context.Map.Item.Value %}" }
}
});
map := sfn.NewMap(this, jsii.String("Map State"), &MapProps{
JsonataMaxConcurrency: jsii.String("{% $states.input.maxConcurrency %}"),
ItemSelector: map[string]interface{}{
"item": jsii.String("{% $states.context.Map.Item.Value %}"),
},
})
Note that jsonataMaxConcurrency is mutually exclusive with maxConcurrency and maxConcurrencyPath.
To define a distributed Map state set itemProcessors mode to ProcessorMode.DISTRIBUTED. An executionType must be specified for the distributed Map workflow.
const map = new sfn.Map(this, 'Map State', {
maxConcurrency: 1,
itemsPath: sfn.JsonPath.stringAt('$.inputForMap'),
itemSelector: {
item: sfn.JsonPath.stringAt('$$.Map.Item.Value'),
},
resultPath: '$.mapOutput',
});
map.itemProcessor(new sfn.Pass(this, 'Pass State'), {
mode: sfn.ProcessorMode.DISTRIBUTED,
executionType: sfn.ProcessorType.STANDARD,
});
map = sfn.Map(self, "Map State",
max_concurrency=1,
items_path=sfn.JsonPath.string_at("$.inputForMap"),
item_selector={
"item": sfn.JsonPath.string_at("$.Map.Item.Value")
},
result_path="$.mapOutput"
)
map.item_processor(sfn.Pass(self, "Pass State"),
mode=sfn.ProcessorMode.DISTRIBUTED,
execution_type=sfn.ProcessorType.STANDARD
)
Map map = Map.Builder.create(this, "Map State")
.maxConcurrency(1)
.itemsPath(JsonPath.stringAt("$.inputForMap"))
.itemSelector(Map.of(
"item", JsonPath.stringAt("$.Map.Item.Value")))
.resultPath("$.mapOutput")
.build();
map.itemProcessor(new Pass(this, "Pass State"), ProcessorConfig.builder()
.mode(ProcessorMode.DISTRIBUTED)
.executionType(ProcessorType.STANDARD)
.build());
var map = new Map(this, "Map State", new MapProps {
MaxConcurrency = 1,
ItemsPath = JsonPath.StringAt("$.inputForMap"),
ItemSelector = new Dictionary<string, object> {
{ "item", JsonPath.StringAt("$.Map.Item.Value") }
},
ResultPath = "$.mapOutput"
});
map.ItemProcessor(new Pass(this, "Pass State"), new ProcessorConfig {
Mode = ProcessorMode.DISTRIBUTED,
ExecutionType = ProcessorType.STANDARD
});
map := sfn.NewMap(this, jsii.String("Map State"), &MapProps{
MaxConcurrency: jsii.Number(1),
ItemsPath: sfn.JsonPath_StringAt(jsii.String("$.inputForMap")),
ItemSelector: map[string]interface{}{
"item": sfn.JsonPath_*StringAt(jsii.String("$.Map.Item.Value")),
},
ResultPath: jsii.String("$.mapOutput"),
})
map.ItemProcessor(sfn.NewPass(this, jsii.String("Pass State")), &ProcessorConfig{
Mode: sfn.ProcessorMode_DISTRIBUTED,
ExecutionType: sfn.ProcessorType_STANDARD,
})
Visit Using Map state in Distributed mode to orchestrate large-scale parallel workloads for more details.
Distributed Map
Step Functions provides a high-concurrency mode for the Map state known as Distributed mode. In this mode, the Map state can accept input from large-scale Amazon S3 data sources. For example, your input can be a JSON or CSV file stored in an Amazon S3 bucket, or a JSON array passed from a previous step in the workflow. A Map state set to Distributed is known as a Distributed Map state. In this mode, the Map state runs each iteration as a child workflow execution, which enables high concurrency of up to 10,000 parallel child workflow executions. Each child workflow execution has its own, separate execution history from that of the parent workflow.
Use the Map state in Distributed mode when you need to orchestrate large-scale parallel workloads that meet any combination of the following conditions:
- The size of your dataset exceeds 256 KB.
- The workflow's execution event history exceeds 25,000 entries.
- You need a concurrency of more than 40 parallel iterations.
A DistributedMap state can be used to run a set of steps for each element of an input array with high concurrency. A DistributedMap state will execute the same steps for multiple entries of an array in the state input or from S3 objects.
const distributedMap = new sfn.DistributedMap(this, 'Distributed Map State', {
maxConcurrency: 1,
itemsPath: sfn.JsonPath.stringAt('$.inputForMap'),
});
distributedMap.itemProcessor(new sfn.Pass(this, 'Pass State'));
distributed_map = sfn.DistributedMap(self, "Distributed Map State",
max_concurrency=1,
items_path=sfn.JsonPath.string_at("$.inputForMap")
)
distributed_map.item_processor(sfn.Pass(self, "Pass State"))
DistributedMap distributedMap = DistributedMap.Builder.create(this, "Distributed Map State")
.maxConcurrency(1)
.itemsPath(JsonPath.stringAt("$.inputForMap"))
.build();
distributedMap.itemProcessor(new Pass(this, "Pass State"));
var distributedMap = new DistributedMap(this, "Distributed Map State", new DistributedMapProps {
MaxConcurrency = 1,
ItemsPath = JsonPath.StringAt("$.inputForMap")
});
distributedMap.ItemProcessor(new Pass(this, "Pass State"));
distributedMap := sfn.NewDistributedMap(this, jsii.String("Distributed Map State"), &DistributedMapProps{
MaxConcurrency: jsii.Number(1),
ItemsPath: sfn.JsonPath_StringAt(jsii.String("$.inputForMap")),
})
distributedMap.ItemProcessor(sfn.NewPass(this, jsii.String("Pass State")))
DistributedMap supports various input source types to determine a list of objects to iterate over:
- JSON array from the JSON state input
- By default,
DistributedMapassumes whole JSON state input is an JSON array and iterates over it:
ts/** * JSON state input: * [ * "item1", * "item2" * ] */ const distributedMap = new sfn.DistributedMap(this, 'DistributedMap'); distributedMap.itemProcessor(new sfn.Pass(this, 'Pass'));- When input source is present at a specific path in JSON state input, then
itemsPathcan be utilised to configure the iterator source.
ts/** * JSON state input: * { * "distributedMapItemList": [ * "item1", * "item2" * ] * } */ const distributedMap = new sfn.DistributedMap(this, 'DistributedMap', { itemsPath: '$.distributedMapItemList', }); distributedMap.itemProcessor(new sfn.Pass(this, 'Pass')); - By default,
- Objects in a S3 bucket with an optional prefix.
- When
DistributedMapis required to iterate over objects stored in a S3 bucket, then an object ofS3ObjectsItemReadercan be passed toitemReaderto configure the iterator source. Note thatS3ObjectsItemReaderwill default to use Distributed map's query language. If the map does not specify a query language, then it falls back to the State machine's query language. An exmaple of usingS3ObjectsItemReaderis as follows:
tsimport * as s3 from 'aws-cdk-lib/aws-s3'; /** * Tree view of bucket: * my-bucket * | * +--item1 * | * +--otherItem * | * +--item2 * | * ... */ const bucket = new s3.Bucket(this, 'Bucket', { bucketName: 'my-bucket', }); const distributedMap = new sfn.DistributedMap(this, 'DistributedMap', { itemReader: new sfn.S3ObjectsItemReader({ bucket, prefix: 'item', }), }); distributedMap.itemProcessor(new sfn.Pass(this, 'Pass'));- If information about
bucketis only known while starting execution ofStateMachine(dynamically or at run-time) via JSON state input:
ts/** * JSON state input: * { * "bucketName": "my-bucket", * "prefix": "item" * } */ const distributedMap = new sfn.DistributedMap(this, 'DistributedMap', { itemReader: new sfn.S3ObjectsItemReader({ bucketNamePath: sfn.JsonPath.stringAt('$.bucketName'), prefix: sfn.JsonPath.stringAt('$.prefix'), }), }); distributedMap.itemProcessor(new sfn.Pass(this, 'Pass'));- Both
bucketandbucketNamePathare mutually exclusive.
- When
- JSON array in a JSON file stored in S3
- When
DistributedMapis required to iterate over a JSON array stored in a JSON file in a S3 bucket, then an object ofS3JsonItemReadercan be passed toitemReaderto configure the iterator source as follows:
tsimport * as s3 from 'aws-cdk-lib/aws-s3'; /** * Tree view of bucket: * my-bucket * | * +--input.json * | * ... * * File content of input.json: * [ * "item1", * "item2" * ] */ const bucket = new s3.Bucket(this, 'Bucket', { bucketName: 'my-bucket', }); const distributedMap = new sfn.DistributedMap(this, 'DistributedMap', { itemReader: new sfn.S3JsonItemReader({ bucket, key: 'input.json', }), }); distributedMap.itemProcessor(new sfn.Pass(this, 'Pass'));- If information about
bucketis only known while starting execution ofStateMachine(dynamically or at run-time) via state input:
ts/** * JSON state input: * { * "bucketName": "my-bucket", * "key": "input.json" * } */ const distributedMap = new sfn.DistributedMap(this, 'DistributedMap', { itemReader: new sfn.S3JsonItemReader({ bucketNamePath: sfn.JsonPath.stringAt('$.bucketName'), key: sfn.JsonPath.stringAt('$.key'), }), }); distributedMap.itemProcessor(new sfn.Pass(this, 'Pass')); - When
- CSV file stored in S3
- S3 inventory manifest stored in S3
Map states in Distributed mode also support writing results of the iterator to an S3 bucket and optional prefix. Use a ResultWriterV2 object provided via the optional resultWriter property to configure which S3 location iterator results will be written. The default behavior id resultWriter is omitted is to use the state output payload. However, if the iterator results are larger than the 256 kb limit for Step Functions payloads then the State Machine will fail.
ResultWriterV2 object will default to use the Distributed map's query language. If the Distributed map's does not specify a query language, then it will fall back to the State machine's query langauge.
Note: ResultWriter has been deprecated, use ResultWriterV2 instead. To enable ResultWriterV2, you will have to set the value for '@aws-cdk/aws-stepfunctions:useDistributedMapResultWriterV2' to true in the CDK context
import * as s3 from 'aws-cdk-lib/aws-s3';
// create a bucket
const bucket = new s3.Bucket(this, 'Bucket');
// create a WriterConfig
const distributedMap = new sfn.DistributedMap(this, 'Distributed Map State', {
resultWriterV2: new sfn.ResultWriterV2({
bucket: bucket,
prefix: 'my-prefix',
writerConfig: {
outputType: sfn.OutputType.JSONL,
transformation: sfn.Transformation.NONE,
},
})
});
distributedMap.itemProcessor(new sfn.Pass(this, 'Pass State'));
import aws_cdk.aws_s3 as s3
# create a bucket
bucket = s3.Bucket(self, "Bucket")
# create a WriterConfig
distributed_map = sfn.DistributedMap(self, "Distributed Map State",
result_writer_v2=sfn.ResultWriterV2(
bucket=bucket,
prefix="my-prefix",
writer_config={
"output_type": sfn.OutputType.JSONL,
"transformation": sfn.Transformation.NONE
}
)
)
distributed_map.item_processor(sfn.Pass(self, "Pass State"))
import software.amazon.awscdk.services.s3.*;
// create a bucket
Bucket bucket = new Bucket(this, "Bucket");
// create a WriterConfig
DistributedMap distributedMap = DistributedMap.Builder.create(this, "Distributed Map State")
.resultWriterV2(ResultWriterV2.Builder.create()
.bucket(bucket)
.prefix("my-prefix")
.writerConfig(Map.of(
"outputType", OutputType.JSONL,
"transformation", Transformation.NONE))
.build())
.build();
distributedMap.itemProcessor(new Pass(this, "Pass State"));
using Amazon.CDK.AWS.S3;
// create a bucket
var bucket = new Bucket(this, "Bucket");
// create a WriterConfig
var distributedMap = new DistributedMap(this, "Distributed Map State", new DistributedMapProps {
ResultWriterV2 = new ResultWriterV2(new ResultWriterV2Props {
Bucket = bucket,
Prefix = "my-prefix",
WriterConfig = new Dictionary<string, object> {
{ "outputType", OutputType.JSONL },
{ "transformation", Transformation.NONE }
}
})
});
distributedMap.ItemProcessor(new Pass(this, "Pass State"));
import s3 "github.com/aws/aws-cdk-go/awscdk"
// create a bucket
bucket := s3.NewBucket(this, jsii.String("Bucket"))
// create a WriterConfig
distributedMap := sfn.NewDistributedMap(this, jsii.String("Distributed Map State"), &DistributedMapProps{
ResultWriterV2: sfn.NewResultWriterV2(&ResultWriterV2Props{
Bucket: bucket,
Prefix: jsii.String("my-prefix"),
WriterConfig: map[string]interface{}{
"outputType": sfn.OutputType_JSONL,
"transformation": sfn.Transformation_NONE,
},
}),
})
distributedMap.ItemProcessor(sfn.NewPass(this, jsii.String("Pass State")))
- If information about
bucketis only known while starting execution ofStateMachine(dynamically or at run-time) via JSON state input:
/**
* JSON state input:
* {
* "bucketName": "my-bucket"
* }
*/
const distributedMap = new sfn.DistributedMap(this, 'DistributedMap', {
resultWriterV2: new sfn.ResultWriterV2({
bucketNamePath: sfn.JsonPath.stringAt('$.bucketName'),
}),
});
distributedMap.itemProcessor(new sfn.Pass(this, 'Pass'));
#
# JSON state input:
# {
# "bucketName": "my-bucket"
# }
#
distributed_map = sfn.DistributedMap(self, "DistributedMap",
result_writer_v2=sfn.ResultWriterV2(
bucket_name_path=sfn.JsonPath.string_at("$.bucketName")
)
)
distributed_map.item_processor(sfn.Pass(self, "Pass"))
/**
* JSON state input:
* {
* "bucketName": "my-bucket"
* }
*/
DistributedMap distributedMap = DistributedMap.Builder.create(this, "DistributedMap")
.resultWriterV2(ResultWriterV2.Builder.create()
.bucketNamePath(JsonPath.stringAt("$.bucketName"))
.build())
.build();
distributedMap.itemProcessor(new Pass(this, "Pass"));
/**
* JSON state input:
* {
* "bucketName": "my-bucket"
* }
*/
var distributedMap = new DistributedMap(this, "DistributedMap", new DistributedMapProps {
ResultWriterV2 = new ResultWriterV2(new ResultWriterV2Props {
BucketNamePath = JsonPath.StringAt("$.bucketName")
})
});
distributedMap.ItemProcessor(new Pass(this, "Pass"));
/**
* JSON state input:
* {
* "bucketName": "my-bucket"
* }
*/
distributedMap := sfn.NewDistributedMap(this, jsii.String("DistributedMap"), &DistributedMapProps{
ResultWriterV2: sfn.NewResultWriterV2(&ResultWriterV2Props{
BucketNamePath: sfn.JsonPath_StringAt(jsii.String("$.bucketName")),
}),
})
distributedMap.ItemProcessor(sfn.NewPass(this, jsii.String("Pass")))
- Both
bucketandbucketNamePathare mutually exclusive.
If you want to specify the execution type for the ItemProcessor in the DistributedMap, you must set the mapExecutionType property in the DistributedMap class. When using the DistributedMap class, the ProcessorConfig.executionType property is ignored.
In the following example, the execution type for the ItemProcessor in the DistributedMap is set to EXPRESS based on the value specified for mapExecutionType.
const distributedMap = new sfn.DistributedMap(this, 'DistributedMap', {
mapExecutionType: sfn.StateMachineType.EXPRESS, // mapExecutionType property is applied.
});
distributedMap.itemProcessor(new sfn.Pass(this, 'Pass'), {
mode: sfn.ProcessorMode.DISTRIBUTED,
executionType: sfn.ProcessorType.STANDARD, // ProcessorConfig.executionType is ignored
});
distributed_map = sfn.DistributedMap(self, "DistributedMap",
map_execution_type=sfn.StateMachineType.EXPRESS
)
distributed_map.item_processor(sfn.Pass(self, "Pass"),
mode=sfn.ProcessorMode.DISTRIBUTED,
execution_type=sfn.ProcessorType.STANDARD
)
DistributedMap distributedMap = DistributedMap.Builder.create(this, "DistributedMap")
.mapExecutionType(StateMachineType.EXPRESS)
.build();
distributedMap.itemProcessor(new Pass(this, "Pass"), ProcessorConfig.builder()
.mode(ProcessorMode.DISTRIBUTED)
.executionType(ProcessorType.STANDARD)
.build());
var distributedMap = new DistributedMap(this, "DistributedMap", new DistributedMapProps {
MapExecutionType = StateMachineType.EXPRESS
});
distributedMap.ItemProcessor(new Pass(this, "Pass"), new ProcessorConfig {
Mode = ProcessorMode.DISTRIBUTED,
ExecutionType = ProcessorType.STANDARD
});
distributedMap := sfn.NewDistributedMap(this, jsii.String("DistributedMap"), &DistributedMapProps{
MapExecutionType: sfn.StateMachineType_EXPRESS,
})
distributedMap.ItemProcessor(sfn.NewPass(this, jsii.String("Pass")), &ProcessorConfig{
Mode: sfn.ProcessorMode_DISTRIBUTED,
ExecutionType: sfn.ProcessorType_STANDARD,
})
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:
- A service integration is available through Amazon States Language, but not available as construct classes in the CDK.
- The state or state properties are available through Step Functions, but are not configurable through constructs
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 Retry and Catch fields are available for error handling. You can configure the Retry field by defining it in the JSON object or by adding it using the addRetry method. However, the Catch field cannot be configured by defining it in the JSON object, so it must be added using the addCatch method.
The following example uses the DynamoDB service integration to insert data into a DynamoDB table.
import * as dynamodb from 'aws-cdk-lib/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,
});
// catch errors with addCatch
const errorHandler = new sfn.Pass(this, 'handle failure');
custom.addCatch(errorHandler);
// retry the task if something goes wrong
custom.addRetry({
errors: [sfn.Errors.ALL],
interval: Duration.seconds(10),
maxAttempts: 5,
});
const chain = sfn.Chain.start(custom)
.next(finalStatus);
const sm = new sfn.StateMachine(this, 'StateMachine', {
definitionBody: sfn.DefinitionBody.fromChainable(chain),
timeout: Duration.seconds(30),
comment: 'a super cool state machine',
});
// don't forget permissions. You need to assign them
table.grantWriteData(sm);
import aws_cdk.aws_dynamodb as dynamodb
# create a table
table = dynamodb.Table(self, "montable",
partition_key=dynamodb.Attribute(
name="id",
type=dynamodb.AttributeType.STRING
)
)
final_status = sfn.Pass(self, "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
state_json = {
"Type": "Task",
"Resource": "arn:aws:states:::dynamodb:putItem",
"Parameters": {
"TableName": table.table_name,
"Item": {
"id": {
"S": "MyEntry"
}
}
},
"ResultPath": null
}
# custom state which represents a task to insert data into DynamoDB
custom = sfn.CustomState(self, "my custom task",
state_json=state_json
)
# catch errors with addCatch
error_handler = sfn.Pass(self, "handle failure")
custom.add_catch(error_handler)
# retry the task if something goes wrong
custom.add_retry(
errors=[sfn.Errors.ALL],
interval=Duration.seconds(10),
max_attempts=5
)
chain = sfn.Chain.start(custom).next(final_status)
sm = sfn.StateMachine(self, "StateMachine",
definition_body=sfn.DefinitionBody.from_chainable(chain),
timeout=Duration.seconds(30),
comment="a super cool state machine"
)
# don't forget permissions. You need to assign them
table.grant_write_data(sm)
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();
// catch errors with addCatch
Pass errorHandler = new Pass(this, "handle failure");
custom.addCatch(errorHandler);
// retry the task if something goes wrong
custom.addRetry(RetryProps.builder()
.errors(List.of(Errors.ALL))
.interval(Duration.seconds(10))
.maxAttempts(5)
.build());
Chain chain = Chain.start(custom).next(finalStatus);
StateMachine sm = StateMachine.Builder.create(this, "StateMachine")
.definitionBody(DefinitionBody.fromChainable(chain))
.timeout(Duration.seconds(30))
.comment("a super cool state machine")
.build();
// don't forget permissions. You need to assign them
table.grantWriteData(sm);
using Amazon.CDK.AWS.DynamoDB;
// create a table
var table = new Table(this, "montable", new TableProps {
PartitionKey = new Attribute {
Name = "id",
Type = AttributeType.STRING
}
});
var 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
IDictionary<string, object> stateJson = new Dictionary<string, object> {
{ "Type", "Task" },
{ "Resource", "arn:aws:states:::dynamodb:putItem" },
{ "Parameters", new Dictionary<string, object> {
{ "TableName", table.TableName },
{ "Item", new Dictionary<string, IDictionary<string, string>> {
{ "id", new Dictionary<string, string> {
{ "S", "MyEntry" }
} }
} }
} },
{ "ResultPath", null }
};
// custom state which represents a task to insert data into DynamoDB
var custom = new CustomState(this, "my custom task", new CustomStateProps {
StateJson = stateJson
});
// catch errors with addCatch
var errorHandler = new Pass(this, "handle failure");
custom.AddCatch(errorHandler);
// retry the task if something goes wrong
custom.AddRetry(new RetryProps {
Errors = new [] { Errors.ALL },
Interval = Duration.Seconds(10),
MaxAttempts = 5
});
var chain = Chain.Start(custom).Next(finalStatus);
var sm = new StateMachine(this, "StateMachine", new StateMachineProps {
DefinitionBody = DefinitionBody.FromChainable(chain),
Timeout = Duration.Seconds(30),
Comment = "a super cool state machine"
});
// don't forget permissions. You need to assign them
table.GrantWriteData(sm);
import "github.com/aws/aws-cdk-go/awscdk"
// create a table
table := dynamodb.NewTable(this, jsii.String("montable"), &TableProps{
PartitionKey: &Attribute{
Name: jsii.String("id"),
Type: dynamodb.AttributeType_STRING,
},
})
finalStatus := sfn.NewPass(this, jsii.String("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
stateJson := map[string]interface{}{
"Type": jsii.String("Task"),
"Resource": jsii.String("arn:aws:states:::dynamodb:putItem"),
"Parameters": map[string]interface{}{
"TableName": table.tableName,
"Item": map[string]map[string]*string{
"id": map[string]*string{
"S": jsii.String("MyEntry"),
},
},
},
"ResultPath": nil,
}
// custom state which represents a task to insert data into DynamoDB
custom := sfn.NewCustomState(this, jsii.String("my custom task"), &CustomStateProps{
StateJson: StateJson,
})
// catch errors with addCatch
errorHandler := sfn.NewPass(this, jsii.String("handle failure"))
custom.AddCatch(errorHandler)
// retry the task if something goes wrong
custom.AddRetry(&RetryProps{
Errors: []*string{
sfn.Errors_ALL(),
},
Interval: awscdk.Duration_Seconds(jsii.Number(10)),
MaxAttempts: jsii.Number(5),
})
chain := sfn.Chain_Start(custom).Next(finalStatus)
sm := sfn.NewStateMachine(this, jsii.String("StateMachine"), &StateMachineProps{
DefinitionBody: sfn.DefinitionBody_FromChainable(chain),
Timeout: awscdk.Duration_*Seconds(jsii.Number(30)),
Comment: jsii.String("a super cool state machine"),
})
// 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:
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', {
definitionBody: sfn.DefinitionBody.fromChainable(definition),
});
step1 = sfn.Pass(self, "Step1")
step2 = sfn.Pass(self, "Step2")
step3 = sfn.Pass(self, "Step3")
step4 = sfn.Pass(self, "Step4")
step5 = sfn.Pass(self, "Step5")
step6 = sfn.Pass(self, "Step6")
step7 = sfn.Pass(self, "Step7")
step8 = sfn.Pass(self, "Step8")
step9 = sfn.Pass(self, "Step9")
step10 = sfn.Pass(self, "Step10")
choice = sfn.Choice(self, "Choice")
condition1 = sfn.Condition.string_equals("$.status", "SUCCESS")
parallel = sfn.Parallel(self, "Parallel")
finish = sfn.Pass(self, "Finish")
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)
sfn.StateMachine(self, "StateMachine",
definition_body=sfn.DefinitionBody.from_chainable(definition)
)
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")
.definitionBody(DefinitionBody.fromChainable(definition))
.build();
var step1 = new Pass(this, "Step1");
var step2 = new Pass(this, "Step2");
var step3 = new Pass(this, "Step3");
var step4 = new Pass(this, "Step4");
var step5 = new Pass(this, "Step5");
var step6 = new Pass(this, "Step6");
var step7 = new Pass(this, "Step7");
var step8 = new Pass(this, "Step8");
var step9 = new Pass(this, "Step9");
var step10 = new Pass(this, "Step10");
var choice = new Choice(this, "Choice");
var condition1 = Condition.StringEquals("$.status", "SUCCESS");
var parallel = new Parallel(this, "Parallel");
var finish = new Pass(this, "Finish");
var 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 StateMachine(this, "StateMachine", new StateMachineProps {
DefinitionBody = DefinitionBody.FromChainable(definition)
});
step1 := sfn.NewPass(this, jsii.String("Step1"))
step2 := sfn.NewPass(this, jsii.String("Step2"))
step3 := sfn.NewPass(this, jsii.String("Step3"))
step4 := sfn.NewPass(this, jsii.String("Step4"))
step5 := sfn.NewPass(this, jsii.String("Step5"))
step6 := sfn.NewPass(this, jsii.String("Step6"))
step7 := sfn.NewPass(this, jsii.String("Step7"))
step8 := sfn.NewPass(this, jsii.String("Step8"))
step9 := sfn.NewPass(this, jsii.String("Step9"))
step10 := sfn.NewPass(this, jsii.String("Step10"))
choice := sfn.NewChoice(this, jsii.String("Choice"))
condition1 := sfn.Condition_StringEquals(jsii.String("$.status"), jsii.String("SUCCESS"))
parallel := sfn.NewParallel(this, jsii.String("Parallel"))
finish := sfn.NewPass(this, jsii.String("Finish"))
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)
sfn.NewStateMachine(this, jsii.String("StateMachine"), &StateMachineProps{
DefinitionBody: sfn.DefinitionBody_FromChainable(definition),
})
If you don't like the visual look of starting a chain directly off the first step, you can use 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)
// ...
step1 = sfn.Pass(self, "Step1")
step2 = sfn.Pass(self, "Step2")
step3 = sfn.Pass(self, "Step3")
definition = sfn.Chain.start(step1).next(step2).next(step3)
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);
var step1 = new Pass(this, "Step1");
var step2 = new Pass(this, "Step2");
var step3 = new Pass(this, "Step3");
var definition = Chain.Start(step1).Next(step2).Next(step3);
step1 := sfn.NewPass(this, jsii.String("Step1"))
step2 := sfn.NewPass(this, jsii.String("Step2"))
step3 := sfn.NewPass(this, jsii.String("Step3"))
definition := sfn.Chain_Start(step1).Next(step2).Next(step3)
Task Credentials
Tasks are executed using the State Machine's execution role. In some cases, e.g. cross-account access, an IAM role can be assumed by the State Machine's execution role to provide access to the resource. This can be achieved by providing the optional credentials property which allows using a fixed role or a json expression to resolve the role at runtime from the task's inputs.
import * as lambda from 'aws-cdk-lib/aws-lambda';
declare const submitLambda: lambda.Function;
declare const iamRole: iam.Role;
// use a fixed role for all task invocations
const role = sfn.TaskRole.fromRole(iamRole);
// or use a json expression to resolve the role at runtime based on task inputs
//const role = sfn.TaskRole.fromRoleArnJsonPath('$.RoleArn');
const submitJob = new tasks.LambdaInvoke(this, 'Submit Job', {
lambdaFunction: submitLambda,
outputPath: '$.Payload',
// use credentials
credentials: { role },
});
import aws_cdk.aws_lambda as lambda_
# submit_lambda: lambda.Function
# iam_role: iam.Role
# use a fixed role for all task invocations
role = sfn.TaskRole.from_role(iam_role)
# or use a json expression to resolve the role at runtime based on task inputs
# const role = sfn.TaskRole.fromRoleArnJsonPath('$.RoleArn');
submit_job = tasks.LambdaInvoke(self, "Submit Job",
lambda_function=submit_lambda,
output_path="$.Payload",
# use credentials
credentials=sfn.Credentials(role=role)
)
import software.amazon.awscdk.services.lambda.*;
Function submitLambda;
Role iamRole;
// use a fixed role for all task invocations
TaskRole role = TaskRole.fromRole(iamRole);
// or use a json expression to resolve the role at runtime based on task inputs
//const role = sfn.TaskRole.fromRoleArnJsonPath('$.RoleArn');
LambdaInvoke submitJob = LambdaInvoke.Builder.create(this, "Submit Job")
.lambdaFunction(submitLambda)
.outputPath("$.Payload")
// use credentials
.credentials(Credentials.builder().role(role).build())
.build();
using Amazon.CDK.AWS.Lambda;
Function submitLambda;
Role iamRole;
// use a fixed role for all task invocations
var role = TaskRole.FromRole(iamRole);
// or use a json expression to resolve the role at runtime based on task inputs
//const role = sfn.TaskRole.fromRoleArnJsonPath('$.RoleArn');
var submitJob = new LambdaInvoke(this, "Submit Job", new LambdaInvokeProps {
LambdaFunction = submitLambda,
OutputPath = "$.Payload",
// use credentials
Credentials = new Credentials { Role = role }
});
import lambda "github.com/aws/aws-cdk-go/awscdk"
var submitLambda Function
var iamRole Role
// use a fixed role for all task invocations
role := sfn.TaskRole_FromRole(iamRole)
// or use a json expression to resolve the role at runtime based on task inputs
//const role = sfn.TaskRole.fromRoleArnJsonPath('$.RoleArn');
submitJob := tasks.NewLambdaInvoke(this, jsii.String("Submit Job"), &LambdaInvokeProps{
LambdaFunction: submitLambda,
OutputPath: jsii.String("$.Payload"),
// use credentials
Credentials: &Credentials{
Role: *Role,
},
})
See the AWS documentation to learn more about AWS Step Functions support for accessing resources in other AWS accounts.
Service Integration Patterns
AWS Step functions integrate directly with other services, either through an optimised integration pattern, or through the AWS SDK. Therefore, it is possible to change the integrationPattern of services, to enable additional functionality of the said AWS Service:
import * as glue from "aws-cdk-lib/aws-glue";
declare const submitGlue: glue.Job;
const submitJob = new tasks.GlueStartJobRun(this, "Submit Job", {
glueJobName: submitGlue.jobName,
integrationPattern: sfn.IntegrationPattern.RUN_JOB,
});
import aws_cdk.aws_glue as glue
# submit_glue: glue.Job
submit_job = tasks.GlueStartJobRun(self, "Submit Job",
glue_job_name=submit_glue.job_name,
integration_pattern=sfn.IntegrationPattern.RUN_JOB
)
import software.amazon.awscdk.services.glue.*;
Job submitGlue;
GlueStartJobRun submitJob = GlueStartJobRun.Builder.create(this, "Submit Job")
.glueJobName(submitGlue.getJobName())
.integrationPattern(IntegrationPattern.RUN_JOB)
.build();
using Amazon.CDK.AWS.Glue;
Job submitGlue;
var submitJob = new GlueStartJobRun(this, "Submit Job", new GlueStartJobRunProps {
GlueJobName = submitGlue.JobName,
IntegrationPattern = IntegrationPattern.RUN_JOB
});
import glue "github.com/aws/aws-cdk-go/awscdk"
var submitGlue Job
submitJob := tasks.NewGlueStartJobRun(this, jsii.String("Submit Job"), &GlueStartJobRunProps{
GlueJobName: submitGlue.JobName,
IntegrationPattern: sfn.IntegrationPattern_RUN_JOB,
})
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:
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:
import { Stack } from 'aws-cdk-lib';
import { Construct } from 'constructs';
import * as sfn from 'aws-cdk-lib/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', {
definitionBody: sfn.DefinitionBody.fromChainable(parallel),
});
}
}
from aws_cdk import Stack
from constructs import Construct
import aws_cdk.aws_stepfunctions as sfn
class MyJob(sfn.StateMachineFragment):
def __init__(self, parent, id, *, jobFlavor):
super().__init__(parent, id)
choice = sfn.Choice(self, "Choice").when(sfn.Condition.string_equals("$.branch", "left"), sfn.Pass(self, "Left Branch")).when(sfn.Condition.string_equals("$.branch", "right"), sfn.Pass(self, "Right Branch"))
# ...
self.start_state = choice
self.end_states = choice.afterwards().end_states
class MyStack(Stack):
def __init__(self, scope, id):
super().__init__(scope, id)
# Do 3 different variants of MyJob in parallel
parallel = sfn.Parallel(self, "All jobs").branch(MyJob(self, "Quick", job_flavor="quick").prefix_states()).branch(MyJob(self, "Medium", job_flavor="medium").prefix_states()).branch(MyJob(self, "Slow", job_flavor="slow").prefix_states())
sfn.StateMachine(self, "MyStateMachine",
definition_body=sfn.DefinitionBody.from_chainable(parallel)
)
import software.amazon.awscdk.Stack;
import software.constructs.Construct;
import software.amazon.awscdk.services.stepfunctions.*;
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
Parallel 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());
StateMachine.Builder.create(this, "MyStateMachine")
.definitionBody(DefinitionBody.fromChainable(parallel))
.build();
}
}
using Amazon.CDK;
using Constructs;
using Amazon.CDK.AWS.StepFunctions;
class MyJobProps
{
public string JobFlavor { get; set; }
}
class MyJob : StateMachineFragment
{
public State StartState { get; }
public INextable[] EndStates { get; }
public MyJob(Construct parent, string id, MyJobProps props) : base(parent, id)
{
var 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"));
// ...
StartState = choice;
EndStates = choice.Afterwards().EndStates;
}
}
class MyStack : Stack
{
public MyStack(Construct scope, string id) : base(scope, id)
{
// Do 3 different variants of MyJob in parallel
var 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());
new StateMachine(this, "MyStateMachine", new StateMachineProps {
DefinitionBody = DefinitionBody.FromChainable(parallel)
});
}
}
import "github.com/aws/aws-cdk-go/awscdk"
import "github.com/aws/constructs-go/constructs"
import "github.com/aws/aws-cdk-go/awscdk"
type myJobProps struct {
jobFlavor *string
}
type myJob struct {
StateMachineFragment
startState State
endStates []INextable
}
func newMyJob(parent Construct, id *string, props myJobProps) *myJob {
this := &myJob{}
sfn.NewStateMachineFragment_Override(this, parent, id)
choice := sfn.NewChoice(this, jsii.String("Choice")).When(sfn.Condition_StringEquals(jsii.String("$.branch"), jsii.String("left")), sfn.NewPass(this, jsii.String("Left Branch"))).When(sfn.Condition_StringEquals(jsii.String("$.branch"), jsii.String("right")), sfn.NewPass(this, jsii.String("Right Branch")))
// ...
this.startState = choice
this.endStates = choice.Afterwards().EndStates
return this
}
type myStack struct {
Stack
}
func newMyStack(scope Construct, id *string) *myStack {
this := &myStack{}
newStack_Override(this, scope, id)
// Do 3 different variants of MyJob in parallel
parallel := sfn.NewParallel(this, jsii.String("All jobs")).Branch(NewMyJob(this, jsii.String("Quick"), &myJobProps{
jobFlavor: jsii.String("quick"),
}).PrefixStates()).Branch(NewMyJob(this, jsii.String("Medium"), &myJobProps{
jobFlavor: jsii.String("medium"),
}).PrefixStates()).Branch(NewMyJob(this, jsii.String("Slow"), &myJobProps{
jobFlavor: jsii.String("slow"),
}).PrefixStates())
sfn.NewStateMachine(this, jsii.String("MyStateMachine"), &StateMachineProps{
DefinitionBody: sfn.DefinitionBody_FromChainable(parallel),
})
return this
}
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.
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:
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 });
activity = sfn.Activity(self, "Activity")
# Read this CloudFormation Output from your application and use it to poll for work on
# the activity.
CfnOutput(self, "ActivityArn", value=activity.activity_arn)
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();
var 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.
new CfnOutput(this, "ActivityArn", new CfnOutputProps { Value = activity.ActivityArn });
activity := sfn.NewActivity(this, jsii.String("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.
awscdk.NewCfnOutput(this, jsii.String("ActivityArn"), &CfnOutputProps{
Value: activity.activityArn,
})
Activity-Level Permissions
Granting IAM permissions to an activity can be achieved by calling the 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');
activity = sfn.Activity(self, "Activity")
role = iam.Role(self, "Role",
assumed_by=iam.ServicePrincipal("lambda.amazonaws.com")
)
activity.grant(role, "states:SendTaskSuccess")
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");
var activity = new Activity(this, "Activity");
var role = new Role(this, "Role", new RoleProps {
AssumedBy = new ServicePrincipal("lambda.amazonaws.com")
});
activity.Grant(role, "states:SendTaskSuccess");
activity := sfn.NewActivity(this, jsii.String("Activity"))
role := iam.NewRole(this, jsii.String("Role"), &RoleProps{
AssumedBy: iam.NewServicePrincipal(jsii.String("lambda.amazonaws.com")),
})
activity.Grant(role, jsii.String("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:
declare const task: sfn.Task;
new cloudwatch.Alarm(this, 'TaskAlarm', {
metric: task.metricFailed(),
threshold: 1,
evaluationPeriods: 1,
});
# task: sfn.Task
cloudwatch.Alarm(self, "TaskAlarm",
metric=task.metric_failed(),
threshold=1,
evaluation_periods=1
)
Task task;
Alarm.Builder.create(this, "TaskAlarm")
.metric(task.metricFailed())
.threshold(1)
.evaluationPeriods(1)
.build();
Task task;
new Alarm(this, "TaskAlarm", new AlarmProps {
Metric = task.MetricFailed(),
Threshold = 1,
EvaluationPeriods = 1
});
var task Task
cloudwatch.NewAlarm(this, jsii.String("TaskAlarm"), &AlarmProps{
Metric: task.metricFailed(),
Threshold: jsii.Number(1),
EvaluationPeriods: jsii.Number(1),
})
There are also metrics on the complete state machine:
declare const stateMachine: sfn.StateMachine;
new cloudwatch.Alarm(this, 'StateMachineAlarm', {
metric: stateMachine.metricFailed(),
threshold: 1,
evaluationPeriods: 1,
});
# state_machine: sfn.StateMachine
cloudwatch.Alarm(self, "StateMachineAlarm",
metric=state_machine.metric_failed(),
threshold=1,
evaluation_periods=1
)
StateMachine stateMachine;
Alarm.Builder.create(this, "StateMachineAlarm")
.metric(stateMachine.metricFailed())
.threshold(1)
.evaluationPeriods(1)
.build();
StateMachine stateMachine;
new Alarm(this, "StateMachineAlarm", new AlarmProps {
Metric = stateMachine.MetricFailed(),
Threshold = 1,
EvaluationPeriods = 1
});
var stateMachine StateMachine
cloudwatch.NewAlarm(this, jsii.String("StateMachineAlarm"), &AlarmProps{
Metric: stateMachine.metricFailed(),
Threshold: jsii.Number(1),
EvaluationPeriods: jsii.Number(1),
})
And there are metrics on the capacity of all state machines in your account:
new cloudwatch.Alarm(this, 'ThrottledAlarm', {
metric: sfn.StateTransitionMetric.metricThrottledEvents(),
threshold: 10,
evaluationPeriods: 2,
});
cloudwatch.Alarm(self, "ThrottledAlarm",
metric=sfn.StateTransitionMetric.metric_throttled_events(),
threshold=10,
evaluation_periods=2
)
Alarm.Builder.create(this, "ThrottledAlarm")
.metric(StateTransitionMetric.metricThrottledEvents())
.threshold(10)
.evaluationPeriods(2)
.build();
new Alarm(this, "ThrottledAlarm", new AlarmProps {
Metric = StateTransitionMetric.MetricThrottledEvents(),
Threshold = 10,
EvaluationPeriods = 2
});
cloudwatch.NewAlarm(this, jsii.String("ThrottledAlarm"), &AlarmProps{
Metric: sfn.StateTransitionMetric_MetricThrottledEvents(),
Threshold: jsii.Number(10),
EvaluationPeriods: jsii.Number(2),
})
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.
States.ALL- A wildcard that matches any known error name.States.Runtime- An execution failed due to some exception that could not be processed. Often these are caused by errors at runtime, such as attempting to apply InputPath or OutputPath on a null JSON payload. AStates.Runtimeerror is not retriable, and will always cause the execution to fail. A retry or catch onStates.ALLwill NOT catch States.Runtime errors.States.DataLimitExceeded- A States.DataLimitExceeded exception will be thrown for the following:- When the output of a connector is larger than payload size quota.
- When the output of a state is larger than payload size quota.
- When, after Parameters processing, the input of a state is larger than the payload size quota.
- See the AWS documentation to learn more about AWS Step Functions Quotas.
States.HeartbeatTimeout- A Task state failed to send a heartbeat for a period longer than the HeartbeatSeconds value.States.Timeout- A Task state either ran longer than the TimeoutSeconds value, or failed to send a heartbeat for a period longer than the HeartbeatSeconds value.States.TaskFailed- A Task state failed during the execution. When used in a retry or catch,States.TaskFailedacts as a wildcard that matches any known error name except forStates.Timeout.
Logging
Enable logging to CloudWatch by passing a logging configuration with a destination LogGroup:
import * as logs from 'aws-cdk-lib/aws-logs';
const logGroup = new logs.LogGroup(this, 'MyLogGroup');
const definition = sfn.Chain.start(new sfn.Pass(this, 'Pass'));
new sfn.StateMachine(this, 'MyStateMachine', {
definitionBody: sfn.DefinitionBody.fromChainable(definition),
logs: {
destination: logGroup,
level: sfn.LogLevel.ALL,
},
});
import aws_cdk.aws_logs as logs
log_group = logs.LogGroup(self, "MyLogGroup")
definition = sfn.Chain.start(sfn.Pass(self, "Pass"))
sfn.StateMachine(self, "MyStateMachine",
definition_body=sfn.DefinitionBody.from_chainable(definition),
logs=sfn.LogOptions(
destination=log_group,
level=sfn.LogLevel.ALL
)
)
import software.amazon.awscdk.services.logs.*;
LogGroup logGroup = new LogGroup(this, "MyLogGroup");
Chain definition = Chain.start(new Pass(this, "Pass"));
StateMachine.Builder.create(this, "MyStateMachine")
.definitionBody(DefinitionBody.fromChainable(definition))
.logs(LogOptions.builder()
.destination(logGroup)
.level(LogLevel.ALL)
.build())
.build();
using Amazon.CDK.AWS.Logs;
var logGroup = new LogGroup(this, "MyLogGroup");
var definition = Chain.Start(new Pass(this, "Pass"));
new StateMachine(this, "MyStateMachine", new StateMachineProps {
DefinitionBody = DefinitionBody.FromChainable(definition),
Logs = new LogOptions {
Destination = logGroup,
Level = LogLevel.ALL
}
});
import logs "github.com/aws/aws-cdk-go/awscdk"
logGroup := logs.NewLogGroup(this, jsii.String("MyLogGroup"))
definition := sfn.Chain_Start(sfn.NewPass(this, jsii.String("Pass")))
sfn.NewStateMachine(this, jsii.String("MyStateMachine"), &StateMachineProps{
DefinitionBody: sfn.DefinitionBody_FromChainable(definition),
Logs: &LogOptions{
Destination: logGroup,
Level: sfn.LogLevel_ALL,
},
})
Encryption
You can encrypt your data using a customer managed key for AWS Step Functions state machines and activities. You can configure a symmetric AWS KMS key and data key reuse period when creating or updating a State Machine or when creating an Activity. The execution history and state machine definition will be encrypted with the key applied to the State Machine. Activity inputs will be encrypted with the key applied to the Activity.
Encrypting state machines
You can provide a symmetric KMS key to encrypt the state machine definition and execution history:
import * as kms from 'aws-cdk-lib/aws-kms';
import * as cdk from 'aws-cdk-lib';
const kmsKey = new kms.Key(this, 'Key');
const stateMachine = new sfn.StateMachine(this, 'StateMachineWithCMKEncryptionConfiguration', {
stateMachineName: 'StateMachineWithCMKEncryptionConfiguration',
definitionBody: sfn.DefinitionBody.fromChainable(sfn.Chain.start(new sfn.Pass(this, 'Pass'))),
stateMachineType: sfn.StateMachineType.STANDARD,
encryptionConfiguration: new sfn.CustomerManagedEncryptionConfiguration(kmsKey, cdk.Duration.seconds(60)),
});
import aws_cdk.aws_kms as kms
import aws_cdk as cdk
kms_key = kms.Key(self, "Key")
state_machine = sfn.StateMachine(self, "StateMachineWithCMKEncryptionConfiguration",
state_machine_name="StateMachineWithCMKEncryptionConfiguration",
definition_body=sfn.DefinitionBody.from_chainable(sfn.Chain.start(sfn.Pass(self, "Pass"))),
state_machine_type=sfn.StateMachineType.STANDARD,
encryption_configuration=sfn.CustomerManagedEncryptionConfiguration(kms_key, cdk.Duration.seconds(60))
)
import software.amazon.awscdk.services.kms.*;
import software.amazon.awscdk.*;
Key kmsKey = new Key(this, "Key");
StateMachine stateMachine = StateMachine.Builder.create(this, "StateMachineWithCMKEncryptionConfiguration")
.stateMachineName("StateMachineWithCMKEncryptionConfiguration")
.definitionBody(DefinitionBody.fromChainable(Chain.start(new Pass(this, "Pass"))))
.stateMachineType(StateMachineType.STANDARD)
.encryptionConfiguration(new CustomerManagedEncryptionConfiguration(kmsKey, Duration.seconds(60)))
.build();
using Amazon.CDK.AWS.KMS;
using Amazon.CDK;
var kmsKey = new Key(this, "Key");
var stateMachine = new StateMachine(this, "StateMachineWithCMKEncryptionConfiguration", new StateMachineProps {
StateMachineName = "StateMachineWithCMKEncryptionConfiguration",
DefinitionBody = DefinitionBody.FromChainable(Chain.Start(new Pass(this, "Pass"))),
StateMachineType = StateMachineType.STANDARD,
EncryptionConfiguration = new CustomerManagedEncryptionConfiguration(kmsKey, Duration.Seconds(60))
});
import kms "github.com/aws/aws-cdk-go/awscdk"
import cdk "github.com/aws/aws-cdk-go/awscdk"
kmsKey := kms.NewKey(this, jsii.String("Key"))
stateMachine := sfn.NewStateMachine(this, jsii.String("StateMachineWithCMKEncryptionConfiguration"), &StateMachineProps{
StateMachineName: jsii.String("StateMachineWithCMKEncryptionConfiguration"),
DefinitionBody: sfn.DefinitionBody_FromChainable(sfn.Chain_Start(sfn.NewPass(this, jsii.String("Pass")))),
StateMachineType: sfn.StateMachineType_STANDARD,
EncryptionConfiguration: sfn.NewCustomerManagedEncryptionConfiguration(kmsKey, cdk.Duration_Seconds(jsii.Number(60))),
})
Encrypting state machine logs in Cloud Watch Logs
If a state machine is encrypted with a customer managed key and has logging enabled, its decrypted execution history will be stored in CloudWatch Logs. If you want to encrypt the logs from the state machine using your own KMS key, you can do so by configuring the LogGroup associated with the state machine to use a KMS key.
import * as kms from 'aws-cdk-lib/aws-kms';
import * as cdk from 'aws-cdk-lib';
import * as logs from 'aws-cdk-lib/aws-logs';
const stateMachineKmsKey = new kms.Key(this, 'StateMachine Key');
const logGroupKey = new kms.Key(this, 'LogGroup Key');
/*
Required KMS key policy which allows the CloudWatchLogs service principal to encrypt the entire log group using the
customer managed kms key. See: https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/encrypt-log-data-kms.html#cmk-permissions
*/
logGroupKey.addToResourcePolicy(new cdk.aws_iam.PolicyStatement({
resources: ['*'],
actions: ['kms:Encrypt*', 'kms:Decrypt*', 'kms:ReEncrypt*', 'kms:GenerateDataKey*', 'kms:Describe*'],
principals: [new cdk.aws_iam.ServicePrincipal(`logs.${cdk.Stack.of(this).region}.amazonaws.com`)],
conditions: {
ArnEquals: {
'kms:EncryptionContext:aws:logs:arn': cdk.Stack.of(this).formatArn({
service: 'logs',
resource: 'log-group',
sep: ':',
resourceName: '/aws/vendedlogs/states/MyLogGroup',
}),
},
},
}));
// Create logGroup and provding encryptionKey which will be used to encrypt the log group
const logGroup = new logs.LogGroup(this, 'MyLogGroup', {
logGroupName: '/aws/vendedlogs/states/MyLogGroup',
encryptionKey: logGroupKey,
});
// Create state machine with CustomerManagedEncryptionConfiguration
const stateMachine = new sfn.StateMachine(this, 'StateMachineWithCMKWithCWLEncryption', {
stateMachineName: 'StateMachineWithCMKWithCWLEncryption',
definitionBody: sfn.DefinitionBody.fromChainable(sfn.Chain.start(new sfn.Pass(this, 'PassState', {
result: sfn.Result.fromString('Hello World'),
}))),
stateMachineType: sfn.StateMachineType.STANDARD,
encryptionConfiguration: new sfn.CustomerManagedEncryptionConfiguration(stateMachineKmsKey),
logs: {
destination: logGroup,
level: sfn.LogLevel.ALL,
includeExecutionData: true,
},
});
import aws_cdk.aws_kms as kms
import aws_cdk as cdk
import aws_cdk.aws_logs as logs
state_machine_kms_key = kms.Key(self, "StateMachine Key")
log_group_key = kms.Key(self, "LogGroup Key")
#
# Required KMS key policy which allows the CloudWatchLogs service principal to encrypt the entire log group using the
# customer managed kms key. See: https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/encrypt-log-data-kms.html#cmk-permissions
#
log_group_key.add_to_resource_policy(cdk.aws_iam.PolicyStatement(
resources=["*"],
actions=["kms:Encrypt*", "kms:Decrypt*", "kms:ReEncrypt*", "kms:GenerateDataKey*", "kms:Describe*"],
principals=[cdk.aws_iam.ServicePrincipal(f"logs.{cdk.Stack.of(this).region}.amazonaws.com")],
conditions={
"ArnEquals": {
"kms:EncryptionContext:aws:logs:arn": cdk.Stack.of(self).format_arn(
service="logs",
resource="log-group",
sep=":",
resource_name="/aws/vendedlogs/states/MyLogGroup"
)
}
}
))
# Create logGroup and provding encryptionKey which will be used to encrypt the log group
log_group = logs.LogGroup(self, "MyLogGroup",
log_group_name="/aws/vendedlogs/states/MyLogGroup",
encryption_key=log_group_key
)
# Create state machine with CustomerManagedEncryptionConfiguration
state_machine = sfn.StateMachine(self, "StateMachineWithCMKWithCWLEncryption",
state_machine_name="StateMachineWithCMKWithCWLEncryption",
definition_body=sfn.DefinitionBody.from_chainable(sfn.Chain.start(sfn.Pass(self, "PassState",
result=sfn.Result.from_string("Hello World")
))),
state_machine_type=sfn.StateMachineType.STANDARD,
encryption_configuration=sfn.CustomerManagedEncryptionConfiguration(state_machine_kms_key),
logs=sfn.LogOptions(
destination=log_group,
level=sfn.LogLevel.ALL,
include_execution_data=True
)
)
import software.amazon.awscdk.services.kms.*;
import software.amazon.awscdk.services.iam.*;
import software.amazon.awscdk.services.logs.*;
Key stateMachineKmsKey = new Key(this, "StateMachine Key");
Key logGroupKey = new Key(this, "LogGroup Key");
/*
Required KMS key policy which allows the CloudWatchLogs service principal to encrypt the entire log group using the
customer managed kms key. See: https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/encrypt-log-data-kms.html#cmk-permissions
*/
logGroupKey.addToResourcePolicy(PolicyStatement.Builder.create()
.resources(List.of("*"))
.actions(List.of("kms:Encrypt*", "kms:Decrypt*", "kms:ReEncrypt*", "kms:GenerateDataKey*", "kms:Describe*"))
.principals(List.of(new ServicePrincipal(String.format("logs.%s.amazonaws.com", cdk.Stack.of(this).getRegion()))))
.conditions(Map.of(
"ArnEquals", Map.of(
"kms:EncryptionContext:aws:logs:arn", cdk.Stack.of(this).formatArn(ArnComponents.builder()
.service("logs")
.resource("log-group")
.sep(":")
.resourceName("/aws/vendedlogs/states/MyLogGroup")
.build()))))
.build());
// Create logGroup and provding encryptionKey which will be used to encrypt the log group
LogGroup logGroup = LogGroup.Builder.create(this, "MyLogGroup")
.logGroupName("/aws/vendedlogs/states/MyLogGroup")
.encryptionKey(logGroupKey)
.build();
// Create state machine with CustomerManagedEncryptionConfiguration
StateMachine stateMachine = StateMachine.Builder.create(this, "StateMachineWithCMKWithCWLEncryption")
.stateMachineName("StateMachineWithCMKWithCWLEncryption")
.definitionBody(DefinitionBody.fromChainable(Chain.start(Pass.Builder.create(this, "PassState")
.result(Result.fromString("Hello World"))
.build())))
.stateMachineType(StateMachineType.STANDARD)
.encryptionConfiguration(new CustomerManagedEncryptionConfiguration(stateMachineKmsKey))
.logs(LogOptions.builder()
.destination(logGroup)
.level(LogLevel.ALL)
.includeExecutionData(true)
.build())
.build();
using Amazon.CDK.AWS.KMS;
using Amazon.CDK;
using Amazon.CDK.AWS.Logs;
var stateMachineKmsKey = new Key(this, "StateMachine Key");
var logGroupKey = new Key(this, "LogGroup Key");
/*
Required KMS key policy which allows the CloudWatchLogs service principal to encrypt the entire log group using the
customer managed kms key. See: https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/encrypt-log-data-kms.html#cmk-permissions
*/
logGroupKey.AddToResourcePolicy(new Aws_iam.PolicyStatement(new PolicyStatementProps {
Resources = new [] { "*" },
Actions = new [] { "kms:Encrypt*", "kms:Decrypt*", "kms:ReEncrypt*", "kms:GenerateDataKey*", "kms:Describe*" },
Principals = new [] { new Aws_iam.ServicePrincipal($"logs.{cdk.Stack.of(this).region}.amazonaws.com") },
Conditions = new Dictionary<string, object> {
{ "ArnEquals", new Dictionary<string, string> {
{ "kms:EncryptionContext:aws:logs:arn", Stack.Of(this).FormatArn(new ArnComponents {
Service = "logs",
Resource = "log-group",
Sep = ":",
ResourceName = "/aws/vendedlogs/states/MyLogGroup"
}) }
} }
}
}));
// Create logGroup and provding encryptionKey which will be used to encrypt the log group
var logGroup = new LogGroup(this, "MyLogGroup", new LogGroupProps {
LogGroupName = "/aws/vendedlogs/states/MyLogGroup",
EncryptionKey = logGroupKey
});
// Create state machine with CustomerManagedEncryptionConfiguration
var stateMachine = new StateMachine(this, "StateMachineWithCMKWithCWLEncryption", new StateMachineProps {
StateMachineName = "StateMachineWithCMKWithCWLEncryption",
DefinitionBody = DefinitionBody.FromChainable(Chain.Start(new Pass(this, "PassState", new PassProps {
Result = Result.FromString("Hello World")
}))),
StateMachineType = StateMachineType.STANDARD,
EncryptionConfiguration = new CustomerManagedEncryptionConfiguration(stateMachineKmsKey),
Logs = new LogOptions {
Destination = logGroup,
Level = LogLevel.ALL,
IncludeExecutionData = true
}
});
import "github.com/aws/aws-cdk-go/awscdk"
import "github.com/aws/aws-cdk-go/awscdk"
import logs "github.com/aws/aws-cdk-go/awscdk"
stateMachineKmsKey := kms.NewKey(this, jsii.String("StateMachine Key"))
logGroupKey := kms.NewKey(this, jsii.String("LogGroup Key"))
/*
Required KMS key policy which allows the CloudWatchLogs service principal to encrypt the entire log group using the
customer managed kms key. See: https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/encrypt-log-data-kms.html#cmk-permissions
*/
logGroupKey.addToResourcePolicy(aws_iam.NewPolicyStatement(&PolicyStatementProps{
Resources: []*string{
jsii.String("*"),
},
Actions: []*string{
jsii.String("kms:Encrypt*"),
jsii.String("kms:Decrypt*"),
jsii.String("kms:ReEncrypt*"),
jsii.String("kms:GenerateDataKey*"),
jsii.String("kms:Describe*"),
},
Principals: []IPrincipal{
aws_iam.NewServicePrincipal(fmt.Sprintf("logs.%v.amazonaws.com", cdk.Stack_Of(this).Region)),
},
Conditions: map[string]interface{}{
"ArnEquals": map[string]*string{
"kms:EncryptionContext:aws:logs:arn": cdk.Stack_*Of(this).formatArn(&ArnComponents{
"service": jsii.String("logs"),
"resource": jsii.String("log-group"),
"sep": jsii.String(":"),
"resourceName": jsii.String("/aws/vendedlogs/states/MyLogGroup"),
}),
},
},
}))
// Create logGroup and provding encryptionKey which will be used to encrypt the log group
logGroup := logs.NewLogGroup(this, jsii.String("MyLogGroup"), &LogGroupProps{
LogGroupName: jsii.String("/aws/vendedlogs/states/MyLogGroup"),
EncryptionKey: logGroupKey,
})
// Create state machine with CustomerManagedEncryptionConfiguration
stateMachine := sfn.NewStateMachine(this, jsii.String("StateMachineWithCMKWithCWLEncryption"), &StateMachineProps{
StateMachineName: jsii.String("StateMachineWithCMKWithCWLEncryption"),
DefinitionBody: sfn.DefinitionBody_FromChainable(sfn.Chain_Start(sfn.NewPass(this, jsii.String("PassState"), &PassProps{
Result: sfn.Result_FromString(jsii.String("Hello World")),
}))),
StateMachineType: sfn.StateMachineType_STANDARD,
EncryptionConfiguration: sfn.NewCustomerManagedEncryptionConfiguration(stateMachineKmsKey),
Logs: &LogOptions{
Destination: logGroup,
Level: sfn.LogLevel_ALL,
IncludeExecutionData: jsii.Boolean(true),
},
})
Encrypting activity inputs
When you provide a symmetric KMS key, all inputs from the Step Functions Activity will be encrypted using the provided KMS key:
import * as kms from 'aws-cdk-lib/aws-kms';
import * as cdk from 'aws-cdk-lib';
const kmsKey = new kms.Key(this, 'Key');
const activity = new sfn.Activity(this, 'ActivityWithCMKEncryptionConfiguration', {
activityName: 'ActivityWithCMKEncryptionConfiguration',
encryptionConfiguration: new sfn.CustomerManagedEncryptionConfiguration(kmsKey, cdk.Duration.seconds(75))
});
import aws_cdk.aws_kms as kms
import aws_cdk as cdk
kms_key = kms.Key(self, "Key")
activity = sfn.Activity(self, "ActivityWithCMKEncryptionConfiguration",
activity_name="ActivityWithCMKEncryptionConfiguration",
encryption_configuration=sfn.CustomerManagedEncryptionConfiguration(kms_key, cdk.Duration.seconds(75))
)
import software.amazon.awscdk.services.kms.*;
import software.amazon.awscdk.*;
Key kmsKey = new Key(this, "Key");
Activity activity = Activity.Builder.create(this, "ActivityWithCMKEncryptionConfiguration")
.activityName("ActivityWithCMKEncryptionConfiguration")
.encryptionConfiguration(new CustomerManagedEncryptionConfiguration(kmsKey, Duration.seconds(75)))
.build();
using Amazon.CDK.AWS.KMS;
using Amazon.CDK;
var kmsKey = new Key(this, "Key");
var activity = new Activity(this, "ActivityWithCMKEncryptionConfiguration", new ActivityProps {
ActivityName = "ActivityWithCMKEncryptionConfiguration",
EncryptionConfiguration = new CustomerManagedEncryptionConfiguration(kmsKey, Duration.Seconds(75))
});
import kms "github.com/aws/aws-cdk-go/awscdk"
import cdk "github.com/aws/aws-cdk-go/awscdk"
kmsKey := kms.NewKey(this, jsii.String("Key"))
activity := sfn.NewActivity(this, jsii.String("ActivityWithCMKEncryptionConfiguration"), &ActivityProps{
ActivityName: jsii.String("ActivityWithCMKEncryptionConfiguration"),
EncryptionConfiguration: sfn.NewCustomerManagedEncryptionConfiguration(kmsKey, cdk.Duration_Seconds(jsii.Number(75))),
})
Changing Encryption
If you want to switch encryption from a customer provided key to a Step Functions owned key or vice-versa you must explicitly provide encryptionConfiguration?
Example: Switching from a customer managed key to a Step Functions owned key for StateMachine
Before
import * as kms from 'aws-cdk-lib/aws-kms';
import * as cdk from 'aws-cdk-lib';
const kmsKey = new kms.Key(this, 'Key');
const stateMachine = new sfn.StateMachine(this, 'StateMachine', {
stateMachineName: 'StateMachine',
definitionBody: sfn.DefinitionBody.fromChainable(sfn.Chain.start(new sfn.Pass(this, 'Pass'))),
stateMachineType: sfn.StateMachineType.STANDARD,
encryptionConfiguration: new sfn.CustomerManagedEncryptionConfiguration(kmsKey, cdk.Duration.seconds(60)),
});
import aws_cdk.aws_kms as kms
import aws_cdk as cdk
kms_key = kms.Key(self, "Key")
state_machine = sfn.StateMachine(self, "StateMachine",
state_machine_name="StateMachine",
definition_body=sfn.DefinitionBody.from_chainable(sfn.Chain.start(sfn.Pass(self, "Pass"))),
state_machine_type=sfn.StateMachineType.STANDARD,
encryption_configuration=sfn.CustomerManagedEncryptionConfiguration(kms_key, cdk.Duration.seconds(60))
)
import software.amazon.awscdk.services.kms.*;
import software.amazon.awscdk.*;
Key kmsKey = new Key(this, "Key");
StateMachine stateMachine = StateMachine.Builder.create(this, "StateMachine")
.stateMachineName("StateMachine")
.definitionBody(DefinitionBody.fromChainable(Chain.start(new Pass(this, "Pass"))))
.stateMachineType(StateMachineType.STANDARD)
.encryptionConfiguration(new CustomerManagedEncryptionConfiguration(kmsKey, Duration.seconds(60)))
.build();
using Amazon.CDK.AWS.KMS;
using Amazon.CDK;
var kmsKey = new Key(this, "Key");
var stateMachine = new StateMachine(this, "StateMachine", new StateMachineProps {
StateMachineName = "StateMachine",
DefinitionBody = DefinitionBody.FromChainable(Chain.Start(new Pass(this, "Pass"))),
StateMachineType = StateMachineType.STANDARD,
EncryptionConfiguration = new CustomerManagedEncryptionConfiguration(kmsKey, Duration.Seconds(60))
});
import kms "github.com/aws/aws-cdk-go/awscdk"
import cdk "github.com/aws/aws-cdk-go/awscdk"
kmsKey := kms.NewKey(this, jsii.String("Key"))
stateMachine := sfn.NewStateMachine(this, jsii.String("StateMachine"), &StateMachineProps{
StateMachineName: jsii.String("StateMachine"),
DefinitionBody: sfn.DefinitionBody_FromChainable(sfn.Chain_Start(sfn.NewPass(this, jsii.String("Pass")))),
StateMachineType: sfn.StateMachineType_STANDARD,
EncryptionConfiguration: sfn.NewCustomerManagedEncryptionConfiguration(kmsKey, cdk.Duration_Seconds(jsii.Number(60))),
})
After
const stateMachine = new sfn.StateMachine(this, 'StateMachine', {
stateMachineName: 'StateMachine',
definitionBody: sfn.DefinitionBody.fromChainable(sfn.Chain.start(new sfn.Pass(this, 'Pass'))),
stateMachineType: sfn.StateMachineType.STANDARD,
encryptionConfiguration: new sfn.AwsOwnedEncryptionConfiguration(),
});
state_machine = sfn.StateMachine(self, "StateMachine",
state_machine_name="StateMachine",
definition_body=sfn.DefinitionBody.from_chainable(sfn.Chain.start(sfn.Pass(self, "Pass"))),
state_machine_type=sfn.StateMachineType.STANDARD,
encryption_configuration=sfn.AwsOwnedEncryptionConfiguration()
)
StateMachine stateMachine = StateMachine.Builder.create(this, "StateMachine")
.stateMachineName("StateMachine")
.definitionBody(DefinitionBody.fromChainable(Chain.start(new Pass(this, "Pass"))))
.stateMachineType(StateMachineType.STANDARD)
.encryptionConfiguration(new AwsOwnedEncryptionConfiguration())
.build();
var stateMachine = new StateMachine(this, "StateMachine", new StateMachineProps {
StateMachineName = "StateMachine",
DefinitionBody = DefinitionBody.FromChainable(Chain.Start(new Pass(this, "Pass"))),
StateMachineType = StateMachineType.STANDARD,
EncryptionConfiguration = new AwsOwnedEncryptionConfiguration()
});
stateMachine := sfn.NewStateMachine(this, jsii.String("StateMachine"), &StateMachineProps{
StateMachineName: jsii.String("StateMachine"),
DefinitionBody: sfn.DefinitionBody_FromChainable(sfn.Chain_Start(sfn.NewPass(this, jsii.String("Pass")))),
StateMachineType: sfn.StateMachineType_STANDARD,
EncryptionConfiguration: sfn.NewAwsOwnedEncryptionConfiguration(),
})
X-Ray tracing
Enable X-Ray tracing for StateMachine:
const definition = sfn.Chain.start(new sfn.Pass(this, 'Pass'));
new sfn.StateMachine(this, 'MyStateMachine', {
definitionBody: sfn.DefinitionBody.fromChainable(definition),
tracingEnabled: true,
});
definition = sfn.Chain.start(sfn.Pass(self, "Pass"))
sfn.StateMachine(self, "MyStateMachine",
definition_body=sfn.DefinitionBody.from_chainable(definition),
tracing_enabled=True
)
Chain definition = Chain.start(new Pass(this, "Pass"));
StateMachine.Builder.create(this, "MyStateMachine")
.definitionBody(DefinitionBody.fromChainable(definition))
.tracingEnabled(true)
.build();
var definition = Chain.Start(new Pass(this, "Pass"));
new StateMachine(this, "MyStateMachine", new StateMachineProps {
DefinitionBody = DefinitionBody.FromChainable(definition),
TracingEnabled = true
});
definition := sfn.Chain_Start(sfn.NewPass(this, jsii.String("Pass")))
sfn.NewStateMachine(this, jsii.String("MyStateMachine"), &StateMachineProps{
DefinitionBody: sfn.DefinitionBody_FromChainable(definition),
TracingEnabled: jsii.Boolean(true),
})
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:
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.grantRedriveExecution(principal)- grants the principal permission to redrive the executions of the state machinestateMachine.grant(principal, actions)- grants the principal state-machine-level permissions for the IAM actions specified
Start Execution Permission
Grant permission to start an execution of a state machine by calling the 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', {
definitionBody: sfn.DefinitionBody.fromChainable(definition),
});
// Give role permission to start execution of state machine
stateMachine.grantStartExecution(role);
# definition: sfn.IChainable
role = iam.Role(self, "Role",
assumed_by=iam.ServicePrincipal("lambda.amazonaws.com")
)
state_machine = sfn.StateMachine(self, "StateMachine",
definition_body=sfn.DefinitionBody.from_chainable(definition)
)
# Give role permission to start execution of state machine
state_machine.grant_start_execution(role)
IChainable definition;
Role role = Role.Builder.create(this, "Role")
.assumedBy(new ServicePrincipal("lambda.amazonaws.com"))
.build();
StateMachine stateMachine = StateMachine.Builder.create(this, "StateMachine")
.definitionBody(DefinitionBody.fromChainable(definition))
.build();
// Give role permission to start execution of state machine
stateMachine.grantStartExecution(role);
IChainable definition;
var role = new Role(this, "Role", new RoleProps {
AssumedBy = new ServicePrincipal("lambda.amazonaws.com")
});
var stateMachine = new StateMachine(this, "StateMachine", new StateMachineProps {
DefinitionBody = DefinitionBody.FromChainable(definition)
});
// Give role permission to start execution of state machine
stateMachine.GrantStartExecution(role);
var definition IChainable
role := iam.NewRole(this, jsii.String("Role"), &RoleProps{
AssumedBy: iam.NewServicePrincipal(jsii.String("lambda.amazonaws.com")),
})
stateMachine := sfn.NewStateMachine(this, jsii.String("StateMachine"), &StateMachineProps{
DefinitionBody: sfn.DefinitionBody_FromChainable(definition),
})
// 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
Read Permissions
Grant read access to a state machine by calling the 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', {
definitionBody: sfn.DefinitionBody.fromChainable(definition),
});
// Give role read access to state machine
stateMachine.grantRead(role);
# definition: sfn.IChainable
role = iam.Role(self, "Role",
assumed_by=iam.ServicePrincipal("lambda.amazonaws.com")
)
state_machine = sfn.StateMachine(self, "StateMachine",
definition_body=sfn.DefinitionBody.from_chainable(definition)
)
# Give role read access to state machine
state_machine.grant_read(role)
IChainable definition;
Role role = Role.Builder.create(this, "Role")
.assumedBy(new ServicePrincipal("lambda.amazonaws.com"))
.build();
StateMachine stateMachine = StateMachine.Builder.create(this, "StateMachine")
.definitionBody(DefinitionBody.fromChainable(definition))
.build();
// Give role read access to state machine
stateMachine.grantRead(role);
IChainable definition;
var role = new Role(this, "Role", new RoleProps {
AssumedBy = new ServicePrincipal("lambda.amazonaws.com")
});
var stateMachine = new StateMachine(this, "StateMachine", new StateMachineProps {
DefinitionBody = DefinitionBody.FromChainable(definition)
});
// Give role read access to state machine
stateMachine.GrantRead(role);
var definition IChainable
role := iam.NewRole(this, jsii.String("Role"), &RoleProps{
AssumedBy: iam.NewServicePrincipal(jsii.String("lambda.amazonaws.com")),
})
stateMachine := sfn.NewStateMachine(this, jsii.String("StateMachine"), &StateMachineProps{
DefinitionBody: sfn.DefinitionBody_FromChainable(definition),
})
// 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*
Task Response Permissions
Grant permission to allow task responses to a state machine by calling the 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', {
definitionBody: sfn.DefinitionBody.fromChainable(definition),
});
// Give role task response permissions to the state machine
stateMachine.grantTaskResponse(role);
# definition: sfn.IChainable
role = iam.Role(self, "Role",
assumed_by=iam.ServicePrincipal("lambda.amazonaws.com")
)
state_machine = sfn.StateMachine(self, "StateMachine",
definition_body=sfn.DefinitionBody.from_chainable(definition)
)
# Give role task response permissions to the state machine
state_machine.grant_task_response(role)
IChainable definition;
Role role = Role.Builder.create(this, "Role")
.assumedBy(new ServicePrincipal("lambda.amazonaws.com"))
.build();
StateMachine stateMachine = StateMachine.Builder.create(this, "StateMachine")
.definitionBody(DefinitionBody.fromChainable(definition))
.build();
// Give role task response permissions to the state machine
stateMachine.grantTaskResponse(role);
IChainable definition;
var role = new Role(this, "Role", new RoleProps {
AssumedBy = new ServicePrincipal("lambda.amazonaws.com")
});
var stateMachine = new StateMachine(this, "StateMachine", new StateMachineProps {
DefinitionBody = DefinitionBody.FromChainable(definition)
});
// Give role task response permissions to the state machine
stateMachine.GrantTaskResponse(role);
var definition IChainable
role := iam.NewRole(this, jsii.String("Role"), &RoleProps{
AssumedBy: iam.NewServicePrincipal(jsii.String("lambda.amazonaws.com")),
})
stateMachine := sfn.NewStateMachine(this, jsii.String("StateMachine"), &StateMachineProps{
DefinitionBody: sfn.DefinitionBody_FromChainable(definition),
})
// 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
Execution-level Permissions
Grant execution-level permissions to a state machine by calling the grantExecution() API:
Redrive Execution Permission
Grant the given identity permission to redrive the execution of the state machine:
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', {
definitionBody: sfn.DefinitionBody.fromChainable(definition),
});
// Give role permission to start execution of state machine
stateMachine.grantStartExecution(role);
// Give role permission to redrive any executions of the state machine
stateMachine.grantRedriveExecution(role);
# definition: sfn.IChainable
role = iam.Role(self, "Role",
assumed_by=iam.ServicePrincipal("lambda.amazonaws.com")
)
state_machine = sfn.StateMachine(self, "StateMachine",
definition_body=sfn.DefinitionBody.from_chainable(definition)
)
# Give role permission to start execution of state machine
state_machine.grant_start_execution(role)
# Give role permission to redrive any executions of the state machine
state_machine.grant_redrive_execution(role)
IChainable definition;
Role role = Role.Builder.create(this, "Role")
.assumedBy(new ServicePrincipal("lambda.amazonaws.com"))
.build();
StateMachine stateMachine = StateMachine.Builder.create(this, "StateMachine")
.definitionBody(DefinitionBody.fromChainable(definition))
.build();
// Give role permission to start execution of state machine
stateMachine.grantStartExecution(role);
// Give role permission to redrive any executions of the state machine
stateMachine.grantRedriveExecution(role);
IChainable definition;
var role = new Role(this, "Role", new RoleProps {
AssumedBy = new ServicePrincipal("lambda.amazonaws.com")
});
var stateMachine = new StateMachine(this, "StateMachine", new StateMachineProps {
DefinitionBody = DefinitionBody.FromChainable(definition)
});
// Give role permission to start execution of state machine
stateMachine.GrantStartExecution(role);
// Give role permission to redrive any executions of the state machine
stateMachine.GrantRedriveExecution(role);
var definition IChainable
role := iam.NewRole(this, jsii.String("Role"), &RoleProps{
AssumedBy: iam.NewServicePrincipal(jsii.String("lambda.amazonaws.com")),
})
stateMachine := sfn.NewStateMachine(this, jsii.String("StateMachine"), &StateMachineProps{
DefinitionBody: sfn.DefinitionBody_FromChainable(definition),
})
// Give role permission to start execution of state machine
stateMachine.grantStartExecution(role)
// Give role permission to redrive any executions of the state machine
stateMachine.grantRedriveExecution(role)
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', {
definitionBody: sfn.DefinitionBody.fromChainable(definition),
});
// Give role permission to get execution history of ALL executions for the state machine
stateMachine.grantExecution(role, 'states:GetExecutionHistory');
# definition: sfn.IChainable
role = iam.Role(self, "Role",
assumed_by=iam.ServicePrincipal("lambda.amazonaws.com")
)
state_machine = sfn.StateMachine(self, "StateMachine",
definition_body=sfn.DefinitionBody.from_chainable(definition)
)
# Give role permission to get execution history of ALL executions for the state machine
state_machine.grant_execution(role, "states:GetExecutionHistory")
IChainable definition;
Role role = Role.Builder.create(this, "Role")
.assumedBy(new ServicePrincipal("lambda.amazonaws.com"))
.build();
StateMachine stateMachine = StateMachine.Builder.create(this, "StateMachine")
.definitionBody(DefinitionBody.fromChainable(definition))
.build();
// Give role permission to get execution history of ALL executions for the state machine
stateMachine.grantExecution(role, "states:GetExecutionHistory");
IChainable definition;
var role = new Role(this, "Role", new RoleProps {
AssumedBy = new ServicePrincipal("lambda.amazonaws.com")
});
var stateMachine = new StateMachine(this, "StateMachine", new StateMachineProps {
DefinitionBody = DefinitionBody.FromChainable(definition)
});
// Give role permission to get execution history of ALL executions for the state machine
stateMachine.GrantExecution(role, "states:GetExecutionHistory");
var definition IChainable
role := iam.NewRole(this, jsii.String("Role"), &RoleProps{
AssumedBy: iam.NewServicePrincipal(jsii.String("lambda.amazonaws.com")),
})
stateMachine := sfn.NewStateMachine(this, jsii.String("StateMachine"), &StateMachineProps{
DefinitionBody: sfn.DefinitionBody_FromChainable(definition),
})
// Give role permission to get execution history of ALL executions for the state machine
stateMachine.grantExecution(role, jsii.String("states:GetExecutionHistory"))
Custom Permissions
You can add any set of permissions to a state machine by calling the grant() API.
const user = new iam.User(this, 'MyUser');
declare const definition: sfn.IChainable;
const stateMachine = new sfn.StateMachine(this, 'StateMachine', {
definitionBody: sfn.DefinitionBody.fromChainable(definition),
});
//give user permission to send task success to the state machine
stateMachine.grant(user, 'states:SendTaskSuccess');
# definition: sfn.IChainable
user = iam.User(self, "MyUser")
state_machine = sfn.StateMachine(self, "StateMachine",
definition_body=sfn.DefinitionBody.from_chainable(definition)
)
# give user permission to send task success to the state machine
state_machine.grant(user, "states:SendTaskSuccess")
IChainable definition;
User user = new User(this, "MyUser");
StateMachine stateMachine = StateMachine.Builder.create(this, "StateMachine")
.definitionBody(DefinitionBody.fromChainable(definition))
.build();
//give user permission to send task success to the state machine
stateMachine.grant(user, "states:SendTaskSuccess");
IChainable definition;
var user = new User(this, "MyUser");
var stateMachine = new StateMachine(this, "StateMachine", new StateMachineProps {
DefinitionBody = DefinitionBody.FromChainable(definition)
});
//give user permission to send task success to the state machine
stateMachine.Grant(user, "states:SendTaskSuccess");
var definition IChainable
user := iam.NewUser(this, jsii.String("MyUser"))
stateMachine := sfn.NewStateMachine(this, jsii.String("StateMachine"), &StateMachineProps{
DefinitionBody: sfn.DefinitionBody_FromChainable(definition),
})
//give user permission to send task success to the state machine
stateMachine.grant(user, jsii.String("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. In addition, the StateMachine can be imported via the StateMachine.fromStateMachineName() method, as long as they are in the same account/region as the current construct.
const app = new App();
const stack = new Stack(app, 'MyStack');
sfn.StateMachine.fromStateMachineArn(
this,
"ViaArnImportedStateMachine",
"arn:aws:states:us-east-1:123456789012:stateMachine:StateMachine2E01A3A5-N5TJppzoevKQ",
);
sfn.StateMachine.fromStateMachineName(
this,
"ViaResourceNameImportedStateMachine",
"StateMachine2E01A3A5-N5TJppzoevKQ",
);
app = App()
stack = Stack(app, "MyStack")
sfn.StateMachine.from_state_machine_arn(self, "ViaArnImportedStateMachine", "arn:aws:states:us-east-1:123456789012:stateMachine:StateMachine2E01A3A5-N5TJppzoevKQ")
sfn.StateMachine.from_state_machine_name(self, "ViaResourceNameImportedStateMachine", "StateMachine2E01A3A5-N5TJppzoevKQ")
App app = new App();
Stack stack = new Stack(app, "MyStack");
StateMachine.fromStateMachineArn(this, "ViaArnImportedStateMachine", "arn:aws:states:us-east-1:123456789012:stateMachine:StateMachine2E01A3A5-N5TJppzoevKQ");
StateMachine.fromStateMachineName(this, "ViaResourceNameImportedStateMachine", "StateMachine2E01A3A5-N5TJppzoevKQ");
var app = new App();
var stack = new Stack(app, "MyStack");
StateMachine.FromStateMachineArn(this, "ViaArnImportedStateMachine", "arn:aws:states:us-east-1:123456789012:stateMachine:StateMachine2E01A3A5-N5TJppzoevKQ");
StateMachine.FromStateMachineName(this, "ViaResourceNameImportedStateMachine", "StateMachine2E01A3A5-N5TJppzoevKQ");
app := awscdk.NewApp()
stack := awscdk.Newstack(app, jsii.String("MyStack"))
sfn.StateMachine_FromStateMachineArn(this, jsii.String("ViaArnImportedStateMachine"), jsii.String("arn:aws:states:us-east-1:123456789012:stateMachine:StateMachine2E01A3A5-N5TJppzoevKQ"))
sfn.StateMachine_FromStateMachineName(this, jsii.String("ViaResourceNameImportedStateMachine"), jsii.String("StateMachine2E01A3A5-N5TJppzoevKQ"))
Types
| Name | Kind | Summary |
|---|---|---|
Activity | Construct (L2) | Define a new Step Functions Activity. |
StateMachine | Construct (L2) | Define a StepFunctions State Machine. |
CfnActivity | Construct (L1) | An activity is a task that you write in any programming language and host on any machine that has access to AWS Step Functions . |
CfnStateMachine | Construct (L1) | Provisions a state machine. |
CfnStateMachineAlias | Construct (L1) | Represents a state machine alias . An alias routes traffic to one or two versions of the same state machine. |
CfnStateMachineVersion | Construct (L1) | Represents a state machine version . A published version uses the latest state machine revision . A revision is an immutable, read-only snapshot of a state machine’s definition and configuration. |
ActivityProps | Struct | Properties for defining a new Step Functions Activity. |
AfterwardsOptions | Struct | Options for selecting the choice paths. |
AssignableStateOptions | Struct | Option properties for state that can assign variables. |
AwsOwnedEncryptionConfiguration | Class | Define a new AwsOwnedEncryptionConfiguration. |
CatchProps | Struct | Error handler details. |
CfnActivity.EncryptionConfigurationProperty | Struct | Settings to configure server-side encryption for an activity. |
CfnActivity.TagsEntryProperty | Struct | The TagsEntry property specifies tags to identify an activity. |
CfnActivityProps | Struct | Properties for defining a CfnActivity. |
CfnStateMachine.CloudWatchLogsLogGroupProperty | Struct | Defines a CloudWatch log group. |
CfnStateMachine.EncryptionConfigurationProperty | Struct | Settings to configure server-side encryption for a state machine. |
CfnStateMachine.LogDestinationProperty | Struct | Defines a destination for LoggingConfiguration . |
CfnStateMachine.LoggingConfigurationProperty | Struct | Defines what execution history events are logged and where they are logged. |
CfnStateMachine.S3LocationProperty | Struct | Defines the S3 bucket location where a state machine definition is stored. |
CfnStateMachine.TagsEntryProperty | Struct | The TagsEntry property specifies tags to identify a state machine. |
CfnStateMachine.TracingConfigurationProperty | Struct | Selects whether or not the state machine's AWS X-Ray tracing is enabled. |
CfnStateMachineAlias.DeploymentPreferenceProperty | Struct | Enables gradual state machine deployments. |
CfnStateMachineAlias.RoutingConfigurationVersionProperty | Struct | The state machine version to which you want to route the execution traffic. |
CfnStateMachineAliasProps | Struct | Properties for defining a CfnStateMachineAlias. |
CfnStateMachineProps | Struct | Properties for defining a CfnStateMachine. |
CfnStateMachineVersionProps | Struct | Properties for defining a CfnStateMachineVersion. |
Chain | Class | A collection of states to chain onto. |
ChainDefinitionBody | Class | |
Choice | Construct | Define a Choice in the state machine. |
ChoiceJsonataProps | Struct | Properties for defining a Choice state that using JSONata. |
ChoiceJsonPathProps | Struct | Properties for defining a Choice state that using JSONPath. |
ChoiceProps | Struct | Properties for defining a Choice state. |
ChoiceTransitionOptions | Struct | Options for Choice Transition. |
Condition | Class | A Condition for use in a Choice state branch. |
Credentials | Struct | Specifies a target role assumed by the State Machine's execution role for invoking the task's resource. |
CsvDelimiter | Enum | Delimiter used in CSV file. |
CsvHeaderLocation | Enum | CSV header location options. |
CsvHeaders | Class | Configuration for CSV header options for a CSV Item Reader. |
CustomerManagedEncryptionConfiguration | Class | Define a new CustomerManagedEncryptionConfiguration. |
CustomState | Construct | State defined by supplying Amazon States Language (ASL) in the state machine. |
CustomStateProps | Struct | Properties for defining a custom state definition. |
DefinitionBody | Class | |
DefinitionConfig | Struct | Partial object from the StateMachine L1 construct properties containing definition information. |
DistributedMap | Construct | Define a Distributed Mode Map state in the state machine. |
DistributedMapJsonataProps | Struct | Properties for configuring a Distribute Map state that using JSONata. |
DistributedMapJsonPathProps | Struct | Properties for configuring a Distribute Map state that using JSONPath. |
DistributedMapProps | Struct | Properties for configuring a Distribute Map state. |
EncryptionConfiguration | Class | Base class for creating an EncryptionConfiguration for either state machines or activities. |
Errors | Class | 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 | Construct | Define a Fail state in the state machine. |
FailJsonataProps | Struct | Properties for defining a Fail state that using JSONata. |
FailJsonPathProps | Struct | Properties for defining a Fail state that using JSONPath. |
FailProps | Struct | Properties for defining a Fail state. |
FieldUtils | Class | Helper functions to work with structures containing fields. |
FileDefinitionBody | Class | |
FindStateOptions | Struct | Options for finding reachable states. |
IActivity | Interface | Represents a Step Functions Activity https://docs.aws.amazon.com/step-functions/latest/dg/concepts-activities.html. |
IChainable | Interface | Interface for objects that can be used in a Chain. |
IItemReader | Interface | Base interface for Item Reader configurations. |
INextable | Interface | Interface for states that can have 'next' states. |
InputType | Enum | The type of task input. |
IntegrationPattern | Enum | AWS Step Functions integrates with services directly in the Amazon States Language. |
IStateMachine | Interface | A State Machine. |
ItemBatcher | Class | Configuration for processing a group of items in a single child workflow execution. |
ItemBatcherProps | Struct | Interface for ItemBatcher configuration properties. |
ItemReaderProps | Struct | Base interface for Item Reader configuration properties. |
JitterType | Enum | Values allowed in the retrier JitterStrategy field. |
JsonataCommonOptions | Struct | Option properties for JSONata state. |
JsonataStateOptions | Struct | Option properties for JSONata task state. |
JsonataStateProps | Struct | Properties shared by all states that use JSONata. |
JsonPath | Class | Extract a field from the State Machine data or context that gets passed around between states. |
JsonPathCommonOptions | Struct | Option properties for JSONPath state. |
JsonPathStateProps | Struct | Properties shared by all states that use JSONPath. |
LogLevel | Enum | Defines which category of execution history events are logged. |
LogOptions | Struct | Defines what execution history events are logged and where they are logged. |
Map | Construct | Define a Map state in the state machine. |
MapBase | Construct | Define a Map state in the state machine. |
MapBaseJsonataOptions | Struct | Base properties for defining a Map state that using JSONata. |
MapBaseJsonPathOptions | Struct | Base properties for defining a Map state that using JSONPath. |
MapBaseOptions | Struct | Base properties for defining a Map state. |
MapBaseProps | Struct | Properties for defining a Map state. |
MapJsonataProps | Struct | Properties for defining a Map state that using JSONata. |
MapJsonPathProps | Struct | Properties for defining a Map state that using JSONPath. |
MapProps | Struct | Properties for defining a Map state. |
OutputType | Enum | The format of the Output of the child workflow executions. |
Parallel | Construct | Define a Parallel state in the state machine. |
ParallelJsonataProps | Struct | Properties for defining a Parallel state that using JSONata. |
ParallelJsonPathProps | Struct | Properties for defining a Parallel state that using JSONPath. |
ParallelProps | Struct | Properties for defining a Parallel state. |
Pass | Construct | Define a Pass in the state machine. |
PassJsonataProps | Struct | Properties for defining a Pass state that using JSONata. |
PassJsonPathProps | Struct | Properties for defining a Pass state that using JSONPath. |
PassProps | Struct | Properties for defining a Pass state. |
ProcessorConfig | Struct | Specifies the configuration for the processor Map state. |
ProcessorMode | Enum | Mode of the Map workflow. |
ProcessorType | Enum | Execution type for the Map workflow. |
ProvideItems | Class | The array that the Map state will iterate over. |
QueryLanguage | Enum | The name of the query language used by the state machine or state. |
Result | Class | The result of a Pass operation. |
ResultWriter | Class | Configuration for writing Distributed Map state results to S3. |
ResultWriterProps | Struct | Interface for Result Writer configuration props. |
ResultWriterV2 | Class | Configuration for writing Distributed Map state results to S3 The ResultWriter field cannot be empty. |
ResultWriterV2Props | Struct | Interface for Result Writer configuration props. |
RetryProps | Struct | Retry details. |
S3CsvItemReader | Class | Item Reader configuration for iterating over items in a CSV file stored in S3. |
S3CsvItemReaderProps | Struct | Properties for configuring an Item Reader that iterates over items in a CSV file in S3. |
S3FileItemReaderProps | Struct | Base interface for Item Reader configuration properties the iterate over entries in a S3 file. |
S3JsonItemReader | Class | Item Reader configuration for iterating over items in a JSON array stored in a S3 file. |
S3JsonLItemReader | Class | Item Reader configuration for iterating over the rows of the JSONL file stored in S3. |
S3ManifestItemReader | Class | Item Reader configuration for iterating over items in a S3 inventory manifest file stored in S3. |
S3ObjectsItemReader | Class | Item Reader configuration for iterating over objects in an S3 bucket. |
S3ObjectsItemReaderProps | Struct | Properties for configuring an Item Reader that iterates over objects in an S3 bucket. |
ServiceIntegrationPattern | Enum | Three ways to call an integrated service: Request Response, Run a Job and Wait for a Callback with Task Token. |
SingleStateOptions | Struct | Options for creating a single state. |
State | Construct | Base class for all other state classes. |
StateBaseProps | Struct | Properties shared by all states. |
StateGraph | Class | A collection of connected states. |
StateMachineFragment | Construct | Base class for reusable state machine fragments. |
StateMachineGrants | Facade | Collection of grant methods for a IStateMachineRef. |
StateMachineGrantsProps | Struct | Properties for StateMachineGrants. |
StateMachineProps | Struct | Properties for defining a State Machine. |
StateMachineType | Enum | Two types of state machines are available in AWS Step Functions: EXPRESS AND STANDARD. |
StateProps | Struct | Properties shared by all states. |
StateTransitionMetric | Class | Metrics on the rate limiting performed on state machine execution. |
StringDefinitionBody | Class | |
Succeed | Construct | Define a Succeed state in the state machine. |
SucceedJsonataProps | Struct | Properties for defining a Succeed state that using JSONata. |
SucceedJsonPathProps | Struct | Properties for defining a Succeed state that using JSONPath. |
SucceedProps | Struct | Properties for defining a Succeed state. |
TaskInput | Class | Type union for task classes that accept multiple types of payload. |
TaskMetricsConfig | Struct | Task Metrics. |
TaskRole | Class | Role to be assumed by the State Machine's execution role for invoking a task's resource. |
TaskStateBase | Construct | Define a Task state in the state machine. |
TaskStateBaseOptions | Struct | Base options for all task states. |
TaskStateBaseProps | Struct | Props that are common to all tasks. |
TaskStateJsonataBaseProps | Struct | Props that are common to all tasks that using JSONata. |
TaskStateJsonPathBaseProps | Struct | Props that are common to all tasks that using JSONPath. |
Timeout | Class | Timeout for a task or heartbeat. |
Transformation | Enum | The transformation to be applied to the Output of the Child Workflow executions. |
Wait | Construct | Define a Wait state in the state machine. |
WaitJsonataProps | Struct | Properties for defining a Wait state that using JSONata. |
WaitJsonPathProps | Struct | Properties for defining a Wait state that using JSONPath. |
WaitProps | Struct | Properties for defining a Wait state. |
WaitTime | Class | Represents the Wait state which delays a state machine from continuing for a specified time. |
WriterConfig | Class | Configuration to format the output. |
WriterConfigProps | Struct | Interface for Writer Config props. |