OnCallReadyStart learning

Azure Lesson 33.4 · Azure V: Compute, App Hosting & the AZ-104 exam · 24 min read

Bicep: the same deployments, in a language people can read

In plain words

Bicep is the same shopping list as an ARM template, written so people can read it. Instead of a page of JSON with brackets and quotes, you write "resource sa 'Microsoft.Storage/storageAccounts@2023-05-01' = { name: ..., location: ... }" and Bicep turns it into the JSON for you.

Azure never sees Bicep: the CLI compiles it to an ARM template first. So everything you know about templates - parameters, what-if, Incremental and Complete - still applies.

Bicep: the same deployments, in a language people can read

The ARM template from the last lesson is 60 lines of JSON for one storage account and a loop of containers, half of it brackets and parameters('...'). Bicep is Microsoft's answer: a small language that compiles to exactly that JSON. Nothing changes on the Azure side - ARM still receives a template, still runs what-if and still records a deployment - but the file you review in a pull request is a third of the size and catches typos before anything is sent. New Azure work that is not Terraform is usually Bicep now, and AZ-104 asks you to read and modify a Bicep file as often as an ARM template.

Need to know: param, var, resource, module and output declarations; a resource is resource SYMBOL 'Type@apiVersion' = { ... }, and SYMBOL.id, SYMBOL.name, SYMBOL.properties.x refer to it - those references create the dependsOn for you. Decorators such as @allowed([...]), @minLength(3), @secure() and @description('...') sit on the line above a param. '${a}-${b}' is string interpolation. az bicep build compiles to ARM JSON, az bicep decompile goes the other way (best effort), and az deployment group create -f main.bicep compiles on the fly. Bicep has no state file: Azure itself is the state, unlike Terraform.

Reading a Bicep file

$ cd ~/oncall-lab/labs/4b-azure/az5/bicep
$ cat web.bicep
// The reporting web app: an App Service plan and one Linux web app.
@description('Short name of the app, used in every resource name')
@minLength(3)
@maxLength(12)
param app string = 'reports'

@allowed([
  'B1'
  'S1'
  'P1v3'
])
param sku string = 'B1'

param location string = resourceGroup().location

var planName = 'plan-${app}'
var siteName = '${app}-${uniqueString(resourceGroup().id)}'

resource plan 'Microsoft.Web/serverfarms@2024-04-01' = {
  name: planName
  location: location
  kind: 'linux'
  sku: {
    name: sku
  }
  properties: {
    reserved: true
  }
}

resource site 'Microsoft.Web/sites@2024-04-01' = {
  name: siteName
  location: location
  properties: {
    serverFarmId: plan.id
    httpsOnly: true
    siteConfig: {
      linuxFxVersion: 'NODE|22-lts'
      minTlsVersion: '1.2'
    }
  }
}

output url string = 'https://${site.properties.defaultHostName}'

Top to bottom:

  • param with a type and an optional default (= 'reports'). The decorators above it are the ARM minLength, maxLength, allowedValues and metadata.description you saw in JSON. A param without a default must be given at deployment time; @secure() makes a string a securestring.
  • var - computed once. 'plan-${app}' is interpolation; it compiles to format().
  • resource plan 'Microsoft.Web/serverfarms@2024-04-01' - plan is a symbolic name used only inside this file; the Azure name is the name: property. The type and API version are joined with @.
  • serverFarmId: plan.id - a reference to the other resource. This is the line that makes Bicep deploy the plan before the site: you never write dependsOn unless there is no reference.
  • output url string = 'https://${site.properties.defaultHostName}' - read after deployment.

Objects and arrays have no commas between items: one property or element per line. Comments are // and /* */. That is most of the language.

What it compiles to

$ az bicep build -f web.bicep
$ jq '.resources[1] | {type, name, dependsOn}' web.json
{
  "type": "Microsoft.Web/sites",
  "name": "[variables('siteName')]",
  "dependsOn": [
    "[resourceId('Microsoft.Web/serverfarms', variables('planName'))]"
  ]
}
$ jq '.outputs.url.value' web.json
"[format('https://{0}', reference(resourceId('Microsoft.Web/sites', variables('siteName')), '2024-04-01').defaultHostName)]"

The dependsOn you did not write is there, built with resourceId(). site.properties.defaultHostName became reference(resourceId('Microsoft.Web/sites', ...), '2024-04-01').defaultHostName. Everything the previous lesson taught about ARM expressions still applies - Bicep only writes them for you. That is also why you can always answer "what will this Bicep file deploy?" by building it and reading the JSON, and why the exam can ask the same question in either language.

Deploying, with parameters and a .bicepparam file

$ az deployment group what-if -g rg-az5-bicep -f web.bicep
Note: The result may contain false positive predictions (noise).
You can help us improve the accuracy of the result by opening an issue here: https://aka.ms/WhatIfIssues

Resource and property changes are indicated with these symbols:
  + Create

The deployment will update the following scope:

Scope: /subscriptions/00000000-1111-2222-3333-444444444444/resourceGroups/rg-az5-bicep

  + Microsoft.Web/serverfarms/plan-reports [2024-04-01]

      apiVersion:          "2024-04-01"
      id:                  "/subscriptions/00000000-1111-2222-3333-444444444444/resourceGroups/rg-az5-bicep/providers/Microsoft.Web/serverfarms/plan-reports"
      kind:                "linux"
      location:            "westeurope"
      name:                "plan-reports"
      properties.reserved: true
      sku.name:            "B1"
      type:                "Microsoft.Web/serverfarms"

  + Microsoft.Web/sites/reports-bglyiztsj5haz [2024-04-01]

      apiVersion:                           "2024-04-01"
      id:                                   "/subscriptions/00000000-1111-2222-3333-444444444444/resourceGroups/rg-az5-bicep/providers/Microsoft.Web/sites/reports-bglyiztsj5haz"
      location:                             "westeurope"
      name:                                 "reports-bglyiztsj5haz"
      properties.httpsOnly:                 true
      properties.serverFarmId:              "/subscriptions/00000000-1111-2222-3333-444444444444/resourceGroups/rg-az5-bicep/providers/Microsoft.Web/serverfarms/plan-reports"
      properties.siteConfig.linuxFxVersion: "NODE|22-lts"
      properties.siteConfig.minTlsVersion:  "1.2"
      type:                                 "Microsoft.Web/sites"

Resource changes: 2 to create.
$ az deployment group create -g rg-az5-bicep -f web.bicep --query properties.outputs.url.value -o tsv
https://reports-bglyiztsj5haz.azurewebsites.net

-f takes the .bicep file directly; the CLI compiles it (with its bundled Bicep CLI, az bicep version) and sends the JSON. Parameters work exactly as for JSON (-p sku=S1). Bicep also has its own parameter file format, .bicepparam, which names the Bicep file it belongs to and is checked against it:

$ cat web.prod.bicepparam
using './web.bicep'

param app = 'reports'
param sku = 'S1'
$ az deployment group what-if -g rg-az5-bicep -f web.bicep -p web.prod.bicepparam
Note: The result may contain false positive predictions (noise).
You can help us improve the accuracy of the result by opening an issue here: https://aka.ms/WhatIfIssues

Resource and property changes are indicated with these symbols:
  ~ Modify
  = Nochange

The deployment will update the following scope:

Scope: /subscriptions/00000000-1111-2222-3333-444444444444/resourceGroups/rg-az5-bicep

  ~ Microsoft.Web/serverfarms/plan-reports [2024-04-01]
    ~ sku.name: "B1" => "S1"

  = Microsoft.Web/sites/reports-bglyiztsj5haz [2024-04-01]

Resource changes: 1 to modify, 1 no change.

The plan moves from B1 to S1 (scale up: same instances, bigger tier) and nothing else changes. A classic JSON parameter file (-p @params.json) also works with a Bicep file.

When the file is wrong

Bicep catches mistakes before anything reaches Azure. Rename the location parameter and leave the resources using the old name:

$ sed -i 's/^param location string/param region string/' web.bicep
$ az bicep build -f web.bicep
/home/learner/oncall-lab/labs/4b-azure/az5/bicep/web.bicep(14,7) : Warning no-unused-params: Parameter "region" is declared but never used. [https://aka.ms/bicep/linter-diagnostics#no-unused-params]
ERROR: /home/learner/oncall-lab/labs/4b-azure/az5/bicep/web.bicep(21,13) : Error BCP057: The name "location" does not exist in the current context. [https://aka.ms/bicep/core-diagnostics#BCP057]
/home/learner/oncall-lab/labs/4b-azure/az5/bicep/web.bicep(33,13) : Error BCP057: The name "location" does not exist in the current context. [https://aka.ms/bicep/core-diagnostics#BCP057]

Every diagnostic has the file, (line,column), a severity, a code and a link. BCP082 / BCP057: a name that does not exist. The linter's no-unused-params warning catches the parameter nobody uses. The same errors stop az deployment group create: nothing is deployed. Codes you will meet:

codemeaning
BCP057 / BCP082the name does not exist (082: "Did you mean ...?")
BCP018 / BCP019expected a character / a new line (a missing } or a comma-separated object)
BCP029not a valid resource type ('Type@apiVersion')
BCP035 / BCP037a required property is missing / a property is not allowed on this type
BCP028the same identifier declared twice
no-unused-params, no-unused-varslinter warnings: declared, never used
$ sed -i 's/^param region string/param location string/' web.bicep
$ az bicep build -f web.bicep && echo ok
ok

Changing a Bicep file safely

The usual modifications, all on the file you have:

  • a new parameter with a default, so existing callers keep working: param alwaysOn bool = false;
  • a new property, wired to it: siteConfig: { alwaysOn: alwaysOn ... };
  • a condition: resource x '...' = if (env == 'prod') { ... } deploys it only when true;
  • a loop: resource c '...' = [for name in containers: { name: '${account.name}/default/${name}' }];
  • an existing resource you need to reference but not deploy: resource kv 'Microsoft.KeyVault/vaults@2023-07-01' existing = { name: 'kv-shop-prod' };
  • a child: parent: account instead of a /-joined name.

After each change: az bicep build (does it compile?), then what-if (does it only change what I meant?), then deploy. The mission after this lesson does exactly that.

Modules split a big file: module st './storage.bicep' = { name: 'storage', params: { env: 'prod' } } deploys another Bicep file as a nested deployment, and st.outputs.accountName reads its outputs. A module can target another resource group with scope: resourceGroup('rg-data').

Decompile: from ARM JSON to Bicep

You inherit the storage.json template from the previous lesson, or an exported one, and want it in Bicep:

$ az bicep decompile -f storage.json
WARNING: Decompilation is a best-effort process, as there is no guaranteed mapping from ARM JSON to Bicep.
You may need to fix warnings and errors in the generated bicep file(s), or decompilation may fail entirely if an accurate conversion is not possible.
If you would like to report any issues or inaccurate conversions, please see https://github.com/Azure/bicep/issues.
$ cat storage.bicep
@description('Which environment this account serves')
@allowed([
  'dev'
  'prod'
])
param env string = 'dev'

param location string = resourceGroup().location

param containers array = [
  'reports'
  'exports'
]

var name = 'st${env}${uniqueString(resourceGroup().id)}'

var sku = ((env == 'prod') ? 'Standard_ZRS' : 'Standard_LRS')

resource storageAccount 'Microsoft.Storage/storageAccounts@2023-05-01' = {
  name: name
  location: location
  tags: {
    env: env
    owner: 'platform'
  }
  sku: {
    name: sku
  }
  kind: 'StorageV2'
  properties: {
    minimumTlsVersion: 'TLS1_2'
    allowBlobPublicAccess: false
  }
}

resource container 'Microsoft.Storage/storageAccounts/blobServices/containers@2023-05-01' = [for i in range(0, length(containers)): {
    name: '${name}/default/${containers[i]}'
    properties: {
      publicAccess: 'None'
    }
    dependsOn: [
      storageAccount
    ]
}]

output accountName string = name
output blobEndpoint string = reference(name).primaryEndpoints.blob

The warning is honest: decompilation is best effort. Look at what you got. The parameters and variables came across with their decorators, format() became interpolation, if(equals(...)) became env == 'prod' ? ... : .... The copy loop is a for expression, but over range(0, length(...)) with an index rather than over the names, the explicit dependsOn stayed although a parent: would make it unnecessary, and the output still calls reference(name) instead of storageAccount.properties.primaryEndpoints.blob. It compiles and deploys the same resources - and it is a first draft:

$ az bicep build -f storage.bicep --stdout | jq '.resources | length'
2
$ az deployment group what-if -g rg-az5-bicep -f storage.bicep -p env=dev | tail -2

Resource changes: 3 to create, 2 to ignore.

The tidy-up after a decompile, in order: rename the generated symbolic names, loop over values not indexes, replace /-joined child names with parent:, delete dependsOn that references already imply, replace reference()/resourceId() calls with symbol properties, and run what-if against the real resources until it says = for everything you did not mean to change.

For a resource group that was built by hand, the route is export, then decompile: az group export -n RG > rg.json && az bicep decompile -f rg.json (the portal's Export template blade has a Bicep tab that does both). Everything the ARM lesson said about exported templates - hard-coded values, read-only properties, odd parameter names - is now in Bicep, with the same clean-up to do.

On the exam (AZ-104 3.1.3, 3.1.5): "convert an ARM template to Bicep" = az bicep decompile --file template.json (PowerShell has no cmdlet for it; it is the Bicep CLI); "deploy a Bicep file" = the same az deployment group create --template-file main.bicep / New-AzResourceGroupDeployment -TemplateFile main.bicep as for JSON. Expect questions where a Bicep excerpt has a mistake: a missing @ between type and API version, a reference to a symbol that does not exist, or a dependsOn question whose answer is "none needed, the reference implies it".

In an interview: "Bicep or Terraform?" - "Both describe the desired state and preview changes. Bicep is Azure-only, has no state file because Azure is the state, and supports every new API version on day one. Terraform works across providers and keeps a state file, which gives drift detection and imports but has to be stored and locked. In an Azure-only team I would be happy with either; in a multi-cloud platform team, Terraform."

Why it helps

Most Azure teams that do not use Terraform write Bicep today, and AZ-104 asks you to read it, change it and convert ARM JSON into it. Symbolic names (sa.id) make dependencies automatic, decorators like @allowed catch bad input before anything is created, and .bicepparam files keep each environment's values typed and checked.

Knowing it is a compiler, not a new service, also tells you where errors come from: the build step, the validation, or the deployment.

Commands in this lesson

cd cat az jq sed

FAQ

Do I need to install something for Bicep?

The Azure CLI installs the Bicep compiler the first time you use it (az bicep install, az bicep version). az deployment group create -f main.bicep compiles on the fly, so you never have to keep the JSON. az bicep build writes the JSON if you want to read it.

What is a .bicepparam file?

A parameter file written in Bicep: using './main.bicep' at the top, then param lines with values. The compiler checks it against the template - a parameter that does not exist or has the wrong type fails before deployment, which a JSON parameter file does not do. Deploy with -p prod.bicepparam.

How good is az bicep decompile?

Good enough to start from, not to ship. It turns ARM JSON into Bicep and warns about what it could not translate cleanly - copy loops, complex expressions, names it had to invent. Read the warnings, rename the symbolic names to something meaningful, build it again and compare with what-if: no changes means the conversion is faithful.

How do Bicep dependencies work?

When one resource uses another's symbolic name (storage.id, vnet.properties.subnets[0].id), Bicep adds the dependsOn in the JSON for you, so the deployment orders them correctly. You only write dependsOn by hand for a dependency that is not visible in the properties, which is rare.

Bicep or Terraform?

Both describe desired state and preview changes. Bicep is Azure-only, keeps no state file (Azure is the state) and supports new API versions immediately. Terraform works across many providers and keeps a state file, which gives drift detection and imports but must be stored and locked. Many platform teams use Terraform for multi-cloud and Bicep inside Azure-only products.

In an interview Mid

Bicep or Terraform - which would you pick for an Azure platform, and why?

Both describe the desired state and preview changes - az deployment group what-if for Bicep, terraform plan for Terraform. Bicep is Azure-only, compiles to an ARM template, keeps no state file because Azure is the state, and supports every new API version on day one. Terraform works across providers and keeps a state file, which gives drift detection and imports but has to be stored and locked. Azure-only team: either; multi-cloud platform team: Terraform.

Also asked: How do you convert an existing ARM template to Bicep? · What does a decorator like @allowed do in Bicep? · How do you handle different environments in Bicep?

Practise this lesson in the terminal Free, in your browser - a real Ubuntu terminal to try it in, with missions that check your work.