Bicep in practice: modules, what-if, deployment stacks
-
Phase 0: Before you start
-
Phase 1: The foundation
-
Phase 2: Day-to-day operations
-
Phase 3: Enterprise architecture
-
Phase 4: Troubleshooting step by step
-
Phase 5: Final project and career
Bicep modules let you build Azure templates out of small, reusable pieces, say one module for an NSG and one for a route table, with a main file that wires them together. On top of that you get what-if to preview each change before it happens, and deployment stacks to look after everything you deployed for its whole life, deletes included.
In Lesson 41 you got one resource into code, but real environments have hundreds, and then the questions change. How do we reuse this? What will this change do before we run it? And what happens to the resources we take out of the template?
In the lab you’ll turn the NSG from Lesson 41 into a module and add a second one, preview a change with what-if, and then deploy the lot as a stack that deletes whatever you remove and blocks manual deletes.
| Time | You need | Cost | By the end you can |
|---|---|---|---|
| About 50 minutes | The files from Lesson 41 in C:\azure-lab\bicep, the CLI, VS Code | No cost: an NSG and a route table | Write and call Bicep modules, read what-if output, and manage resources with deployment stacks |
What it is, in one line
A Bicep module is a .bicep file you call from another Bicep file, passing parameters in and getting outputs back.
In Simple Words
Lego sets and the building plan
A Lego house is built from ready-made parts like a door set, a window set and a roof set. You don’t design a new door each time; you pick up the door set and say “blue, this size”. Those sets are your modules, and the house plan that lists them is main.bicep.
Before changing the house, you hold the new plan up next to the model to see what would move, and that’s what-if.
A deployment stack works like a glass case over the model: nobody can pull a piece off by hand, and when you take a part out of the plan, it gets removed from the model for you.
Engineer's View
Modules, what-if and deployment stacks
- Modules:
module nsg 'modules/nsg.bicep' = { name: ..., params: {...} }. Each module becomes a nested deployment with its own name; outputs come back asnsg.outputs.nsgId. Conditions (if (...)) and loops (for) work on modules. - Sharing: local paths work for a single repo. For many teams you’d use a private Bicep registry (an Azure Container Registry) or template specs, and Microsoft also publishes Azure Verified Modules.
- What-if:
az deployment group what-ifcompares the template with what already exists and shows you Create (+), Delete (-), Modify (~), NoChange (=) and Ignore (*), without changing anything. - Deployment stacks: a resource (
Microsoft.Resources/deploymentStacks) that remembers what it deployed.--action-on-unmanagedecides what happens to resources that get dropped from the template, which can be detach, delete resources, or delete everything including resource groups.--deny-settings-modecan block deletes or writes made outside the stack. - Complete mode vs stacks: complete mode deletes anything in the group that isn’t in the template, even resources it never created, whereas a stack only touches what it manages.
How it works, step by step
Here’s what happens when you update a stack after taking a module out:
- Bicep compiles main.bicep and skips the rt module, because deployRouteTable is false.
- The stack deploys the template, and the NSG stays as it is.
- The stack then compares its list of managed resources with the new deployment and sees that rt-saat-dev isn’t in it any more.
- Since action-on-unmanage is set to deleteResources, the stack deletes rt-saat-dev.
- Finally the deny settings get refreshed on the resources it still manages.
Without a stack, removing a module from a template leaves the old resource sitting there, forgotten and still billing, and that’s how most “orphaned” resources come about.
Always run what-if before you update a stack in production, because it’s the cheapest review you’ll ever do.
Hands-on lab: Bicep modules in a deployment stack
Before you run any command, double-check it
Read every command twice before you press Enter. Check the target: the system or account, the IDs, the names and the sizes. These commands are for learning and were tested in our lab, not on your system. At work, run the read-only list commands first, follow your change process, make sure a backup exists, and ask a second person to check anything that changes or deletes data. You run them at your own risk.
Make a folder for this lesson and copy the NSG file from Lesson 41 into it as a module:
New-Item -ItemType Directory -Path C:\azure-lab\bicep42\modules -Force | Out-Null
Set-Location C:\azure-lab\bicep42
(Get-Content C:\azure-lab\bicep\nsg.bicep) -replace "lesson: '41'", "lesson: '42'" | Set-Content modules\nsg.bicep
az group create --name rg-saat-l42 --location centralindia --tags course=saatvedha-azure lesson=42 -o none1Write a second module
Save the route table module:
$r = @'
@description('Name of the route table')
param rtName string
@description('Azure region for the route table')
param location string = resourceGroup().location
resource rt 'Microsoft.Network/routeTables@2024-05-01' = {
name: rtName
location: location
tags: {
course: 'saatvedha-azure'
lesson: '42'
}
properties: {
disableBgpRoutePropagation: false
routes: [
{
name: 'drop-onprem-range'
properties: {
addressPrefix: '10.80.0.0/16'
nextHopType: 'None'
}
}
]
}
}
output rtId string = rt.id
'@
Set-Content -Path modules\rt.bicep -Value $rThis route sends 10.80.0.0/16 (the future “on-premises” range from the course plan) to None, which drops the traffic. That’s harmless here, since the route table isn’t attached to any subnet.
2Write main.bicep to call both modules
Save it along with a parameters file, then build:
$m = @'
@description('Short environment name used in resource names')
@allowed([
'dev'
'prod'
])
param env string = 'dev'
@minValue(100)
@maxValue(4096)
param httpsPriority int = 110
@description('Deploy the route table module')
param deployRouteTable bool = true
module nsg 'modules/nsg.bicep' = {
name: 'nsg-${env}'
params: {
nsgName: 'nsg-saat-${env}'
httpsPriority: httpsPriority
}
}
module rt 'modules/rt.bicep' = if (deployRouteTable) {
name: 'rt-${env}'
params: {
rtName: 'rt-saat-${env}'
}
}
output nsgId string = nsg.outputs.nsgId
output rtId string = deployRouteTable ? rt!.outputs.rtId : 'none'
'@
Set-Content -Path main.bicep -Value $m
Set-Content -Path dev.bicepparam -Value "using 'main.bicep'`n`nparam env = 'dev'`nparam httpsPriority = 110"
az bicep build --file main.bicep
(Get-Content main.bicep).CountYou should see this (no errors or warnings):
313Deploy it as a deployment stack
Run this:
az stack group create --resource-group rg-saat-l42 --name stack-saat-l42 --template-file main.bicep --parameters dev.bicepparam --action-on-unmanage deleteResources --deny-settings-mode denyDelete --yes -o none
az stack group show --resource-group rg-saat-l42 --name stack-saat-l42 --query "{state:provisioningState, onUnmanage:actionOnUnmanage.resources, deny:denySettings.mode, managed:length(resources)}" -o tableYou should see something like this:
State OnUnmanage Deny Managed
--------- ------------ ---------- ---------
succeeded delete denyDelete 24Preview a change with what-if
In the parameters file, change the priority to 120 and preview it without deploying:
Set-Content -Path dev.bicepparam -Value "using 'main.bicep'`n`nparam env = 'dev'`nparam httpsPriority = 120"
az deployment group what-if --resource-group rg-saat-l42 --template-file main.bicep --parameters dev.bicepparamYou should see something like this at the end:
~ Microsoft.Network/networkSecurityGroups/nsg-saat-dev [2024-05-01]
~ properties.securityRules: [
~ 0:
~ properties.priority: 110 => 120
]
= Microsoft.Network/routeTables/rt-saat-dev [2024-05-01]
Resource changes: 1 to modify, 1 no change.Only one property on one resource changes, and nothing gets created or deleted. That’s the kind of review you want before any production deployment, and if what-if ever shows a Delete you weren’t expecting, stop there.
5Remove a module and let the stack clean up
Switch the route table off and update the stack:
Set-Content -Path dev.bicepparam -Value "using 'main.bicep'`n`nparam env = 'dev'`nparam httpsPriority = 120`nparam deployRouteTable = false"
az stack group create --resource-group rg-saat-l42 --name stack-saat-l42 --template-file main.bicep --parameters dev.bicepparam --action-on-unmanage deleteResources --deny-settings-mode denyDelete --yes -o none
az resource list --resource-group rg-saat-l42 --query "[].{name:name, type:type}" -o tableYou should see this:
Name Type
------------ ---------------------------------------
nsg-saat-dev Microsoft.Network/networkSecurityGroupsThe route table has gone. The stack noticed it wasn’t managing it any more and deleted it, because you picked deleteResources, whereas with a normal deployment it would still be sitting there.

Take a look at the files you have now: a main.bicep of 31 lines and two Bicep modules that any other template can call. When a second team needs the same NSG standard, they call modules/nsg.bicep with their own name and priority instead of writing their own.
Once lots of teams share Bicep modules, local paths stop working well. Publish the modules to a private Bicep registry with version numbers, so one team can stay on version 1.2 while you test 1.3. That habit alone saves you from most “it worked yesterday” template problems.

✅ Checkpoint: main.bicep calls two modules, what-if showed one change, and the stack deleted the route table when you removed it.
Break It, Then Fix It
You’ll probably hit both of these in your first week with modules and stacks.
1Break it: the module that can’t be found
Someone renames the folder in the module path by mistake:
(Get-Content main.bicep) -replace "modules/rt.bicep", "module/rt.bicep" | Set-Content main-typo.bicep
az bicep build --file main-typo.bicepYou’ll get errors like these:
main-typo.bicep(23,11) : Error BCP091: An error occurred reading file. Could not find a part of the path 'C:\azure-lab\bicep42\module\rt.bicep'.
main-typo.bicep(31,41) : Error BCP062: The referenced declaration with name "rt" is not valid.The first error is the real one, because the path is wrong, and the second only follows from it, since the output refers to a module that couldn’t load. Always fix the first error in the list first, and many of the later ones go away by themselves.
To fix it, correct the path (module paths are relative to the file that calls them) and delete the broken copy:
Remove-Item main-typo.bicep
az bicep build --file main.bicepIf nothing prints, it builds again.
2Break it: “just delete it in the portal”
Someone tries removing the NSG by hand:
az network nsg delete --resource-group rg-saat-l42 --name nsg-saat-devYou’ll get an error like this:
(DenyAssignmentAuthorizationFailed) The client 'you@example.com' with object id '...' has permission to perform action 'Microsoft.Network/networkSecurityGroups/delete' on scope '.../nsg-saat-dev'; however, the access is denied because of the deny assignment with name '...' and Id '...' at scope '.../resourceGroups/rg-saat-l42'.The stack’s denyDelete setting created a deny assignment (Lesson 8), so even an Owner can’t delete managed resources outside the stack. That’s deliberate, because changes are meant to go through the template and its review rather than the portal.
To fix it, make your changes through the stack. If you want to remove everything, delete the stack itself:
az stack group delete --resource-group rg-saat-l42 --name stack-saat-l42 --action-on-unmanage deleteAll --yes
az group delete --name rg-saat-l42 --yes
C:\azure-lab\Find-LabResources.ps1 -Lesson 42You should see this:
Nothing tagged course=saatvedha-azure is left.
✅ Checkpoint: You fixed a broken module path and saw a stack block a manual delete. The stack and its resources are gone; the files stay in C:\azure-lab\bicep42.
This happened at work
The route table that outlived its app
A bank’s platform team retired an old integration app by taking its module out of their main Bicep file and redeploying. The pipeline went green and the app’s VMs stopped working, which was the plan.
Six months later a network engineer came across a route table still attached to a shared subnet, sending a range of addresses to a firewall that didn’t exist any more. Normal deployments only add and update, so removing the module had left its resources behind. When a new app reused that address range, its team lost two days chasing a routing problem before anyone found it.
What they changed: every environment is now a deployment stack with deleteResources and denyDelete. Each pull request includes the what-if output, and any Delete in it needs a second approver. They also run a monthly Resource Graph report that lists resources no stack manages.
Common mistakes and troubleshooting
| Mistake | What you see | What to do |
|---|---|---|
| Wrong module path | BCP091, then BCP062 | Fix the path relative to the calling file. |
| Skipping what-if | Surprise deletes or changes | Run what-if and read every Delete. |
| Removing a module without a stack | Orphaned resources keep billing | Use a stack with deleteResources. |
| Complete mode on a shared group | Other teams’ resources deleted | Use stacks; they touch only what they manage. |
| Manual changes to stack resources | DenyAssignmentAuthorizationFailed | Change the template and update the stack. |
| Copy-pasting modules between repos | Versions drift apart | Publish modules to a registry or use template specs. |
Interview questions
Click a question to open it. Each one is worded the way an interviewer would ask it, and underneath you’ll find why they ask it and one way you could answer in your own words.
Fresher level
1. What is a Bicep module?
Why they ask this: To check the basic concept.
How you might answer: It’s a Bicep file that another Bicep file calls, with parameters going in and outputs coming back. It lets you reuse a building block like an NSG or a VNet across environments and teams.
2. What does what-if do?
Why they ask this: A safety habit check.
How you might answer: It compares a template with the resources that are already there and shows you what would be created, changed, deleted or left alone, without deploying anything.
3. What is a deployment stack?
Why they ask this: Newer feature knowledge.
How you might answer: It’s a resource that deploys a template and keeps track of the resources it manages. It can delete resources you remove from the template, and its deny settings can block manual deletes or changes.
2–5 years experience
4. How do you decide what goes into a module?
Why they ask this: They want design judgement.
How you might answer: Something with a clear purpose and clear parameters that gets reused at least twice, like a standard NSG, VNet or storage account with our defaults baked in. If you make too many tiny modules the templates get hard to follow, and with too few they’re hard to reuse.
5. What-if shows a Delete you didn’t expect. What do you do?
Why they ask this: They want caution.
How you might answer: I’d stop and work out why. It might be a renamed resource, a changed condition or a different parameter file, and in Bicep a rename often means delete and create. I only carry on once every change in the output is one we meant.
6. How do stacks compare with complete deployment mode?
Why they ask this: They want trade-offs.
How you might answer: Complete mode deletes everything in the resource group that isn’t in the template, including things other people deployed. A stack only deletes resources it manages, it can span scopes and it adds deny settings, so it’s the safer choice.
Senior level
7. How would you share Bicep modules across 20 teams?
Why they ask this: They want platform engineering.
How you might answer: I’d set up a private Bicep registry or template specs with versioned modules, building on Azure Verified Modules where we can, with tests and what-if in CI. Teams pin the versions they use, and the platform team publishes changes with release notes.
8. How do you handle emergency changes when deny settings block the portal?
Why they ask this: They want operational realism.
How you might answer: I’d exclude a break-glass group in the stack’s deny settings and only allow it through PIM. After the emergency, the same change goes into the template straight away so the next deployment doesn’t undo it.
9. How do you detect drift between templates and Azure?
Why they ask this: They’re checking ongoing governance.
How you might answer: Scheduled what-if runs in the pipeline that alert when something has changed, deny settings so drift can’t happen in the first place, Azure Policy for configuration rules, and Resource Graph reports to find unmanaged resources.
Quick quiz
Q1. How do you call a module in Bicep?
- import
- module name ‘path’ = {…}
- include
- using
Show answer
B — module declares a call to another Bicep file.
Q2. Which command previews changes without deploying?
- az bicep build
- az deployment group what-if
- az stack group show
- az group export
Show answer
B — what-if shows changes only.
Q3. A module is removed; the stack uses deleteResources. Result?
- Resource kept
- Resource deleted
- Error
- Resource moved
Show answer
B — Unmanaged resources are deleted.
Q4. BCP091 means:
- A cycle
- The file can’t be read
- A bad value
- A deny assignment
Show answer
B — Usually a wrong path.
Q5. denyDelete on a stack causes manual deletes to fail with:
- BlobArchived
- DenyAssignmentAuthorizationFailed
- QuotaExceeded
- BCP080
Show answer
B — The stack creates a deny assignment.
Quick recap
You can now build environments from modules, preview each change before it lands, and keep your deployments tidy.
- Modules are reusable Bicep files with parameters and outputs.
- what-if shows creates, changes and deletes before you deploy.
- Stacks delete resources you remove from the template, if you tell them to.
- Deny settings stop manual deletes outside the stack.
- Fix the first Bicep error first.
Next lesson
Lesson 43: Azure Automation runbooks → You run PowerShell runbooks on a schedule with a managed identity to stop lab VMs every evening.
Further reading: Bicep modules
Want to go deeper into Bicep modules? See Microsoft’s Bicep modules and Deployment stacks. You can also see the full plan for this course on the Azure Cloud Administration course page.
