Reading Time: 2 minutes

Using conditional deployments with Bicep and the if statement is a powerful way to make your deployment scripts more flexible and customizable. With this feature, you can specify conditions that determine whether a resource should be deployed or not based on various factors such as environment, region, or customer preferences. This can help avoid creating duplicate resources, which can cause issues with billing, access control, and other aspects of your deployment.

In this post, we’ll explore how to use an if statement in Bicep to conditionally deploy an Azure storage account resource.

Let’s start by looking at the Bicep module we’ll be using for this example:

param deployStg bool


resource stg 'Microsoft.Storage/storageAccounts@2022-09-01' = if (deployStg) {
  name: 'mystg${uniqueString(resourceGroup().id)}'
  location: resourceGroup().location
  sku: {
    name: 'Standard_LRS'
  }
  kind: 'StorageV2'
}

In the example above, we have the parameter called deployStg, which we can be either set to true or false depending on whether the storage account resource is needed and should be deployed. We’ll use this parameter in the if statement that follows, which checks if the deployStg parameter is set to false.

If deployStg is set to true, then a new storage account resource will be created with the specified name, location, SKU, and kind. The name property is set to ‘mystg‘, but you can replace it with any valid name for your storage account. The location property is set to the location of the resource group, which is obtained using the resourceGroup().location function. The sku property is set to ‘Standard_LRS‘, which is the default SKU for storage accounts. Finally, the kind property is set to ‘StorageV2‘, which is the latest version of Azure Storage.

If deployStg is set to false, the storage account resource will not be created.

To use this Bicep module in your own deployment scripts, you’ll need to set the deployStg parameter based on whether the storage account needs to be deployed. The value can be included in the template or can be specified during runtime.

For example, when value is included in the template

param deployStg bool = true

or during runtime

New-AzResourceGroupDeployment -name mystg -ResourceGroupName myrg -TemplateFile myBicepTemplate.bicep -deployStg $true

Overall, conditional deployments with Bicep offer a flexible and powerful way to manage your Azure resources. Whether you’re deploying resources to a single environment or multiple environments, using conditional deployments with Bicep can help you save time and improve the overall efficiency of your deployment process!

Thanks for reading my blog!

Feel free to drop your comment or question below.