if-elseif-else in Azure Bicep

Azure Bicep supports conditional deployments making it easy to create resources depending on external factors such as the current environment. And while the official docs show a simple example with just if-statements it’s also possible to have a bit more complex scenarios with multiple chained if-else-blocks.

Bicep does not have normal if-else-blocks as known from basically any programming language. It does support the ternary conditional operator though so you can write things like:

var res = isProd ? prodResource : testResource

And by chaining you can add multiple conditions, e.g.:

var res = isProd ? prodResource : isTest ? testResource : devResource

Below you can see how this might be used in a bicep file to create different storage accounts depending on the stage and returning the name as an output. For brevity reasons we’re working with existing resource here. Not that mult-line statements are also supported to keep the code readable.

param stage string = 'prod'
var isProd = stage == 'prod'
var isTest = stage == 'test'
var isDev = stage == 'dev'
resource saProd 'Microsoft.Storage/storageAccounts@2022-09-01' existing = if (isProd) {
name: 'prodstorageaccounttp'
}
resource saTest 'Microsoft.Storage/storageAccounts@2022-09-01' existing = if (isTest) {
name: 'teststorageaccounttp'
}
resource saDev 'Microsoft.Storage/storageAccounts@2022-09-01' existing = if (isDev) {
name: 'devstorageaccounttp'
}
// supports multi-line and multiple conditions
output saName string = isProd ? saProd.name
: isTest ? saTest.name
: isDev ? saDev.name
: 'unknown'
view raw elseif.bicep hosted with ❤ by GitHub

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.