Skip to content
Tutorials Center
My learning

Topics

Lesson 37 of 57 ยท Infrastructure as Code and DevOps

Bicep and ARM Templates

Describe Azure infrastructure in code with Bicep: parameters, variables, resources, modules, outputs, what-if previews and how Bicep compiles to ARM JSON.

Clicking through the portal is a fine way to learn Azure and a poor way to run it. Nobody remembers every setting they changed, a second environment never quite matches the first, and when something breaks there is no record of what was different. Infrastructure as Code (IaC) fixes this by describing your resources in text files. The files live in Git, are reviewed like application code, and can be deployed again and again to create the same environments (dev, test, production) with only a few values changed.

Azure's own IaC language is Bicep. It is a readable, declarative language that compiles to ARM templates, the JSON format that Azure Resource Manager understands. You write Bicep; Azure runs ARM JSON. Deploying needs an Azure account, so the Bicep and commands here are read-only. The runnable examples are JavaScript stand-ins that expand a small template with parameters and that model the idempotent behavior of a deployment.

Declarative and idempotent

Bicep is declarative: you state what should exist ("a storage account with these settings"), not what steps to run. Azure Resource Manager compares your description with what is already in the resource group and works out the changes.

That makes deployments idempotent: running the same template twice leaves the same result. The first run creates things; the second finds nothing to change. Idempotency is what makes IaC safe to repeat from a pipeline (see CI/CD with GitHub Actions and Azure DevOps).

A first Bicep file

Create a file named main.bicep (read-only example):

BICEP
@description('Short prefix: 3 to 11 lowercase letters or digits')
@minLength(3)
@maxLength(11)
param storagePrefix string

@allowed([
  'dev'
  'prod'
])
param environment string = 'dev'

param location string = resourceGroup().location

var storageName = '${storagePrefix}${uniqueString(resourceGroup().id)}'
var skuName = environment == 'prod' ? 'Standard_GRS' : 'Standard_LRS'

resource storage 'Microsoft.Storage/storageAccounts@2023-05-01' = {
  name: storageName
  location: location
  kind: 'StorageV2'
  sku: {
    name: skuName
  }
  properties: {
    minimumTlsVersion: 'TLS1_2'
    allowBlobPublicAccess: false
  }
  tags: {
    environment: environment
  }
}

resource blobService 'Microsoft.Storage/storageAccounts/blobServices@2023-05-01' = {
  parent: storage
  name: 'default'
}

resource logs 'Microsoft.Storage/storageAccounts/blobServices/containers@2023-05-01' = {
  parent: blobService
  name: 'logs'
}

output blobEndpoint string = storage.properties.primaryEndpoints.blob

Walk through the parts:

  • param declares an input. A parameter with = value has a default; one without must be supplied. Decorators such as @minLength, @allowed and @description add validation and documentation. Never put secrets in parameters unless you mark them @secure().
  • var names a computed value. uniqueString() returns a deterministic 13-character hash, handy for globally unique names such as storage accounts (3 to 24 lowercase letters and digits, so a prefix of at most 11 characters plus the 13 hash characters fits).
  • resource declares one resource: a symbolic name you use inside the file (storage), then the type and API version in quotes, then the body. The name property is the Azure name, which is different from the symbolic name.
  • parent nests a child resource under its parent.
  • output returns a value after deployment, for scripts or other modules.

Bicep works out the order automatically. blobService refers to storage, so Bicep knows the account must exist first. Where there is no natural reference you can add dependsOn, but you rarely need it.

Other features you will meet quickly: string interpolation '${x}-web', conditions (resource x '...' = if (deployIt) { ... }), loops ([for name in names: { ... }]), and existing to refer to a resource that was created elsewhere.

Modules

A module is a Bicep file used by another Bicep file. Modules keep large deployments readable and let you reuse a pattern, such as "a web app with its plan".

BICEP
module web 'modules/webapp.bicep' = {
  name: 'webDeployment'
  params: {
    appName: 'shop-${environment}'
    location: location
    planSkuName: environment == 'prod' ? 'P1v3' : 'B1'
  }
}

output webHost string = web.outputs.defaultHostName

And modules/webapp.bicep:

BICEP
param appName string
param location string
param planSkuName string

resource plan 'Microsoft.Web/serverfarms@2023-12-01' = {
  name: 'plan-${appName}'
  location: location
  kind: 'linux'
  sku: {
    name: planSkuName
  }
  properties: {
    reserved: true
  }
}

resource site 'Microsoft.Web/sites@2023-12-01' = {
  name: appName
  location: location
  properties: {
    serverFarmId: plan.id
    httpsOnly: true
  }
}

output defaultHostName string = site.properties.defaultHostName

The parent file passes parameters in and reads outputs back. Teams often publish shared modules to a private registry so every project uses the same hardened pattern.

Deploying, previewing and compiling

Terminal
az group create --name shop-dev-rg --location westeurope

# Preview the changes without making any
az deployment group what-if \
  --resource-group shop-dev-rg \
  --template-file main.bicep \
  --parameters storagePrefix=shop environment=dev

# Deploy
az deployment group create \
  --resource-group shop-dev-rg \
  --template-file main.bicep \
  --parameters storagePrefix=shop environment=dev

# Compile to ARM JSON, or convert JSON back into Bicep
az bicep build --file main.bicep
az bicep decompile --file main.json

What-if shows a colored preview of what would be created, modified or deleted. Make it a habit before every production deployment, and run it in your pipeline for pull requests.

The deployment scope matters. az deployment group create targets a resource group. There are also az deployment sub create (subscription level, for creating resource groups and policies), az deployment mg create (management group) and az deployment tenant create. The file chooses its scope with targetScope = 'subscription'; the default is the resource group.

Deployment mode is another important switch:

  • Incremental (default): resources in the template are created or updated; other resources in the group are left alone.
  • Complete: resources in the group that are not in the template are deleted. It is powerful and dangerous, so use what-if first.

What Bicep compiles to

az bicep build produces an ARM template. A shortened excerpt of the result for the file above looks like this (read-only; the real output has extra metadata):

JSON
{
  "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#",
  "contentVersion": "1.0.0.0",
  "parameters": {
    "storagePrefix": { "type": "string", "minLength": 3, "maxLength": 11 },
    "environment": {
      "type": "string",
      "defaultValue": "dev",
      "allowedValues": [ "dev", "prod" ]
    }
  },
  "resources": [
    {
      "type": "Microsoft.Storage/storageAccounts",
      "apiVersion": "2023-05-01",
      "name": "[format('{0}{1}', parameters('storagePrefix'), uniqueString(resourceGroup().id))]",
      "kind": "StorageV2"
    }
  ]
}

The JSON does the same job but is noisier: every expression is a string wrapped in square brackets and written with functions. Because Bicep compiles to ARM, anything ARM can deploy, Bicep can too, and new Azure features are available in Bicep on day one.

flowchart LR
  B["main.bicep<br/>+ modules"] -- "az bicep build" --> J["ARM template<br/>(JSON)"]
  J --> R["Azure Resource Manager"]
  P["parameters"] --> R
  R -- "create or update" --> Res["Resources in the group"]

Bicep is a friendlier front end; Azure Resource Manager always receives an ARM template.

Expanding a template: a stand-in

The real compiler and Resource Manager are not available here. The stand-in below keeps the middle step: take a template and some parameter values, apply defaults, check the decorators, compute variables, and produce the final resource list. The template is written as JavaScript functions for brevity, and uniqueString is only a stand-in hash, not Azure's algorithm, so the names it produces will differ from real ones.

JS Expand a template with parameters

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The same template produced a locally redundant account for dev and a geo-redundant one for prod: one description, many environments. The rejected cases fail before anything is created, just as decorators do in a real deployment.

Incremental and complete deployments: a stand-in

The second stand-in models a resource group as a map of resources and a deployment engine that compares desired against actual. It shows the three outcomes of a what-if (create, modify, no change), the idempotent second run, and the difference between incremental and complete mode.

JS Idempotent deployments and complete mode

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The second deployment reports "no change" for every resource: that is idempotency. Complete mode removed the hand-made disk, which is exactly why it needs care. Real what-if output is richer: it lists the individual properties that would change.

Bicep or Terraform?

Bicep is made for Azure only and has no state file to manage, because Azure Resource Manager itself is the source of truth. Terraform on Azure works across clouds and keeps its own state. If your estate is Azure-only, Bicep is the simplest choice; if you manage several clouds or services, Terraform's wider provider ecosystem may win. Both beat clicking in the portal.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does it mean that a Bicep deployment is idempotent?

    Because Bicep describes desired state, a second run finds nothing to change and leaves the environment as it was.
  2. 2. What does az bicep build produce?

    Bicep compiles to ARM JSON, which is what Azure Resource Manager actually deploys.
  3. 3. You want to see what a deployment would change without changing anything. Which feature do you use?

    The what-if operation compares your template with the resource group and reports creates, modifications and deletes without applying them.
  4. 4. A resource group contains a hand-made disk that is not in your template. What does a Complete-mode deployment do to it?

    In Complete mode, resources in the group that the template does not declare are deleted. Incremental mode leaves them untouched.
  5. 5. In Bicep, what is the symbolic name of a resource used for?

    The symbolic name exists only in the file. The Azure name is set by the name property.

Summary

  • Infrastructure as Code describes resources in files so environments are repeatable, reviewable and versioned.
  • Bicep is a declarative Azure language that compiles to ARM JSON; Azure Resource Manager always deploys the ARM template.
  • A file contains parameters (with decorators), variables, resources (symbolic name, type@apiVersion, body), modules and outputs; dependencies are inferred from references.
  • Deployments are idempotent: unchanged resources report no change.
  • Run what-if before deploying; know that Complete mode deletes undeclared resources.
  • Choose the scope (resource group, subscription, management group, tenant) with the matching az deployment command.

Next: Terraform on Azure.