Bicep Loops – Copy Loop

Often in Bicep you need to deploy multiple resources that are very similar. This could be multiple storage accounts, virtual networks, or VMs and we can use a loop to go through and deploy the resources. Loops will save you from typing your code out more than once. Instead of having separate code to create 4 storage accounts, you can use one bit of code in a loop to deploy the 4 storage accounts. This makes the code easier to read and understand and can make your code more flexible and save time when writing the code and could potentially be deployed many many times to create additional storage accounts.

Copy Loop

You create your for loop in the same place where we created our conditions in my previous blog. So, after the resource type, API, and = sign you add a square brackets and use the key words for and make up a name (can be anything but makes sense to use something meaningful for the resource) to be used and then use the key word in followed by a parameter.  So, in the below example we use storageAccountName in storageAccountNames.

We then need to remember to include the closing square loop at the end of the resource to close the loop.

For the storageAccountNames parameter we use an array with as many storage account names in as we need to deploy. Below, we’ll be using three storage account names which the for loop will loop through.

So, basically the for loop is saying, for storage account name, in the storage account array list, create a storage account. We then use the name that you made up in the for loop as the property in the resource. So in the below example, for the name of the resource we use storageAccountName which will loop through the storageAccountNames. This will loop through three times as there are three storage account names in the list.

If you’re using Visual Studio Code, which I would highly recommend, it can create for loops for you when you create the resource.

It then inserts the syntax for you.

About the author