I would like to have a default value for a parameter passed into a step function
e.g.,
"Parameters": {
"foo.$": "$.foo" OR "bar" if "$.foo" not specified
}
is there a way to do this natively with JSONPath or do I have to use a choice + pass state?
I'd even settle for using choice/pass if there were a way to not break when a parameter is not specified in the input.
If I don't include "foo": ""
in the input, I will get an error like "JSONPath ... could not be found in the input."
This answer is meanwhile deprecated (although it might still work). As commented by Buddha, the answer from Brett Ryan uses intrinsic functions which were added later and make the solution much more compact.
I'm solving this using a combination of the Choice
and Pass
states. Given that a state machine at least gets an empty input object, you can check if it has members present using the IsPresent
comparison operator in the Choice
state. If your variable of desire is not present, you can route to a Pass
state to inject a default fallback object.
{
"keyThatMightNotExist": {
"options": {
"foo": "bar",
"baz": false
},
"id": 1234
}
}
{
"Comment": "An example for how to deal with empty input and setting defaults.",
"StartAt": "Choice State: looking for input",
"States": {
"Choice State: looking for input": {
"Type": "Choice",
"Choices": [
{
Checking for existence and if so, also validate a child member:
"And": [
{
"Variable": "$.keyThatMightNotExist",
"IsPresent": true
},
{
"Variable": "$.keyThatMightNotExist.id",
"IsNull": false
}
],
If the key variable is present and its child node "id"
is true
, skip the next state and hop over to the "State that works with $.keyThatMightNotExist"
"Next": "State that works with $.keyThatMightNotExist"
}
],
"Default": "LoadDefaults"
},
The following is where we inject our defaults:
"LoadDefaults": {
"Type": "Pass",
"Result": {
"id": 0,
"text": "not applicable"
},
"ResultPath": "$.keyThatMightNotExist",
"Next": "State that works with $.keyThatMightNotExist"
},
At this point, there is an object to work with. Either from actual input, or by using the defaults:
"State that works with $.keyThatMightNotExist": {
"Type": "Succeed"
}
}
}
For further information, refer to the AWS Step Functions Developer Guide, choice-state-example