|
| 1 | +# Azure Bicep - Iterative loops (for) |
| 2 | + |
| 3 | +## Introduction |
| 4 | + |
| 5 | +For loops in Azure Bicep can be a great way to simplify and minimise your Bicep templates, as they allow you to define multiple copies of a resource which helps reduce and avoids us repeating code in our Bicep templates. |
| 6 | + |
| 7 | +Using a for loop, you can quickly deploy multiple resources, in this instance a virtual network resource with multiple subnets in one block. |
| 8 | + |
| 9 | +You can go through the Microsoft Learn training module for this which is great [here](https://learn.microsoft.com/en-us/training/modules/build-flexible-bicep-templates-conditions-loops/). |
| 10 | + |
| 11 | +## 📃 Benefits of using for loops in Bicep |
| 12 | + |
| 13 | +1. ✅ DRY (Don't repeat yourself) - avoids repeating Bicep code uncessarily |
| 14 | + |
| 15 | +2. ✅ Clean templates. By avoiding duplicating code, we can reduce large template files with lots of code lines |
| 16 | + |
| 17 | +3. ✅ Best practice. It's good practice to use for loops in your Bicep templates for the reasons above as well as maintainability as you scale |
| 18 | + |
| 19 | +## For Loop Example |
| 20 | + |
| 21 | +In the basic example within the `main.bicep` file, we can using the `for` property to state for each `vnet` resource, loop through and create the virtual network with subnets. |
| 22 | + |
| 23 | +As the variable (refer to the `main.bicep` file) also contains the required subnets, we're further looping the sub-property within the `vnet` to loop for each `subnet` within the `vnet` as it deploys. |
| 24 | + |
| 25 | +```javascript |
| 26 | +resource vnet 'Microsoft.Network/virtualNetworks@2020-06-01' = [for vnet in vnets: { |
| 27 | + name: vnet.name |
| 28 | + location: location |
| 29 | + properties: { |
| 30 | + addressSpace: { |
| 31 | + addressPrefixes: [ |
| 32 | + vnet.addressPrefix |
| 33 | + ] |
| 34 | + } |
| 35 | + subnets: [for subnet in vnet.subnets: { |
| 36 | + name: subnet.name |
| 37 | + properties: { |
| 38 | + addressPrefix: subnet.subnetPrefix |
| 39 | + } |
| 40 | + }] |
| 41 | + } |
| 42 | +}] |
| 43 | +``` |
| 44 | + |
| 45 | +## 🚀 Deployment |
| 46 | + |
| 47 | +> [!NOTE] |
| 48 | +> You need to have a resource group deployed before trying this out. |
| 49 | +
|
| 50 | +In VisualStudio Code open a terminal and run: |
| 51 | + |
| 52 | +CLI |
| 53 | + |
| 54 | +```bash |
| 55 | +az login |
| 56 | +az account set --subscription 'subscription name or id' |
| 57 | +az deployment group create -g 'your-rg' --confirm-with-what-if -f '.\main.bicep' |
| 58 | +``` |
| 59 | + |
| 60 | +or PowerShell |
| 61 | + |
| 62 | +```powershell |
| 63 | +Connect-AzAccount |
| 64 | +Set-AzContext -Subscription "subscription name or id" |
| 65 | +New-AzResourceGroupDeployment -Confirm -ResourceGroup "your-rg -TemplateFile "main.bicep" |
| 66 | +``` |
0 commit comments