English

AWS EmulatorでStep FunctionsのMapを1件ずつ処理する方法

​​AWS Emulator​AWS CLI,AWS Lambda,AWS Step Functions,Python,テスト

Step Functions の Map ステートに "MaxConcurrency": 1 を書くと、配列の要素を先頭から1件ずつ、前の1件が終わってから次の1件を処理できます。注文の明細やファイルの一覧のような配列について、要素ごとに Lambda 関数を呼ぶループ処理(for each の繰り返し)を、ワークフローの中で書きたいときの方法です。AWS のアカウントは使わず、手元に入れた AWS Emulator で、定義の書き方から、同時に動かしたときとの違い、途中の1件が失敗したときの止まり方までを試しました。コマンドと出力は、そのまま載せています。

補足

検証環境は Ubuntu 24.04.5(x86_64)、AWS Emulator 1.0.602(2026年11月24日リリース、Debian パッケージ)、AWS CLI 2.42.2、Lambda のランタイムは python3.12 です。AWS のアカウントと認証情報は使っていません。本物の AWS Step Functions での動き、料金、同時に動く数の上限(Inline モードで40)、実行の履歴の上限(25,000件)は確かめておらず、触れるところは公式ドキュメントを出どころにしています。Distributed モードの Map、JSONata で書く定義、Map ステートそのものへの Retry、MaxConcurrency に 2 以上の値を書いたときの動きは試していません。

準備:エミュレーターを起動し、関数を作る

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> に置き換えています。

明細の1件を受け取って小計を返す関数 example-process-item を、Python で書きました。1件ずつ動いているかを確かめるために、1秒スリープし、始めた時刻と終えた時刻も返します。数量が負の値のときは、例外を出します。

python
# fn/process_item.py
import time
from datetime import datetime, timezone


def now():
    return datetime.now(timezone.utc).strftime("%H:%M:%S.%f")[:-3]


def lambda_handler(event, context):
    start = now()
    if event.get("qty", 0) < 0:
        raise ValueError(f"qty must not be negative: {event['name']}")
    time.sleep(1)
    return {
        "name": event["name"],
        "subtotal": event["price"] * event["qty"],
        "start": start,
        "end": now(),
    }
text
$ aws lambda create-function --function-name example-process-item --runtime python3.12 --handler process_item.lambda_handler --role arn:aws:iam::$ACC:role/example-lambda-role --zip-file fileb://process_item.zip --query "{FunctionName:FunctionName,State:State}"
{
    "FunctionName": "example-process-item",
    "State": "Pending"
}

$ACC には、aws sts get-caller-identity --query Account --output text で取ったアカウントIDを入れています。

Map の定義を書く

注文の入力は、次のような JSON です。items の配列の3件を、1件ずつ関数に渡します。

json
{"orderId":"A-001","items":[{"name":"cat-food","price":500,"qty":3},{"name":"cat-toy","price":800,"qty":1},{"name":"cat-bed","price":3000,"qty":2}]}

ステートマシンの定義 sm-map.json は、Map ステートを1つ置くだけです。

json
{
  "Comment": "注文の明細を1件ずつ Lambda で処理する",
  "StartAt": "ProcessItems",
  "States": {
    "ProcessItems": {
      "Type": "Map",
      "ItemsPath": "$.items",
      "MaxConcurrency": 1,
      "ItemProcessor": {
        "ProcessorConfig": { "Mode": "INLINE" },
        "StartAt": "ProcessItem",
        "States": {
          "ProcessItem": {
            "Type": "Task",
            "Resource": "arn:aws:states:::lambda:invoke",
            "Parameters": { "FunctionName": "example-process-item", "Payload.$": "$" },
            "OutputPath": "$.Payload",
            "End": true
          }
        }
      },
      "End": true
    }
  }
}

Inline モードの Map ステートの説明によると、それぞれの項目の意味は次のとおりです。

  • ItemsPath:入力の中の、処理する配列の場所。書かないと $(入力そのもの)が配列として扱われる
  • ItemProcessor:配列の1件ごとに動かすステートの組。中の StartAt と States は、ふつうのステートマシンと同じ書き方
  • ProcessorConfig の Mode:INLINE が既定。1件ごとの処理が、親のワークフローの中で動き、その履歴も親の実行の履歴に入る
  • MaxConcurrency:同時に動かす数の上限。既定は 0 で、上限を設けずにできるだけ同時に動かす

同じ説明には、MaxConcurrency を 1 にすると、配列に並んでいる順に処理し、前の1件が終わるまで次の1件を始めない、とあります。

古い書き方の Iterator と、Map の中の Parameters は、それぞれ ItemProcessor と ItemSelector(あとで使います)に置き換わり、今は使わないように勧められています。

エミュレーターでも、validate-state-machine-definition で "result": "OK" が返り、そのまま登録できました。

text
$ aws stepfunctions validate-state-machine-definition --definition file://sm-map.json
{
    "result": "OK",
    "diagnostics": [],
    "truncated": false
}
$ aws stepfunctions create-state-machine --name example-map --definition file://sm-map.json --role-arn arn:aws:iam::$ACC:role/example-sfn-role
{
    "stateMachineArn": "arn:aws:states:us-east-1:<12桁のアカウントID>:stateMachine:example-map",
    "creationDate": "2026-11-24T12:57:49.148000+00:00"
}

実行すると、3件が順番に1件ずつ処理される

start-execution は実行を始めるだけで、終わるのを待ちません。そこで、describe-execution の status が RUNNING でなくなるまで待って、最後の status を出す小さなスクリプト wait-exec.sh を用意しました。

bash
# 実行が 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 を入れた変数です。

text
$ aws stepfunctions start-execution --state-machine-arn $SM:example-map --name run-serial --input file://input.json
{
    "executionArn": "arn:aws:states:us-east-1:<12桁のアカウントID>:execution:example-map:run-serial",
    "startDate": "2026-11-24T12:57:49.858000+00:00"
}
$ bash wait-exec.sh $EX:example-map:run-serial
SUCCEEDED
$ aws stepfunctions describe-execution --execution-arn $EX:example-map:run-serial --query output --output text | python3 -m json.tool
[
    {
        "name": "cat-food",
        "subtotal": 1500,
        "start": "12:57:50.045",
        "end": "12:57:51.046"
    },
    {
        "name": "cat-toy",
        "subtotal": 800,
        "start": "12:57:51.052",
        "end": "12:57:52.052"
    },
    {
        "name": "cat-bed",
        "subtotal": 6000,
        "start": "12:57:52.060",
        "end": "12:57:53.060"
    }
]

Map ステートの出力は、1件ごとの結果を並べた配列です。2件目と3件目は、どちらも前の1件の end のあとに start しているので、3件が1件ずつ順番に動いたことが分かります。

実行の履歴を見ると、MapIterationStarted から MapIterationSucceeded までの1件分のイベントが、3回続けて並んでいました。MapStateStarted のイベントには、配列の長さ "length": 3 が入っています。

text
$ aws stepfunctions get-execution-history --execution-arn $EX:example-map:run-serial --query "events[].[id,type]" --output text
1	ExecutionStarted
2	MapStateEntered
3	MapStateStarted
4	MapIterationStarted
5	TaskStateEntered
6	TaskScheduled
7	TaskStarted
8	TaskSucceeded
9	TaskStateExited
10	MapIterationSucceeded
(11〜23 は省略。2件目と3件目でも、1件目と同じ7つのイベントが続く)
24	MapIterationSucceeded
25	MapStateSucceeded
26	MapStateExited
27	ExecutionSucceeded
$ aws stepfunctions get-execution-history --execution-arn $EX:example-map:run-serial --query "events[?type==\`MapStateStarted\`].mapStateStartedEventDetails"
[
    {
        "length": 3
    }
]

1件ごとに7つのイベントが親の実行の履歴に積み上がるので、配列が長いほど履歴は長くなります。Inline モードの説明では、実行の履歴が 25,000 件を超えない場合に Inline モードを使うよう勧めています。

MaxConcurrency を書かないと、同時に動く

比べるために、MaxConcurrency の行だけを消した定義で、ステートマシン example-map-parallel を作りました。

text
$ diff sm-map.json sm-map-parallel.json
2c2
<   "Comment": "注文の明細を1件ずつ Lambda で処理する",
---
>   "Comment": "MaxConcurrency を書かない",
8d7
<       "MaxConcurrency": 1,

同じ入力で実行すると、3件の関数がほぼ同時に始まりました。それでも出力の配列は、終わった順ではなく、入力の配列と同じ並び(cat-food、cat-toy、cat-bed)でした。

text
$ aws stepfunctions describe-execution --execution-arn $EX:example-map-parallel:run-parallel --query output --output text | python3 -m json.tool
[
    {
        "name": "cat-food",
        "subtotal": 1500,
        "start": "12:57:59.541",
        "end": "12:58:00.542"
    },
    {
        "name": "cat-toy",
        "subtotal": 800,
        "start": "12:57:59.697",
        "end": "12:58:00.698"
    },
    {
        "name": "cat-bed",
        "subtotal": 6000,
        "start": "12:57:59.683",
        "end": "12:58:00.683"
    }
]

実行の始まりから終わりまで(describe-execution の startDate から stopDate まで)は、1件ずつのときが約3.7秒、同時のときが約1.7秒でした(どちらもエミュレーターでの値です)。

MaxConcurrency: 1 では cat-food、cat-toy、cat-bed の3つの棒が0秒、1秒、2秒から順に重ならずに並ぶ。MaxConcurrency を書かないときは、3つの棒が0〜0.16秒の間にほぼ同時に始まって重なる
関数が動いていた時間。MaxConcurrency: 1(上)と書かないとき(下)
ポイント

外部の API に同時にリクエストを送りたくないときや、前の1件が終わってから次に進めたいときは、"MaxConcurrency": 1 を書きます。

ItemSelector で、配列の外の値や何件目かを渡す

1件ごとの処理には、既定では配列の要素だけが渡ります。注文番号 orderId のような配列の外にある値や、何件目かを知りたいときは、ItemSelector で渡す内容を組み立てます。ItemSelector の説明とコンテキストオブジェクトの Map の項目によると、$$.Map.Item.Index は何件目か(0 から数える)を、$$.Map.Item.Value はその要素を表し、どちらも ItemSelector の中で使えます。一方、$ で始まるパスは、Map ステートの入力(ここでは注文全体)を指します。

受け取った内容をそのまま返す関数 example-echo を作り、次の定義をステートマシン example-map-selector として登録して呼びました。Map ステートに "ResultPath": "$.results" も足しています。

python
# fn/echo.py
def lambda_handler(event, context):
    return {"received": event, "subtotal": event["price"] * event["qty"]}
json
{
  "StartAt": "ProcessItems",
  "States": {
    "ProcessItems": {
      "Type": "Map",
      "ItemsPath": "$.items",
      "MaxConcurrency": 1,
      "ItemSelector": {
        "orderId.$": "$.orderId",
        "index.$": "$$.Map.Item.Index",
        "name.$": "$$.Map.Item.Value.name",
        "price.$": "$$.Map.Item.Value.price",
        "qty.$": "$$.Map.Item.Value.qty"
      },
      "ItemProcessor": {
        "ProcessorConfig": { "Mode": "INLINE" },
        "StartAt": "ProcessItem",
        "States": {
          "ProcessItem": {
            "Type": "Task",
            "Resource": "arn:aws:states:::lambda:invoke",
            "Parameters": { "FunctionName": "example-echo", "Payload.$": "$" },
            "OutputPath": "$.Payload",
            "End": true
          }
        }
      },
      "ResultPath": "$.results",
      "End": true
    }
  }
}

実行の出力では、関数が受け取った received に、orderId と 0 から始まる index が入っていました。また、ResultPath を書いたので、元の入力(orderId と items)が残り、1件ごとの結果の配列は results に入りました。ResultPath を書かなかった前の節では、出力は結果の配列だけになっています。

text
$ aws stepfunctions describe-execution --execution-arn $EX:example-map-selector:run-selector --query output --output text | python3 -m json.tool
{
    "orderId": "A-001",
    "items": [
(入力と同じ3件。省略)
    ],
    "results": [
        {
            "received": {
                "orderId": "A-001",
                "index": 0,
                "name": "cat-food",
                "price": 500,
                "qty": 3
            },
            "subtotal": 1500
        },
        {
            "received": {
                "orderId": "A-001",
                "index": 1,
                "name": "cat-toy",
                "price": 800,
                "qty": 1
            },
            "subtotal": 800
        },
        {
            "received": {
                "orderId": "A-001",
                "index": 2,
                "name": "cat-bed",
                "price": 3000,
                "qty": 2
            },
            "subtotal": 6000
        }
    ]
}

途中の1件が失敗すると、残りは処理されない

2件目の cat-toy の数量を -1 にした入力で、example-map を実行しました。2件目で関数が ValueError を出し、実行全体が FAILED になりました。

text
$ aws stepfunctions start-execution --state-machine-arn $SM:example-map --name run-fail --input file://input-fail.json --query executionArn
"arn:aws:states:us-east-1:<12桁のアカウントID>:execution:example-map:run-fail"
$ bash wait-exec.sh $EX:example-map:run-fail
FAILED
$ aws stepfunctions describe-execution --execution-arn $EX:example-map:run-fail --query "{status:status,error:error,cause:cause}"
{
    "status": "FAILED",
    "error": "ValueError",
    "cause": "{\"errorMessage\":\"qty must not be negative: cat-toy\",\"errorType\":\"ValueError\",(以下は省略)"
}

履歴は MapIterationFailed、MapStateFailed、ExecutionFailed で終わっていて、3件目の cat-bed の関数は呼ばれていませんでした。関数を呼んだ回数(TaskScheduled のイベントの数)は 2 です。

text
$ aws stepfunctions get-execution-history --execution-arn $EX:example-map:run-fail --query "events[].[id,type]" --output text
(1〜10 は1件目の成功で、最初に実行した `run-serial` の履歴の1〜10と同じなので省略)
11	MapIterationStarted
12	TaskStateEntered
13	TaskScheduled
14	TaskStarted
15	TaskFailed
16	MapIterationFailed
17	MapStateFailed
18	ExecutionFailed
$ aws stepfunctions get-execution-history --execution-arn $EX:example-map:run-fail --query "length(events[?type==\`TaskScheduled\`])"
2

Inline モードの説明にも、Inline モードではどれか1件が失敗すると Map ステートが失敗し、すべての処理が止まる、とあります。

Catch を中に書くと、失敗した1件を記録して先へ進める

失敗した1件があっても残りを処理したいときは、ItemProcessor の中のステートに Catch を書き、失敗した1件の結果を別のステートで作ります。ここでは、ValueError を受け止めて、Pass ステート MarkFailed で failed: true とエラー名を返すようにしました(Catch と ResultPath の書き方はCatch の書き方の説明にあります)。

json

"ProcessItem": {
            "Type": "Task",
            "Resource": "arn:aws:states:::lambda:invoke",
            "Parameters": { "FunctionName": "example-process-item", "Payload.$": "$" },
            "OutputPath": "$.Payload",
            "Catch": [
              { "ErrorEquals": ["ValueError"], "ResultPath": "$.error", "Next": "MarkFailed" }
            ],
            "End": true
          },
          "MarkFailed": {
            "Type": "Pass",
            "Parameters": { "name.$": "$.name", "failed": true, "error.$": "$.error.Error" },
            "End": true
          }

ItemProcessor の States の中だけを載せました。Comment がないことのほかは、sm-map.json と同じです。この定義をステートマシン example-map-catch として登録し、2件目の数量を -1 にした入力(input-fail.json)で実行しました。実行は SUCCEEDED になり、2件目だけが failed の結果になって、3件目も処理されました。

text
$ bash wait-exec.sh $EX:example-map-catch:run-catch
SUCCEEDED
$ aws stepfunctions describe-execution --execution-arn $EX:example-map-catch:run-catch --query output --output text | python3 -m json.tool
[
    {
        "name": "cat-food",
        "subtotal": 1500,
        "start": "12:58:15.417",
        "end": "12:58:16.418"
    },
    {
        "name": "cat-toy",
        "failed": true,
        "error": "ValueError"
    },
    {
        "name": "cat-bed",
        "subtotal": 6000,
        "start": "12:58:16.426",
        "end": "12:58:17.427"
    }
]

空の配列は成功し、配列でないと States.Runtime で失敗する

items が空の配列 [] のときは、関数を1度も呼ばずに成功し、出力は空の配列 [] でした。items が配列ではなくオブジェクトのときと、items のキーがないときは、どちらも States.Runtime で失敗しました。

text
$ aws stepfunctions describe-execution --execution-arn $EX:example-map:run-empty --query '{status:status,output:output,error:error,cause:cause}'
{
    "status": "SUCCEEDED",
    "output": "[]",
    "error": null,
    "cause": null
}
$ aws stepfunctions describe-execution --execution-arn $EX:example-map:run-object --query '{status:status,output:output,error:error,cause:cause}'
{
    "status": "FAILED",
    "output": null,
    "error": "States.Runtime",
    "cause": "Reference path \"$.items\" must point to array."
}
$ aws stepfunctions describe-execution --execution-arn $EX:example-map:run-nokey --query '{status:status,output:output,error:error,cause:cause}'
{
    "status": "FAILED",
    "output": null,
    "error": "States.Runtime",
    "cause": "An error occurred while executing the state 'ProcessItems' (entered at the event id #2). Invalid path '$.items' : No results for path: $['items']"
}

試したステートマシンと関数は、delete-state-machine と delete-function で消し、エミュレーターを止めました。

​Posted by 86