While working with Azure Logic Apps, I was faced with a difficult challenging of coming up with a ‘local’ variable (actually, it was just a loop counter really) for a ‘For each’ loop.
I immediately went to using an ‘Initialize Variable’, setting the value to zero, and in my ‘For each’ loop simply do an ‘Increment Variable’ to increment it on each iteration.
What I didn’t realize at first – it was incremented by each running loop! Loops run in parallel in Logic Apps (at least by default – you can go to ‘Settings’ within the For Each block itself and set the ‘degree of parellism’ to 1, and this will also solve the problem besides the solution I’m writing), and because they run in parallel, each iteration increments the same Variable! I sort of imagined that each iteration would have its own local variable, but this is not the case.
So….unless you do the solution of setting the ‘degree of parellism’ to 1, you will need to do something to handle this. In my case, it was okay to set the ‘degree of parellism’ to 1 (the app I wrote was just doing routine maintenance, so it didn’t matter that it took an extra 5 min), but I did think of a possible solution on how you could handle the parallel case:
It’s a little bit heavy, because you will need either a) an Azure SQL DB, or b) Azure Storage, but a possible solution is:
– Create a temp table in an Azure SQL DB that will store the local variable for each iteration (where, the ‘primary key’ to your table could either be an ID you have handy, or maybe you can inject a ‘row index’ value into the item your iterating over beforehand ie before your ‘for each’ loop)
– Create temp files in the Azure storage, with each file associated with each iteration of your loop, and this file could store the local variable
Admittingly, neither solution is really that pretty or elegant, but I’m pretty certain it would work. It’s also dependant on having either an Azure SQL DB or a Azure storage. If neither of these is available, you might be able to use to some other ‘storage’ medium to accomplish the same goal (if its available).
Also, although not as powerful as the solution above, you may want to consider using the code function iterationIndexes(‘loopName’) as a loop counter if that’s all you need. I think it only works for ‘Until’ loops though, not for ‘For each’ loops. Feel free to google it to learn more.
Well, not the prettiest solution, but hopefully a ‘solution’ nonetheless 🙂 Hopefully this tip will help you.