Passing arrays and using loops in ARM templates

Posted by

Today we going to build a dynamic ARM template to read in a list of our webapps, and loop through the this array to dynamically build our backend pool of resources for our Front Door load balancer.

Part 1: passing an array into an ARM template

The first step is to add a new parameter type we haven’t used before to our ARM template, the “Array” type. The syntax is a bit tricky, we found creating a “test” template really useful to get this right. The screenshot below shows how we read in an array of strings in the parameters, and then in the outputs, return the size of the array, (2 in this case), and the actual array/list.

To test this template, we use Azure CLI to deploy to a target resource group, and a deployment name ($frontDoorName in this screenshot – oops!)

Below we see the results – which shows the output as expected. Highly recommend this test structure as you start to work with loops and arrays in ARM templates.

Part 2: Looping in an ARM Template

Back to our problem – we need to build an array dynamically in PowerShell to pass to the ARM template. We had a bit of difficulty getting our array to build dynamically – this syntax works:

For two items, it would look like this:

Our final ARM template deployment PowerShell looks like this:

Now the ARM template changes, where we will add in our loops – this is where things get a bit complicated. Let’s look at the ARM template before we insert in the loops. Here we manually added two web apps to the back end pool from the portal and then exported the template. We can see, in red and green, each of the two backend webapps.

Now we add the loop. First, we need a “copy” command, below in red. This is the loop around the set of code, essentially like a for or while loop. This copy loop needs information we have in green, including the name of the item that we are looping within, “backends”, the number of times to loop, “length”, and then the actual looping content, in the “input” element. Finally, in blue, we can pull in the items from the parameters array with an index, based on the backend loop. This took us a while to figure out – hopefully the colors help with understanding.

Wrap up

Today we setup our Frontdoor ARM template to read in an array of back end resources. We showed a simple way to learn and test these arrays with a blank template. We also learned how to setup the custom ARM templates in our Frontdoor resource, to dynamically create backend resources, depending on the number of resources we pass into the template.



Leave a Reply to fhneundr6ie4d6un Cancel reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s