Loops and Conditionals
You'll learn how to use Bicep's for loops to create multiple resources efficiently and if conditionals to deploy resources only when certain conditions are met.
Core Idea
When defining infrastructure, you often need to create multiple similar resources (like several storage accounts or VMs) or deploy resources only under specific circumstances (like a production database but not a dev one). Bicep's loops and conditionals let you avoid repetition and make your templates flexible.
For Loops: Creating Multiple Resources
Instead of copying and pasting resource declarations, use a for loop to iterate over an array:
param storageAccountNames array = ['storage1', 'storage2', 'storage3']
resource storageAccounts 'Microsoft.Storage/storageAccounts@2021-04-01' = [for name in storageAccountNames: {
name: name
location: resourceGroup().location
sku: {
name: 'Standard_LRS'
}
kind: 'StorageV2'
}]
This creates three storage accounts in one declaration—clean and maintainable.
Conditional Deployment with If
Deploy resources only when a condition is true:
param deployDatabase bool = true
resource sqlServer 'Microsoft.Sql/servers@2021-02-01-preview' = if (deployDatabase) {
name: 'myserver'
location: resourceGroup().location
properties: {
administratorLogin: 'sqladmin'
}
}
If deployDatabase is false, the SQL server won't be created at all.
Real-World Use
Loops avoid duplication when deploying multiple environments or resources. Conditionals let you use the same template for dev (minimal resources) and prod (full stack) by toggling parameters.
Key Takeaway: Use for expressions to create multiple resources from arrays and if expressions to conditionally deploy resources based on parameter values—making your Bicep templates flexible and DRY (Don't Repeat Yourself).