I’m creating multiple new Landing Zones for a customer with multiple default Resource Groups. I don’t want to create all the Resource Groups manually so I decided to deploy them using Bicep.

In this example I will be deploying six Resource Groups named RG1-RG6. We can declare the resources one by one but as you can see the code is pretty messy already. Let’s use a loop instead.

targetScope = 'subscription'

param location string = 'westeurope'

resource ResourceGroup1 'Microsoft.Resources/resourceGroups@2018-05-01' =  {
  name: 'RG1'
  location: location
}

resource ResourceGroup2 'Microsoft.Resources/resourceGroups@2018-05-01' =  {
  name: 'RG2'
  location: location
}

resource ResourceGroup3 'Microsoft.Resources/resourceGroups@2018-05-01' =  {
  name: 'RG3'
  location: location
}

resource ResourceGroup4 'Microsoft.Resources/resourceGroups@2018-05-01' =  {
  name: 'RG4'
  location: location
}

resource ResourceGroup5 'Microsoft.Resources/resourceGroups@2018-05-01' =  {
  name: 'RG5'
  location: location
}

resource ResourceGroup6 'Microsoft.Resources/resourceGroups@2018-05-01' =  {
  name: 'RG6'
  location: location
}

Let’s loop!

First let’s create a new parameter. We’ll use the ‘array’ type for this since we have multiple strings and we will add all the Resource Group names we want to create in this array.

Next we will add a single Resource, but we will tell it to loop through the array we just created. The complete code will look like this. As you can see it’s a lot shorter and readable.

targetScope = 'subscription'

param location string = 'westeurope'
param ResourceGroupNames array = [ 
  'rg1'
  'rg2'
  'rg3'
  'rg4'
  'rg5'
  'rg6'
 ]

resource rg 'Microsoft.Resources/resourceGroups@2019-05-01' = [for ResourceGroupName in ResourceGroupNames: {
  name: ResourceGroupName
  location: location
}]

After deploying the file our six Resouce Groups are succesfully created.

So now you know how to create simple loop in Bicep.
Of course this works for any Resource Type you want to deploy. Using loops is a great way to simplify your code and save some time. 🙂

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *