Conditional deployments in Bicep with the if expression
Article
To optionally deploy a resource or module in Bicep, use the if expression. An if expression includes a condition that resolves to true or false. When the if condition is true, the resource is deployed. When the value is false, the resource isn't created. The value can only be applied to the whole resource or module.
Note
Conditional deployment doesn't cascade to child resources. If you want to conditionally deploy a resource and its child resources, you must apply the same condition to each resource type.
In Bicep, you can conditionally deploy a resource by passing in a parameter that specifies whether the resource is deployed. You test the condition with an if expression in the resource declaration. The following example shows the syntax for an if expression in a Bicep file. It conditionally deploys a DNS zone. When deployZone is true, it deploys the DNS zone. When deployZone is false, it skips deploying the DNS zone.
Bicep
paramdeployZoneboolresourcednsZone'Microsoft.Network/dnsZones@2023-07-01-preview' = if (deployZone) {
name: 'myZone'location: 'global'
}
The next example conditionally deploys a module.
Bicep
paramdeployZoneboolmodulednsZone'dnszones.bicep' = if (deployZone) {
name: 'myZoneModule'
}
Conditions may be used with dependency declarations. For explicit dependencies, Azure Resource Manager automatically removes it from the required dependencies when the resource isn't deployed. For implicit dependencies, referencing a property of a conditional resource is allowed but may produce a deployment error.
New or existing resource
You can use conditional deployment to create a new resource or use an existing one. The following example shows how to either deploy a new storage account or use an existing storage account.
When the parameter newOrExisting is set to new, the condition evaluates to true. The storage account is deployed. Otherwise the existing storage account is used.
Warning
If you reference a conditionally-deployed resource that is not deployed. You will get an error saying the resource is not defined in the template.
Runtime functions
If you use a reference or list function with a resource that is conditionally deployed, the function is evaluated even if the resource isn't deployed. You get an error if the function refers to a resource that doesn't exist.
Use the conditional expression ?: operator to make sure the function is only evaluated for conditions when the resource is deployed. The following example template shows how to use this function with expressions that are only conditionally valid.
Build end-to-end solutions in Microsoft Azure to create Azure Functions, implement and manage web apps, develop solutions utilizing Azure storage, and more.