AWS EmulatorのStep Functionsで条件分岐する方法
Step Functions の Choice ステートを使うと、前のステートの出力を条件で調べて、次に進むステートを変えられます。合計金額が 5000 円以上なら送料を無料にする、会員なら別の処理にする、のように、ワークフローの中に if 文のような条件分岐を作りたいときに使います。AWS のアカウントは使わず、手元に入れた AWS Emulator で、定義の書き方に加えて、条件の並び順による違い、Default を書かなかったときや入力にない値を調べたときの動きを試しました。コマンドと出力は、そのまま載せています。
検証環境は Ubuntu 24.04.5(x86_64)、AWS Emulator 1.0.624(2026年11月26日リリース、Debian パッケージ)、AWS CLI 2.42.4、Lambda のランタイムは python3.12 です。AWS のアカウントと認証情報は使っていません。本物の AWS Step Functions での動きと料金は確かめておらず、記事で触れるところは公式ドキュメントを出どころにしています。条件を JSONata(Condition)で書く定義、Assign での変数の設定、時刻(Timestamp…)や StringMatches の比べ方、Or と Not、Express ワークフローは試していません。

準備:エミュレーターを起動し、合計を出す関数を作る
AWS Emulator は、公式ガイドにある Linux での入れ方のとおりに、Debian パッケージの署名を gpg で確かめてから入れました。起動は aws-emulator -t off です。-t off は、使用状況のデータ(テレメトリー)を送らない指定です。
AWS CLI は、SDK の接続先をエミュレーターに向ける手順にある環境変数を設定して使っています。入れ方と環境変数の詳しい説明は「AWS EmulatorをUbuntuに入れて使い始める方法」に、Step Functions から Lambda 関数を呼ぶ基本(実行ロールと lambda:InvokeFunction の許可、OutputPath の意味)は「AWS EmulatorのStep Functionsで関数を順に呼ぶ方法」に載せました。この記事でも同じように、Lambda 関数用のロール example-lambda-role と、ステートマシン用のロール example-sfn-role を作り、example-sfn-role には example-* の関数を呼ぶ許可を付けています。以下のコマンドと出力の中のアカウントIDは、<12桁のアカウントID> に置き換えています。
分岐の前に動かす関数として、注文の明細から合計金額 total を出す example-calc-total を Python で書きました。
# fn/calc_total.py
def lambda_handler(event, context):
total = sum(i["price"] * i["qty"] for i in event["items"])
return {
"orderId": event["orderId"],
"total": total,
"member": event.get("member", False),
}
$ aws lambda create-function --function-name example-calc-total --runtime python3.12 --handler calc_total.lambda_handler --role arn:aws:iam::$ACC:role/example-lambda-role --zip-file fileb://calc_total.zip --query "{FunctionName:FunctionName,State:State}"
{
"FunctionName": "example-calc-total",
"State": "Pending"
}
$ aws lambda wait function-active-v2 --function-name example-calc-total && echo active
active
$ACC には、aws sts get-caller-identity --query Account --output text で取ったアカウントIDを入れています。
Choice ステートの定義を書く
関数の結果を見て、送料を分けるステートマシン sm-choice.json を書きました。合計が 5000 円以上か、会員で 3000 円以上なら送料 0 円の FreeShipping に、それ以外は送料 500 円の AddShipping に進みます。
{
"Comment": "合計金額と会員かどうかで、送料を分ける",
"StartAt": "CalcTotal",
"States": {
"CalcTotal": {
"Type": "Task",
"Resource": "arn:aws:states:::lambda:invoke",
"Parameters": { "FunctionName": "example-calc-total", "Payload.$": "$" },
"OutputPath": "$.Payload",
"Next": "CheckShipping"
},
"CheckShipping": {
"Type": "Choice",
"Choices": [
{
"Variable": "$.total",
"NumericGreaterThanEquals": 5000,
"Next": "FreeShipping"
},
{
"And": [
{ "Variable": "$.member", "BooleanEquals": true },
{ "Variable": "$.total", "NumericGreaterThanEquals": 3000 }
],
"Next": "FreeShipping"
}
],
"Default": "AddShipping"
},
"FreeShipping": {
"Type": "Pass",
"Result": 0,
"ResultPath": "$.shipping",
"End": true
},
"AddShipping": {
"Type": "Pass",
"Result": 500,
"ResultPath": "$.shipping",
"End": true
}
}
}
Choice ステートの説明によると、それぞれの項目の意味は次のとおりです。
Choices:条件(Choice Rule)の配列。1つ以上が必要Variable:調べる値の場所。ここでは、前のステートの出力のtotalとmemberNumericGreaterThanEquals、BooleanEquals:比べ方と、比べる相手の値。名前の先頭がNumeric、String、Boolean、Timestampのものがあり、値の型ごとに使い分けるAnd:中に並べた条件がすべて当てはまったときに、この条件が当てはまる。OrとNotもある。中の条件にはNextを書かず、Nextはいちばん外側の条件にだけ書くDefault:どの条件にも当てはまらなかったときに進むステート。省略できるが、書くことが推奨されている
FreeShipping と AddShipping は Pass ステートで、Result の値を、ResultPath で指定した shipping という項目に入れるだけです。エミュレーターでも、validate-state-machine-definition で "result": "OK" が返り、そのまま登録できました。
$ aws stepfunctions validate-state-machine-definition --definition file://sm-choice.json
{
"result": "OK",
"diagnostics": [],
"truncated": false
}
$ aws stepfunctions create-state-machine --name example-choice --definition file://sm-choice.json --role-arn arn:aws:iam::$ACC:role/example-sfn-role
{
"stateMachineArn": "arn:aws:states:us-east-1:<12桁のアカウントID>:stateMachine:example-choice",
"creationDate": "2026-11-26T05:57:29.596000+00:00"
}
3件の注文で、進む先が分かれる
条件の違う3件の注文で実行しました。start-execution は実行を始めるだけで、終わるのを待ちません。そこで、describe-execution の status が RUNNING でなくなるまで待って、最後の status を出す小さなスクリプト wait-exec.sh を用意しました。
# 実行が RUNNING でなくなるまで待って、最後の status を出す
EX=$1
while [ "$(aws stepfunctions describe-execution --execution-arn $EX --query status --output text)" = RUNNING ]; do sleep 0.5; done
aws stepfunctions describe-execution --execution-arn $EX --query status --output text
コマンドの中の $SM と $EX は、arn:aws:states:us-east-1:<12桁のアカウントID>:stateMachine と arn:aws:states:us-east-1:<12桁のアカウントID>:execution を入れた変数です。1件目は、会員でない 6000 円の注文です。
$ cat input-big.json
{"orderId":"A-001","member":false,"items":[{"name":"cat-bed","price":3000,"qty":2}]}
$ aws stepfunctions start-execution --state-machine-arn $SM:example-choice --name run-big --input file://input-big.json --query executionArn
"arn:aws:states:us-east-1:<12桁のアカウントID>:execution:example-choice:run-big"
$ bash wait-exec.sh $EX:example-choice:run-big
SUCCEEDED
$ aws stepfunctions describe-execution --execution-arn $EX:example-choice:run-big --query output --output text
{"orderId":"A-001","total":6000,"member":false,"shipping":0}
$ aws stepfunctions get-execution-history --execution-arn $EX:example-choice:run-big --query 'events[].stateEnteredEventDetails.name' --output text
CalcTotal CheckShipping FreeShipping
最後のコマンドは、実行の履歴から、入ったステートの名前を順に取り出しています。1つ目の条件に当てはまり、FreeShipping に進んで shipping が 0 になりました。
2件目と3件目は、どちらも 3500 円で、会員かどうかだけが違います。会員の注文は2つ目の条件(And)に当てはまって FreeShipping に、会員でない注文はどちらの条件にも当てはまらず、Default の AddShipping に進みました。
$ cat input-member.json
{"orderId":"A-002","member":true,"items":[{"name":"cat-food","price":500,"qty":7}]}
(start-execution と wait-exec.sh は1件目と同じなので省略。結果は SUCCEEDED)
$ aws stepfunctions describe-execution --execution-arn $EX:example-choice:run-member --query output --output text
{"orderId":"A-002","total":3500,"member":true,"shipping":0}
$ aws stepfunctions get-execution-history --execution-arn $EX:example-choice:run-member --query 'events[].stateEnteredEventDetails.name' --output text
CalcTotal CheckShipping FreeShipping
$ cat input-small.json
{"orderId":"A-003","member":false,"items":[{"name":"cat-food","price":500,"qty":7}]}
(start-execution と wait-exec.sh は省略。結果は SUCCEEDED)
$ aws stepfunctions describe-execution --execution-arn $EX:example-choice:run-small --query output --output text
{"orderId":"A-003","total":3500,"member":false,"shipping":500}
$ aws stepfunctions get-execution-history --execution-arn $EX:example-choice:run-small --query 'events[].stateEnteredEventDetails.name' --output text
CalcTotal CheckShipping AddShipping
3件目の履歴を全部出すと、Choice ステートは ChoiceStateEntered と ChoiceStateExited の2つのイベントだけでした。ChoiceStateExited の output は、入ってきた値(関数の出力)そのままです。Choice ステートは進む先を選ぶだけで、値は変えていません。
$ aws stepfunctions get-execution-history --execution-arn $EX:example-choice:run-small --query 'events[].[id,type]' --output text
1 ExecutionStarted
2 TaskStateEntered
3 TaskScheduled
4 TaskStarted
5 TaskSucceeded
6 TaskStateExited
7 ChoiceStateEntered
8 ChoiceStateExited
9 PassStateEntered
10 PassStateExited
11 ExecutionSucceeded
$ aws stepfunctions get-execution-history --execution-arn $EX:example-choice:run-small --query 'events[?type==`ChoiceStateExited`].stateExitedEventDetails'
[
{
"name": "CheckShipping",
"output": "{\"orderId\":\"A-003\",\"total\":3500,\"member\":false}",
"outputDetails": {
"truncated": false
}
}
]
条件は上から順に調べ、最初に当てはまったものだけで進む
Choice ステートの説明には、Choices の条件を並んでいる順に調べ、最初に当てはまった条件の Next に進む、とあります。金額で会員のランクを分けるステートマシンで、条件の並びを間違えたときの動きを確かめました。3000 円以上の条件を、5000 円以上の条件より先に書いています。
{
"StartAt": "CheckRank",
"States": {
"CheckRank": {
"Type": "Choice",
"Choices": [
{ "Variable": "$.total", "NumericGreaterThanEquals": 3000, "Next": "Silver" },
{ "Variable": "$.total", "NumericGreaterThanEquals": 5000, "Next": "Gold" }
],
"Default": "Normal"
},
"Gold": { "Type": "Pass", "Result": "gold", "ResultPath": "$.rank", "End": true },
"Silver": { "Type": "Pass", "Result": "silver", "ResultPath": "$.rank", "End": true },
"Normal": { "Type": "Pass", "Result": "normal", "ResultPath": "$.rank", "End": true }
}
}
これを example-order として登録し、6000 円で実行すると、gold ではなく silver になりました。6000 は1つ目の「3000 以上」に当てはまるので、2つ目の条件は使われません。
$ aws stepfunctions start-execution --state-machine-arn $SM:example-order --name run-6000 --input '{"total":6000}' --query executionArn
"arn:aws:states:us-east-1:<12桁のアカウントID>:execution:example-order:run-6000"
$ bash wait-exec.sh $EX:example-order:run-6000
SUCCEEDED
$ aws stepfunctions describe-execution --execution-arn $EX:example-order:run-6000 --query output --output text
{"total":6000,"rank":"silver"}
範囲の狭い条件(5000 以上)を先に書くように並べ替えた定義を example-order-fixed として登録すると、6000 円は gold、3500 円は silver、1000 円は Default の normal になりました。
$ python3 -c 'import json;print(json.dumps(json.load(open("sm-order-fixed.json"))["States"]["CheckRank"]["Choices"], indent=2))'
[
{
"Variable": "$.total",
"NumericGreaterThanEquals": 5000,
"Next": "Gold"
},
{
"Variable": "$.total",
"NumericGreaterThanEquals": 3000,
"Next": "Silver"
}
]
$ aws stepfunctions describe-execution --execution-arn $EX:example-order-fixed:run-6000 --query output --output text
{"total":6000,"rank":"gold"}
$ aws stepfunctions describe-execution --execution-arn $EX:example-order-fixed:run-3500 --query output --output text
{"total":3500,"rank":"silver"}
$ aws stepfunctions describe-execution --execution-arn $EX:example-order-fixed:run-1000 --query output --output text
{"total":1000,"rank":"normal"}
上の3件の start-execution と wait-exec.sh は省略しました。どれも SUCCEEDED です。
Default を書かないと、当てはまらなかった実行が失敗する
example-order-fixed の定義から Default の指定と Normal ステートを消した example-no-default を作りました。validate-state-machine-definition は "result": "OK" を返し、登録もできました。ところが、どの条件にも当てはまらない 1000 円で実行すると、実行全体が FAILED になりました。
$ aws stepfunctions validate-state-machine-definition --definition file://sm-no-default.json
{
"result": "OK",
"diagnostics": [],
"truncated": false
}
$ aws stepfunctions start-execution --state-machine-arn $SM:example-no-default --name run-1000 --input '{"total":1000}' --query executionArn
"arn:aws:states:us-east-1:<12桁のアカウントID>:execution:example-no-default:run-1000"
$ bash wait-exec.sh $EX:example-no-default:run-1000
FAILED
$ aws stepfunctions describe-execution --execution-arn $EX:example-no-default:run-1000 --query '{status:status,error:error,cause:cause}'
{
"status": "FAILED",
"error": "States.Runtime",
"cause": "An error occurred while executing the state 'CheckRank' (entered at the event id #2). Failed to transition out of the state. The state does not point to a next state."
}
$ aws stepfunctions get-execution-history --execution-arn $EX:example-no-default:run-1000 --query 'events[].[id,type]' --output text
1 ExecutionStarted
2 ChoiceStateEntered
3 ExecutionFailed
Choice ステートの説明にも、どの条件にも当てはまらず Default もないときは、次のステートに移れず、エラーになる、とあります。エミュレーターでのエラー名は States.Runtime でした。エラーの扱いの説明によると、Catch を書けるのは Task、Parallel、Map のステートだけで、States.Runtime は States.ALL の Catch でも受け止められません。
エミュレーターでは、定義の検証(validate-state-machine-definition)では Default がないことは見つかりませんでした。想定外の値で実行が止まらないように、Default を書いておきます。
入力にない値を調べるときは、IsPresent を先に書く
クーポンの番号 coupon が入力にあれば値引きするステートマシン example-coupon を作りました。条件は $.coupon が "NEKO10" と等しいかどうかだけで、Default も書いています。
{
"StartAt": "CheckCoupon",
"States": {
"CheckCoupon": {
"Type": "Choice",
"Choices": [
{ "Variable": "$.coupon", "StringEquals": "NEKO10", "Next": "ApplyCoupon" }
],
"Default": "NoCoupon"
},
"ApplyCoupon": { "Type": "Pass", "Result": 10, "ResultPath": "$.discount", "End": true },
"NoCoupon": { "Type": "Pass", "Result": 0, "ResultPath": "$.discount", "End": true }
}
}
coupon がある入力では discount が 10 になりました。一方、coupon がない入力では、Default に進まずに、実行が States.Runtime で失敗しました。
(create-state-machine、start-execution と wait-exec.sh は省略。結果は SUCCEEDED)
$ aws stepfunctions describe-execution --execution-arn $EX:example-coupon:run-with --query output --output text
{"total":3000,"coupon":"NEKO10","discount":10}
$ aws stepfunctions start-execution --state-machine-arn $SM:example-coupon --name run-without --input '{"total":3000}' --query executionArn
"arn:aws:states:us-east-1:<12桁のアカウントID>:execution:example-coupon:run-without"
$ bash wait-exec.sh $EX:example-coupon:run-without
FAILED
$ aws stepfunctions describe-execution --execution-arn $EX:example-coupon:run-without --query '{status:status,error:error,cause:cause,output:output}'
{
"status": "FAILED",
"error": "States.Runtime",
"cause": "An error occurred while executing the state 'CheckCoupon' (entered at the event id #2). Invalid path '$.coupon': The choice state's condition path references an invalid value.",
"output": null
}
公式の説明には、IsPresent の条件を先に置いて And でまとめると、値があるときだけ StringEquals を調べる例が載っています。同じように書き換えた定義を example-coupon-safe として登録しました。
$ diff sm-coupon.json sm-coupon-safe.json
7c7,13
< { "Variable": "$.coupon", "StringEquals": "NEKO10", "Next": "ApplyCoupon" }
---
> {
> "And": [
> { "Variable": "$.coupon", "IsPresent": true },
> { "Variable": "$.coupon", "StringEquals": "NEKO10" }
> ],
> "Next": "ApplyCoupon"
> }
今度は、coupon がない入力でも実行が SUCCEEDED になり、Default の NoCoupon に進んで discount が 0 になりました。coupon がある入力の結果は、書き換える前と同じです。
(create-state-machine と、2件の start-execution、wait-exec.sh は省略。結果はどちらも SUCCEEDED)
$ aws stepfunctions describe-execution --execution-arn $EX:example-coupon-safe:run-with --query output --output text
{"total":3000,"coupon":"NEKO10","discount":10}
$ aws stepfunctions describe-execution --execution-arn $EX:example-coupon-safe:run-without --query output --output text
{"total":3000,"discount":0}
数値の条件に文字列の "6000" が来ると、当てはまらない
example-order-fixed に、total を数値ではなく文字列の "6000" にした入力を渡しました。実行は失敗せずに SUCCEEDED になりましたが、「5000 以上」の条件には当てはまらず、Default の normal に進みました。
$ aws stepfunctions start-execution --state-machine-arn $SM:example-order-fixed --name run-string --input '{"total":"6000"}' --query executionArn
"arn:aws:states:us-east-1:<12桁のアカウントID>:execution:example-order-fixed:run-string"
$ bash wait-exec.sh $EX:example-order-fixed:run-string
SUCCEEDED
$ aws stepfunctions describe-execution --execution-arn $EX:example-order-fixed:run-string --query output --output text
{"total":"6000","rank":"normal"}
Choice ステートの説明にも、比べ方ごとに値の型(文字列、数値、真偽値、時刻)が決まっていて、数値の比べ方で文字列の値を比べることはしない、とあります。エラーにならないぶん、間違った分岐に気づきにくくなります。前の関数が金額を文字列で返していないかは、実行の履歴の output で確かめられます。
Choice ステートには End を書けない
Choice ステートは、ワークフローの最後のステートにはなれません。example-coupon-safe の CheckCoupon に "End": true を足した定義は、validate-state-machine-definition で FAIL になり、create-state-machine でも登録できませんでした。
$ aws stepfunctions validate-state-machine-definition --definition file://sm-choice-end.json
{
"result": "FAIL",
"diagnostics": [
{
"severity": "ERROR",
"code": "SCHEMA_VALIDATION_FAILED",
"message": "Field 'End' is not supported",
"location": "/States/CheckCoupon"
}
],
"truncated": false
}
$ aws stepfunctions create-state-machine --name example-choice-end --definition file://sm-choice-end.json --role-arn arn:aws:iam::$ACC:role/example-sfn-role --query stateMachineArn
aws: [ERROR]: An error occurred (InvalidDefinition) when calling the CreateStateMachine operation: Invalid State Machine Definition: 'SCHEMA_VALIDATION_FAILED: Field 'End' is not supported at /States/CheckCoupon'
Choice ステートの説明にも、Choice ステートは End を使えず、Next は Choices の中でだけ使う、とあります。分岐した先で終わらせたいときは、この記事の FreeShipping のように、進んだ先のステートに "End": true を書きます。何もせずに終えるだけなら、Succeed ステートの説明にあるとおり、Succeed ステートに進める書き方もあります。





