Bicep Notes

Purpose

This is to track various thoughts, code snippets, etc. on Bicep files.

Tips And Reminders

  • output items to reduce the amount of dependsOn statements
  • It is incredibly common to include the Resource Group location as the location parameter.
  • Parameters are for settings that change between deployments
    • The learn module that introduces them is another good resource
  • Variables are typically for settings that don’t change between deployments
    • Great example on conditional deployments (test vs prod) as well as iterative loops for naming conventions

Snippets

Below are what I’m tracking for personal reference, but there are entire code sites available on Microsoft Learn and across the web.

Tags

Standard tag parameter for these exercises:

param tags object = {
  environment: 'Learning'
  module: 'AZ-104'
  method: 'Bicep'
}

Dynamic Names

Dynamic names can be achieved with techniques similar to the following. I’m curious if there is an object with a shorter ID, or maybe a “Grab random X number of character selections from ‘object’” that can be used vs the entire RG.ID.

param location string = resourceGroup().location
param namePrefix string 'name_descriptor'

resource <name> <API> ={
    name: '${namePrefix}${uniqueString(resourceGroup().id)}'
}

/* For example */
param storageNamePrefix string = 'stg'
//var storageName = '${toLower(storageNamePrefix)}${uniqueString(resourceGroup().id)}'
var '${toLower(storageNamePrefix)${take(uniqueString(resourceGroup().id), 6)}}'

Conditions

Simple conditions are true or false boolean operators. Only if the statement is true does the resource deploy.

param deployStorageAccount bool

resource storageAccount 'Microsoft.Storage/storageAccounts@2021-09-01' = if (deployStorageAccount) {
  name: 'teddybearstorage'
  location: resourceGroup().location
  kind: 'StorageV2'
  // ...
}

Or conditions can be expressions, deployed only if a parameter has a specific value, or deployed in different ways depending on value.

param environmentName string = 'Dev'
param storageNamePrefix string = 'stg'
var storageName '${toLower(storageNamePrefix)${take(uniqueString(resourceGroup().id), 4)}}'

var storageAccountSku = if (environmentName == 'Dev') {
  'Standard_LRS'
} else if (environmentName == 'Test') {
  'Premium_LRS'
} else if (environmentName == 'Prod') {
  'Premium_GRS'
} else {
  throw 'Invalid environmentName. Allowed values are: Dev, Test, Prod.'
}

resource storageAccount 'Microsoft.Storage/storageAccounts@2019-06-01' = {
  name: storageName
  location: 'East US' // Specify your desired location
  sku: {
    name: storageAccountSku
  }
  kind: 'StorageV2'
}