Home > Software design >  How can I get the index of an iterator/map state in AWS step function
How can I get the index of an iterator/map state in AWS step function

Time:01-09

I'm trying to create a step function that creates an array of results in a map state. My code looks something like that:

"MyIterator": {
   "Type": "Map",
   "InputPath": "$.myArray",
   "Iterator": {
     "StartAt": "Parser",
     "States": {
       "Parser": {
         "Type": "Task",
         "Resource": "${my-lambda}",
         "ResultPath": "$.Result",
         "End": true
     }
  }
}

I want my step function to go through the array I provided, and create an array as the result, but I'm not sure how to do it. For example, if my lambda will be the function: x = x 1 and the input is myArray = [0,1,2], the result will be Result = [1,2,3]. Something I thought of is to access the index of the iteration in my Parser stage. For example, use "ResultPath": "$.Result[i]" if i is the index of the iteration. Is that possible in AWS step functions? I know I can create another lambda that acts as a counter, I just don't really want to add another one as it looks way over complicated for such a usecase.

I tried to use the above code, but the iteration seemed to override the parameter Result each time.

CodePudding user response:

The Map item index is available on the Context object as $$.Map.Item.Index. The ItemSelector field*, which overrides the values passed to each Map iteration, can reference the Context object:

"MyIterator": {
   "Type": "Map",
   "InputPath": "$.myArray",
   "Iterator": {
     "StartAt": "Parser",
     "States": {
       "Parser": {
         "Type": "Task",
         "Resource": "${my-lambda}",
         "ResultPath": "$.Result",
         "End": true
     }
  },
  "ItemSelector": {
    "ContextIndex.$": "$$.Map.Item.Index",
    "ContextValue.$": "$$.Map.Item.Value"
  },
}

Using your example myArray = [0,1,2], the first iteration would receive:

{ "ContextIndex": 0, "ContextValue": 0 }

* ItemSelector replaces the deprecated Parameters field, which did the same thing. Note also that ItemProcessor has replaced the deprecated Iterator field. They all still work, though.

  • Related