Skip to content
Visual explainer 3h 30m to learn 5 steps

Reproducible Azure infrastructure with Bicep

Write a Bicep template with parameters, modules and outputs, preview it with what-if and deploy it.

By Invicly Tech, , in Microsoft Azure Cloud Engineering. About 12 minutes to read.

Topic 20 of 33

In short

Bicep is Azure's own language for describing infrastructure as code. You declare the resources you want, Azure Resource Manager works out how to create or update them, and the same file builds the same environment every time. Parameters, modules and outputs keep templates reusable, and what-if shows the changes before anything is touched.

Think of it like this: A Bicep file is a recipe, and Azure Resource Manager is the cook who checks the kitchen and only makes what is missing.

Explained simply

Clicking through the Azure portal is a good way to learn, but it is hard to repeat exactly. Next month you will not remember every setting you chose. Infrastructure as code fixes that: you write the setup down in a file, keep it in Git, and let a tool build it the same way every time.

Bicep is Microsoft's language for this. A Bicep file lists the resources you want, such as a storage account or a web app, and their settings. You do not write the steps to create them. Azure Resource Manager, the service behind every Azure change, reads the file and works out what to create or update.

Parameters let one file serve many environments. The same template can build a small dev setup and a larger production setup by passing different values. Modules split a big file into smaller ones, and outputs pass useful values, such as a web address, back to you.

Before you deploy, you can ask Azure for a preview called what-if. It lists what would be created, changed or deleted. Reading that list is the habit that stops most accidents.

Press Play on a diagram to walk through it one step at a time.

FlowFrom Bicep file to deployed resources
  1. 1
    Write main.bicep

    Parameters, resources, modules, outputs

  2. 2
    Build

    Bicep compiles to an ARM JSON template

  3. 3
    What-if

    Preview create, modify and delete

  4. 4
    Deploy

    Resource Manager creates or updates in dependency order

  5. 5
    Outputs

    IDs and host names for the next step

ComparePortal clicks, ARM JSON or Bicep
Portal
  • Good for exploring
  • Hard to repeat exactly
  • No review before change
  • Drift is invisible
ARM JSON
  • Same engine as Bicep
  • Verbose and hard to read
  • Explicit dependsOn everywhere
  • Still accepted by all tools
Bicep
  • Short, typed syntax
  • Implicit dependencies
  • Modules and parameter files
  • Compiles to ARM JSON

In depth

The parts of a Bicep file

A Bicep file has a few kinds of statement. param declares an input, with an optional default and decorators such as @allowed, @minLength, @description and @secure for passwords, which keeps them out of logs. var holds a computed value, such as a name built from the environment. resource declares an Azure resource with a symbolic name, a type and an API version, for example Microsoft.Storage/storageAccounts@2023-05-01, then its properties. module deploys another Bicep file. output returns values. Functions help with names and locations: resourceGroup().location gives the group's region, and uniqueString(resourceGroup().id) gives a stable 13-character hash, handy for globally unique names. Editor support in VS Code, through the Bicep extension, checks types and property names as you type.

  • param: input, validated by decorators
  • var: computed value
  • resource: what to deploy, with API version
  • module: another Bicep file
  • output: value returned after deployment

Modules and deployment scope

A module is just another Bicep file called from the main one. Give each module one concern, such as storage, the app, or monitoring, with clear parameters and outputs. The main file then reads like a table of contents. Each deployment has a target scope. The default is a resource group, deployed with az deployment group create. A file that starts with targetScope = 'subscription' can create resource groups and then deploy modules into them by setting scope: rg on the module; you deploy that with az deployment sub create and a location for the deployment record. Shared modules can live in a private Bicep registry, and Microsoft publishes Azure Verified Modules, a set of tested modules for common resources, which are worth reading even if you write your own.

MapA small Bicep project layout
infra/
  • main.bicep
    • Parameters for env and location
    • Calls each module
    • Outputs the app URL
  • modules/
    • storage.bicep
    • app.bicep
    • monitoring.bicep
  • dev.bicepparam
    • using './main.bicep'
    • env = 'dev', small SKUs
  • prod.bicepparam
    • using './main.bicep'
    • env = 'prod', zone-redundant SKUs

How dependencies are worked out

Resource Manager deploys resources in parallel unless one depends on another. In Bicep you rarely write the dependency yourself. When the web app's settings mention st.name or st.properties.primaryEndpoints.blob, Bicep sees the reference and makes the app wait for the storage account. The same happens when the main file passes a module output into another module. Child resources use the parent property, for example a blob container whose parent is the blob service. To use something that already exists, declare it with the existing keyword: Bicep reads it but never changes it. dependsOn is for the rare case where order matters but no property is referenced. Too many manual dependsOn entries slow deployments and usually mean a reference is missing.

  • Reference a property: implicit dependency
  • parent: for child resources
  • existing: read, never modify
  • dependsOn: only when no reference exists

What-if and deployment modes

az deployment group what-if sends your template to Resource Manager and returns a list of changes without applying them. Each resource is marked Create, Modify, Delete, NoChange, Ignore or Deploy, and Modify shows the property-level difference, such as a SKU going from Standard_LRS to Standard_ZRS. Some results are noise, for example properties Azure fills in itself, so read with care rather than trusting a short list blindly. The default deployment mode is incremental: resources in the template are created or updated, and anything else in the resource group is left alone. Complete mode deletes resources that are not in the template, which is powerful and dangerous. For managed deletion, deployment stacks are the newer option. Add --confirm-with-what-if to az deployment group create to see the preview and answer yes before it runs.

Troubleshooting and rollback

If a deployment fails, look at the deployment record. The portal shows it under the resource group's Deployments page, and az deployment operation group list shows each operation and its error. Common causes are a name already taken by someone else (storage account names are global), a property not valid for that API version, a missing resource provider registration, or a policy deny such as RequestDisallowedByPolicy, which needs the template changed or a policy exemption. Bicep has no separate state file: Azure itself is the record of what exists, so drift appears in what-if. To undo a bad change, redeploy the previous commit of the template. The --rollback-on-error flag redeploys the last successful deployment automatically when a new one fails, which helps, but only for resources the templates describe.

FlowFixing a failed deployment
  1. 1
    Read the error

    Deployments page or deployment operation list

  2. 2
    Classify it

    Name taken, invalid property, provider, policy

  3. 3
    Fix the template

    Never patch by hand in the portal

  4. 4
    What-if again

    Confirm only the intended change remains

  5. 5
    Redeploy

    Or redeploy the last good commit to roll back

Learn it in 5 short steps

About 40m each. Track them with a timer in your plan.

  1. 1
    Declare resources and parameters~40m
  2. 2
    Split into modules~40m
  3. 3
    Reference dependencies~40m
  4. 4
    Return outputs~40m
  5. 5
    Preview with what-if~40m

Key points

  • Bicep is declarative: you describe the end state, not the steps.
  • Referencing one resource from another creates the dependency automatically.
  • Modules split a template into reusable files with their own parameters and outputs.
  • Deployments are incremental by default: resources missing from the file are left alone.
  • Run what-if before every deployment to shared or production environments.

Key terms

Tap a card to flip it. 0/6 known

Examples

bicep
@allowed(['dev', 'prod'])
param env string
param location string = resourceGroup().location

resource st 'Microsoft.Storage/storageAccounts@2023-05-01' = {
  name: 'st${env}${uniqueString(resourceGroup().id)}'
  location: location
  sku: { name: env == 'prod' ? 'Standard_ZRS' : 'Standard_LRS' }
  kind: 'StorageV2'
  properties: { minimumTlsVersion: 'TLS1_2', allowBlobPublicAccess: false }
}

output storageId string = st.id

Preview with az deployment group what-if -g rg-app-dev -f main.bicep -p env=dev, then deploy with az deployment group create.

Main file using a storage module

Prerequisites: Azure CLI with Bicep (az bicep install), and permission to create a resource group in a lab subscription. Step 1: save the storage example from the explainer as modules/storage.bicep. Step 2: write main.bicep below, which calls the module and passes its output into an output of its own. Step 3: create the group with az group create -n rg-bicep-lab -l westeurope. Step 4: run what-if; expect one Create for the storage account. Step 5: deploy. Evidence: az deployment group show -g rg-bicep-lab -n main --query properties.outputs returns the blob endpoint. Cleanup: az group delete -n rg-bicep-lab --yes.

bicep
@allowed(['dev', 'prod'])
param env string = 'dev'

module storage 'modules/storage.bicep' = {
  name: 'storage'
  params: { env: env }
}

output storageId string = storage.outputs.storageId

// az deployment group what-if -g rg-bicep-lab -f main.bicep -p env=dev
// az deployment group create -g rg-bicep-lab -f main.bicep -p env=dev

Catching a risky change with what-if

A colleague changes the storage module so the SKU depends on a new parameter, but the production parameter file still passes the old value. Step 1: run what-if against production with prod.bicepparam. Step 2: the output shows Modify on the storage account with sku.name changing from Standard_ZRS to Standard_LRS, which would reduce redundancy. Step 3: stop, fix the parameter file, and run what-if again. Step 4: the storage account now shows NoChange and only the intended app setting shows Modify. Step 5: deploy. Nothing reached production that the team had not seen first.

bash
az deployment group what-if -g rg-shop-prod \
  -f infra/main.bicep -p infra/prod.bicepparam
# ~ Microsoft.Storage/storageAccounts/stprod...
#   ~ sku.name: "Standard_ZRS" => "Standard_LRS"
# fix prod.bicepparam, then:
az deployment group create -g rg-shop-prod \
  -f infra/main.bicep -p infra/prod.bicepparam --confirm-with-what-if

Quick reference

  • Preview: az deployment group what-if -g RG -f main.bicep -p env=dev
  • Deploy with a prompt: az deployment group create ... --confirm-with-what-if
  • Subscription scope: targetScope = 'subscription' and az deployment sub create -l LOCATION
  • Unique names: uniqueString(resourceGroup().id) gives a stable 13-character string
  • Module output: moduleName.outputs.outputName
  • Use @secure() for passwords and keys so they are not logged
  • Default mode is incremental; complete mode deletes resources not in the template
  • Compile and lint locally: az bicep build -f main.bicep

Common mistakes

  • Changing resources by hand in the portal, so the next deployment silently reverts or conflicts with your change.
  • Using complete mode without reading what-if, which deletes resources not in the template.
  • Hard-coding names and secrets instead of parameters, uniqueString and Key Vault references.

Quick quiz

Pick an answer to see if you're right and why.

Question 1

1Your app resource sets an app setting to st.properties.primaryEndpoints.blob. What does Bicep do?

Question 2

2Which deployment mode deletes resources in the resource group that are not in the template?

Question 3

3What does what-if do?

Question 4

4How do you mark a parameter that holds a database password?

Question 5

5A deployment fails with RequestDisallowedByPolicy. What is the right fix?

0/5 answered

Practice exercises

Try each one yourself first. Use the hint if you get stuck, then compare with the solution.

  1. Exercise 1easy

    Add an object parameter named tags to the storage template, with a default owner and cost centre, apply it to the storage account, and output the account name.

  2. Exercise 2medium

    Write a bicepparam file for dev and one for prod for the main template, then preview both with what-if.

  3. Exercise 3hard

    Write a subscription-scoped main file that creates the resource group rg-app-ENV and deploys the storage module into it. Give the deploy command and cleanup.

Check yourself

Answer in your head, reveal, then be honest with yourself.

Feel confident about this topic?

Frequently asked questions

Should I learn Bicep or Terraform?
Bicep if you only target Azure and want no state file to manage. Terraform if you deploy to several clouds or your team already uses it. The concepts carry over either way.
Does Bicep keep a state file like Terraform?
No. Azure Resource Manager is the source of truth, and what-if compares your template with the live resources each time.
Can I convert an existing resource group into Bicep?
Yes, as a starting point. Export the template from the portal or use az bicep decompile on ARM JSON, then clean up names, parameters and hard-coded values by hand.
Does deploying the same template twice create duplicates?
No. Deployments are idempotent: resources with the same name and type are updated to match, and unchanged ones are left as they are.

Go deeper

ShareXLinkedInWhatsApp