简体   繁体   中英

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

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM