Skip to content
v2.274.0

Choice ​

Define a Choice in the state machine.

A choice state can be used to make decisions based on the execution state.

Example ​

ts
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);
python
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)
java
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);
csharp
// Install: dotnet add package Amazon.CDK.Lib
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);
go
// Install: go get github.com/aws/aws-cdk-go/awscdk/v2
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)

Initializer ​

ts
new Choice(scope: Construct, id: string, props?: ChoiceProps)
python
Choice(scope: Construct, id: str, props: typing.Optional[ChoiceProps] = None)
java
new Choice(Construct scope, String id, ChoiceProps props)
csharp
new Choice(Construct scope, string id, ChoiceProps? props = null)
go
NewChoice(Scope Construct, Id *string, Props ChoiceProps)

Construct Props ​

assign{ [key: string]: any }assigntyping.Mapping[str, Any]assignMap<String, Object>AssignIDictionary<string, object>Assign*map[string]interface{}= Not assign variables#
Workflow variables to store in this step.

Using workflow variables, you can store data in a step and retrieve that data in future steps.

commentstringcommentstrcommentStringCommentstringComment*string= No comment#
A comment describing this state.
inputPathstringinput_pathstrinputPathStringInputPathstringInputPath*string= $#
JSONPath expression to select part of the state to be the input to this state.

May also be the special value JsonPath.DISCARD, which will cause the effective input to be the empty object {}.

outputPathstringoutput_pathstroutputPathStringOutputPathstringOutputPath*string= $#
JSONPath expression to select part of the state to be the output to this state.

May also be the special value JsonPath.DISCARD, which will cause the effective output to be the empty object {}.

outputsanyoutputsAnyoutputsObjectOutputsobjectOutputsinterface{}= $states.result or $states.errorO…#
Used to specify and transform output from the state.
notes · default

When specified, the value overrides the state output default. The output field accepts any JSON value (object, array, string, number, boolean, null). Any string value, including those inside objects or arrays, will be evaluated as JSONata if surrounded by {% %} characters. Output also accepts a JSONata expression directly.

Default: $states.result or $states.errorOutput

queryLanguageQueryLanguagequery_languageQueryLanguagequeryLanguageQueryLanguageQueryLanguageQueryLanguageQueryLanguageQueryLanguage= JSONPath#
The name of the query language used by the state.

If the state does not contain a queryLanguage field, then it will use the query language specified in the top-level queryLanguage field.

stateNamestringstate_namestrstateNameStringStateNamestringStateName*string= The construct ID will be used as…#
Optional name for this state.
default

Default: The construct ID will be used as state name

Properties ​

endStatesINextable[]end_statestyping.List[INextable]endStatesList<INextable>EndStatesINextable[]EndStates*[]INextablerequired#
Continuable states of this Chainable.
idstringidstridStringIdstringId*stringrequired#
Descriptive identifier for this chainable.
nodeNodenodeNodenodeNodeNodeNodeNodeNoderequired#
The tree node.
startStateStatestart_stateStatestartStateStateStartStateStateStartStateStaterequired#
First state of this Chainable.
stateIdstringstate_idstrstateIdStringStateIdstringStateId*stringrequired#
Tokenized string that evaluates to the state's ID.

Methods ​

addPrefix(x: string): voiddef add_prefix(self, x: str) -> Nonepublic void addPrefix(String x)public void AddPrefix(string x)func AddPrefix(X *string)#
Add a prefix to the stateId of this state.
afterwards(options?: AfterwardsOptions): Chaindef afterwards(self, options: typing.Optional[AfterwardsOptions] = None) -> Chainpublic Chain afterwards(AfterwardsOptions options)public Chain Afterwards(AfterwardsOptions? options = null)func Afterwards(Options AfterwardsOptions) Chain#
Return a Chain that contains all reachable end states from this Choice.

Use this to combine all possible choice paths back.

bindToGraph(graph: StateGraph): voiddef bind_to_graph(self, graph: StateGraph) -> Nonepublic void bindToGraph(StateGraph graph)public void BindToGraph(StateGraph graph)func BindToGraph(Graph StateGraph)#
Register this state as part of the given graph.

Don't call this. It will be called automatically when you work with states normally.

filterNextables(states: State[]): INextable[]@staticmethod def filter_nextables(states: typing.List[State]) -> typing.List[INextable]public static List<INextable> filterNextables(List<State> states)public static INextable[] FilterNextables(State[] states)func FilterNextables(States *[]State) *[]INextablestatic#
Return only the states that allow chaining from an array of states.
findReachableEndStates(start: State, options?: FindStateOptions): State[]@staticmethod def find_reachable_end_states(start: State, options: typing.Optional[FindStateOptions] = None) -> typing.List[State]public static List<State> findReachableEndStates(State start, FindStateOptions options)public static State[] FindReachableEndStates(State start, FindStateOptions? options = null)func FindReachableEndStates(Start State, Options FindStateOptions) *[]Statestatic#
Find the set of end states states reachable through transitions from the given start state.
findReachableStates(start: State, options?: FindStateOptions): State[]@staticmethod def find_reachable_states(start: State, options: typing.Optional[FindStateOptions] = None) -> typing.List[State]public static List<State> findReachableStates(State start, FindStateOptions options)public static State[] FindReachableStates(State start, FindStateOptions? options = null)func FindReachableStates(Start State, Options FindStateOptions) *[]Statestatic#
Find the set of states reachable through transitions from the given start state.

This does not retrieve states from within sub-graphs, such as states within a Parallel state's branch.

isConstruct(x: any): boolean@staticmethod def is_construct(x: Any) -> boolpublic static Boolean isConstruct(Object x)public static bool IsConstruct(object x)func IsConstruct(X interface{}) *boolstatic#
Checks if `x` is a construct.
notes · 1 parameter · returns

Use this method instead of instanceof to properly detect Construct instances, even when the construct library is symlinked.

Explanation: in JavaScript, multiple copies of the constructs library on disk are seen as independent, completely different libraries. As a consequence, the class Construct in each copy of the constructs library is seen as a different class, and an instance of one class will not test as instanceof the other class. npm install will not create installations like this, but users may manually symlink construct libraries together or use a monorepo tool: in those cases, multiple copies of the constructs library can be accidentally installed, and instanceof will behave unpredictably. It is safest to avoid using instanceof, and using this type-testing method instead.

Parameters

  • xxxxX — Any object.

Returns: true if x is an object created from a class which extends Construct.

jsonata(scope: Construct, id: string, props?: ChoiceJsonataProps): Choice // chainable@staticmethod def jsonata(scope: Construct, id: str, props: typing.Optional[ChoiceJsonataProps] = None) -> Choicepublic static Choice jsonata(Construct scope, String id, ChoiceJsonataProps props)public static Choice Jsonata(Construct scope, string id, ChoiceJsonataProps? props = null)func Jsonata(Scope Construct, Id *string, Props ChoiceJsonataProps) Choicestatic#
Define a Choice using JSONata in the state machine.

A choice state can be used to make decisions based on the execution state.

jsonPath(scope: Construct, id: string, props?: ChoiceJsonPathProps): Choice // chainable@staticmethod def json_path(scope: Construct, id: str, props: typing.Optional[ChoiceJsonPathProps] = None) -> Choicepublic static Choice jsonPath(Construct scope, String id, ChoiceJsonPathProps props)public static Choice JsonPath(Construct scope, string id, ChoiceJsonPathProps? props = null)func JsonPath(Scope Construct, Id *string, Props ChoiceJsonPathProps) Choicestatic#
Define a Choice using JSONPath in the state machine.

A choice state can be used to make decisions based on the execution state.

otherwise(def: IChainable): Choice // chainabledef otherwise(self, def: IChainable) -> Choicepublic Choice otherwise(IChainable def)public Choice Otherwise(IChainable def)func Otherwise(Def IChainable) Choice#
If none of the given conditions match, continue execution with the given state.

If no conditions match and no otherwise() has been given, an execution error will be raised.

prefixStates(root: IConstruct, prefix: string): void@staticmethod def prefix_states(root: IConstruct, prefix: str) -> Nonepublic static void prefixStates(IConstruct root, String prefix)public static void PrefixStates(IConstruct root, string prefix)func PrefixStates(Root IConstruct, Prefix *string)static#
Add a prefix to the stateId of all States found in a construct tree.
toStateJson(topLevelQueryLanguage?: QueryLanguage): jsondef to_state_json(self, top_level_query_language: typing.Optional[QueryLanguage] = None) -> Anypublic Object toStateJson(QueryLanguage topLevelQueryLanguage)public object ToStateJson(QueryLanguage? topLevelQueryLanguage = null)func ToStateJson(TopLevelQueryLanguage QueryLanguage) interface{}#
Return the Amazon States Language object for this state.
toString(): stringdef to_string(self, ) -> strpublic String toString()public string ToString()func ToString() *string#
Returns a string representation of this construct.
when(condition: Condition, next: IChainable, options?: ChoiceTransitionOptions): Choice // chainabledef when(self, condition: Condition, next: IChainable, options: typing.Optional[ChoiceTransitionOptions] = None) -> Choicepublic Choice when(Condition condition, IChainable next, ChoiceTransitionOptions options)public Choice When(Condition condition, IChainable next, ChoiceTransitionOptions? options = null)func When(Condition Condition, Next IChainable, Options ChoiceTransitionOptions) Choice#
If the given condition matches, continue execution with the given state.
with(...mixins: IMixin[]): IConstructdef with(self, mixins: IMixin) -> IConstructpublic IConstruct with(IMixin mixins)public IConstruct With(IMixin mixins)func With(Mixins IMixin) IConstruct#
Applies one or more mixins to this construct.

Mixins are applied in order. The list of constructs is captured at the start of the call, so constructs added by a mixin will not be visited. Use multiple with() calls if subsequent mixins should apply to added constructs.

1 parameter · returns

Parameters

  • mixinsmixinsmixinsmixinsMixins — The mixins to apply.

Returns: This construct for chaining