Cloud can be tricky sometimes. Find out what scenarios we've ran into that are worth being mentioned and explained.
When working with Azure Bicep, handling null values correctly is essential to prevent deployment failures and ensure templates behave as expected. While most developers are familiar with arithmetic (+, -) and comparison (==, !=) operators, Bicep also provides nullability operators that help manage null values effectively.
Bicep
var varVmSkus = [
{ name: 'Standard_DS3_v2' price: 200 }
{ name: 'Standard_B2s' price: 100 }
]
output outSelectedSku object = first(filter(varVmSkus, sku => sku.price < 150))
Bicep
output outSelectedSku object = first(filter(varVmSkus, sku => sku.price < 150))!
Why Use It?
Bicep
param parNsgName string?
resource resNetworkSecurityGroup 'Microsoft.Network/networkSecurityGroups@2023-04-01' = {
name: parNsgName ?? 'default-nsg'
location: resourceGroup().location
}
How It Works:
Bicep
param parNsgName string?
var varBackupName = 'backup-nsg'
resource resNetworkSecurityGroup 'Microsoft.Network/networkSecurityGroups@2023-04-01' = {
name: parNsgName ?? varBackupName ?? 'final-default-nsg'
}
In this case:
Bicep
param parVmPublicIp object?
resource resVirtualMachine 'Microsoft.Compute/virtualMachines@2023-07-01' = {
name: 'example-vm'
location: resourceGroup().location
properties: {
networkProfile: {
networkInterfaces: [
{
id: parVmPublicIp.id
}
]
}
}
}
If parVmPublicIp is null (i.e., the VM has no public IP), referencing .id will cause a deployment failure.
Bicep
resource resVirtualMachine 'Microsoft.Compute/virtualMachines@2023-07-01' = {
name: 'example-vm'
location: resourceGroup().location
properties: {
networkProfile: {
networkInterfaces: [
{
id: parVmPublicIp.?id
}
]
}
}
}
Now, if parVmPublicIp is null, .id will not be accessed, and the deployment will not fail.
id: contains(parVmPublicIp, 'id') ? parVmPublicIp.id : null