We earn commissions when you shop through affiliate links on this site, at no extra cost to you. Our guides and technical recommendations are written independently of these relationships: a commission never decides what we recommend, how we diagnose a problem or what we publish, and the content does not depend on it. Affiliate disclosure

Azure · Cost · Intermediate · 15 min

Stop Azure costs automatically at a budget limit

Azure budgets only send e-mail. Build a tested auto-stop: budget, action group, webhook and a runbook that deletes test resource groups and stops VMs.

An Azure budget never stops anything by itself, and a pay-as-you-go subscription has no spending limit. This guide builds a stop for test subscriptions with the Azure CLI: a budget that calls an action group, a webhook, and a runbook that deletes lab resource groups and deallocates running VMs. The whole chain was tested with a budget-type test notification.

An Azure budget only sends e-mail. Microsoft says it plainly: when a threshold is exceeded, "resources aren't affected, and your consumption isn't stopped". A pay-as-you-go subscription has no spending limit at all. If you run test machines and want a hard stop, you have to build it: a budget that calls an action group, which calls a webhook, which starts a small runbook that deletes your test resource groups and deallocates running VMs.

This guide builds that chain with the Azure CLI and tests it end to end without waiting for a real overspend. It was run on 12 November 2026 with Azure CLI 2.92.0 on a pay-as-you-go subscription. We used other resource names than the ones below; the commands are the same.

From a budget threshold to a stopped lab1. Cost Management Budget (monthly limit on the subscription) [evaluated every 24 h] Then 2. Azure Monitor Action group (e-mail and a webhook receiver) Then 3. Automation Webhook (a secret URL) [keep it private] Then 4. Automation Runbook (managed identity, Contributor) [deletes lab-* groups, deallocates VMs].CostManagementBudgetmonthly limit onthe subscriptionevaluated every24 hat 100%Azure MonitorAction groupe-mail and awebhook receivercallsAutomationWebhooka secret URLkeep it privatestartsAutomationRunbookmanagedidentity,Contributordeletes lab-*groups,deallocates VMs
Azure evaluates the budget once a day on cost data that is 8 to 24 hours old, so the stop can come up to about two days after the limit is crossed. Every step after the budget can be tested at once with a test notification.

0. Rules of engagement

  • It is late by design. Cost data reaches Azure in 8 to 24 hours and budgets are evaluated every 24 hours (Microsoft's figures), so the stop can come up to about two days after you cross the limit. Set the limit well below what would hurt.
  • Decide what the stop is allowed to destroy. This runbook deletes every resource group whose name starts with lab-, and deallocates any running VM. Keep everything you care about out of lab-* groups, and put the guard itself in a group with another name, or it deletes itself.
  • The runbook's identity can change the whole subscription. It needs Contributor on the subscription, because the groups it deletes do not exist yet when you assign the role. Only you should be able to edit the Automation account.
  • Test it before you rely on it, with a test notification (section 6), not by overspending.

1. Register the providers

A new subscription may not be registered for Automation and Azure Monitor yet. The first create then fails with MissingSubscriptionRegistration:

# One-time: allow Automation accounts and action groups in this subscription
az provider register -n Microsoft.Automation --wait
az provider register -n Microsoft.Insights --wait
az provider show -n Microsoft.Automation --query registrationState -o tsv
# Real output
Registered

2. The Automation account and its identity

# A resource group for the guard (NOT lab-*), and an Automation account with a system-assigned identity
SUB=$(az account show --query id -o tsv); L=northeurope
az group create -n rg-budget-guard -l $L --query properties.provisioningState -o tsv
B="https://management.azure.com/subscriptions/$SUB/resourceGroups/rg-budget-guard/providers/Microsoft.Automation/automationAccounts/aa-budget-guard"
az rest --method put --url "$B?api-version=2023-11-01" --body "{\"location\":\"$L\",\"identity\":{\"type\":\"SystemAssigned\"},\"properties\":{\"sku\":{\"name\":\"Basic\"}}}" --query properties.state -o tsv
# Real output
Succeeded
Ok

az rest calls the Azure Resource Manager API directly, so you do not need the automation CLI extension. If a region answers RequestDisallowedByAzure ... The selected region is currently not accepting new customers (ours did for West Europe), pick another region for the Automation account; the resource group can stay where it is.

3. The runbook

# The runbook: PowerShell 7.2, delete lab-* resource groups, deallocate running VMs
az rest --method put --url "$B/runbooks/stop-lab?api-version=2023-11-01" --body "{\"location\":\"$L\",\"properties\":{\"runbookType\":\"PowerShell72\",\"logProgress\":false,\"logVerbose\":false}}" --query properties.runbookType -o tsv
cat > stop-lab.ps1 <<'PS'
Connect-AzAccount -Identity | Out-Null
foreach ($g in Get-AzResourceGroup | Where-Object { $_.ResourceGroupName -like 'lab-*' }) {
  Write-Output "Deleting resource group $($g.ResourceGroupName)"
  Remove-AzResourceGroup -Name $g.ResourceGroupName -Force | Out-Null
}
foreach ($vm in Get-AzVM -Status | Where-Object { $_.PowerState -eq 'VM running' }) {
  Write-Output "Deallocating VM $($vm.Name)"
  Stop-AzVM -ResourceGroupName $vm.ResourceGroupName -Name $vm.Name -Force -NoWait | Out-Null
}
Write-Output "Cut-off done."
PS
TOKEN=$(az account get-access-token --query accessToken -o tsv)
curl -s -o /dev/null -w "upload: %{http_code}\n" -X PUT -H "Authorization: Bearer $TOKEN" -H "Content-Type: text/powershell" --data-binary @stop-lab.ps1 "$B/runbooks/stop-lab/draft/content?api-version=2023-11-01"
curl -s -o /dev/null -w "publish: %{http_code}\n" -X POST -H "Authorization: Bearer $TOKEN" -H "Content-Length: 0" "$B/runbooks/stop-lab/publish?api-version=2023-11-01"
# Real output
PowerShell72
upload: 202
publish: 202

The Az PowerShell modules are already in the PowerShell 7.2 runtime; nothing to import. If you would rather only stop spending and keep your data, drop the first loop and keep the deallocation: a deallocated VM stops compute charges, but its disks and public IP still cost money.

4. Give the runbook a role

# The identity's object ID, then Contributor on the subscription
PID=$(az rest --method get --url "$B?api-version=2023-11-01" --query identity.principalId -o tsv)
az role assignment create --assignee-object-id "$PID" --assignee-principal-type ServicePrincipal --role Contributor --scope "/subscriptions/$SUB"

We assigned this one in the portal instead (Subscription, Access control (IAM), Add role assignment, Contributor, Managed identity, the Automation account), then checked it from the CLI:

# Which roles the runbook identity has on the subscription
az role assignment list --assignee "$PID" --scope "/subscriptions/$SUB" --query '[].roleDefinitionName' -o tsv
# Real output
Contributor

5. Webhook, action group and budget

# A webhook for the runbook. Its URL is a secret: anyone with it can start the runbook. Keep it in a file only you can read.
URI=$(az rest --method post --url "$B/webhooks/generateUri?api-version=2015-10-31" -o tsv)
az rest --method put --url "$B/webhooks/budget-stop?api-version=2015-10-31" --body "{\"name\":\"budget-stop\",\"properties\":{\"isEnabled\":true,\"uri\":\"$URI\",\"expiryTime\":\"2027-11-01T00:00:00Z\",\"runbook\":{\"name\":\"stop-lab\"}}}" --query properties.isEnabled -o tsv
umask 077; echo "$URI" > ~/.budget-stop-webhook
# An action group that calls the webhook and e-mails you
MAIL=you@example.com
AG=$(az monitor action-group create -g rg-budget-guard -n ag-budget-stop --short-name budgetstop --action webhook runbook "$URI" usecommonalertschema --action email owner "$MAIL" --query id -o tsv)
# A monthly budget of 10 in your billing currency (EUR on our subscription) on the subscription that fires the action group at 100%
cat > budget.json <<J
{"properties":{"category":"Cost","amount":10,"timeGrain":"Monthly","timePeriod":{"startDate":"2026-11-01T00:00:00Z","endDate":"2027-11-01T00:00:00Z"},
 "notifications":{"stop100":{"enabled":true,"operator":"GreaterThanOrEqualTo","threshold":100,"contactEmails":["$MAIL"],"contactGroups":["$AG"]}}}}
J
az rest --method put --url "https://management.azure.com/subscriptions/$SUB/providers/Microsoft.Consumption/budgets/budget-10-stop?api-version=2023-05-01" --body @budget.json --query '{name:name, amount:properties.amount, groups:length(properties.notifications.stop100.contactGroups)}' -o tsv
# Real output (names differ in our run)
true
budget-10-stop	10.0	1

The budget start date must be the first day of a month. The webhook expires on the date you set; put a reminder in your calendar a week before, because an expired webhook fails silently and the budget then only sends e-mail. The budget shows up in the portal under Cost Management, Budgets, with the scope set to the subscription; it is not listed among the alert rules in Azure Monitor.

6. Test the whole chain

Do not wait for a real overspend. Create an empty lab- group, send the action group a test notification of the budget type, and watch the group disappear:

# A throwaway group, then a test notification through the same webhook
az group create -n lab-guardtest -l northeurope --query name -o tsv
az monitor action-group test-notifications create --action-group ag-budget-stop --resource-group rg-budget-guard --alert-type budget --add-action webhook runbook "$(cat ~/.budget-stop-webhook)" --query state -o tsv
# Real output
lab-guardtest
Complete

Then read the newest runbook job (it took about a minute to start and finish) and list the groups:

# The last job's output, then the lab-* groups that are left
JOB=$(az rest --method get --url "$B/jobs?api-version=2023-11-01" --query "value | sort_by(@, &properties.creationTime) | [-1].name" -o tsv)
az rest --method get --url "$B/jobs/$JOB/streams?api-version=2023-11-01" --query "value[].properties.summary" -o tsv
az group list --query "[?starts_with(name,'lab-')].name" -o tsv
# Real output: the runbook deleted the test group, and no lab-* group is left
Deleting resource group lab-guardtest
Cut-off done.

We also started the webhook directly with curl -X POST -H "Content-Length: 0" "$(cat ~/.budget-stop-webhook)" (HTTP 202) and got the same result. What we did not do is overspend for real, so the budget-to-action-group step is Microsoft's documented behavior, not something we watched happen.

Common mistakes

  • Putting the guard in a lab- group. The runbook deletes its own Automation account on the first run, and nothing protects you after that.
  • Expecting the budget to stop things on its own. Without the action group and runbook it only sends e-mail, and even the e-mail comes after the daily evaluation.
  • A budget scoped to a resource group when the costs are elsewhere. Scope the budget to the subscription if any resource outside one group can cost money.
  • Forgetting the role. Without a role on the subscription the runbook's identity cannot see or delete the groups. After every test, check the job output for the "Deleting" lines, not just the job status.
  • Pasting the webhook URL into a ticket, a chat or a repository. It is a bearer secret: anyone who has it can run the stop.

7. Verify and maintain

  • The budget, its threshold and the action group: az rest --method get --url "https://management.azure.com/subscriptions/$SUB/providers/Microsoft.Consumption/budgets?api-version=2023-05-01" --query "value[].{name:name, amount:properties.amount, spent:properties.currentSpend.amount}" -o tsv.
  • Re-run the test in section 6 after any change to the runbook, the role or the webhook.
  • Renew the webhook before it expires (create a new one, update the action group, delete the old one).

8. Rollback

Delete the budget, then the guard's resource group (Automation account, runbook, webhook and action group go with it), then the role assignment:

# Remove the whole guard
az rest --method delete --url "https://management.azure.com/subscriptions/$SUB/providers/Microsoft.Consumption/budgets/budget-10-stop?api-version=2023-05-01"
az role assignment delete --assignee "$PID" --role Contributor --scope "/subscriptions/$SUB"
az group delete --name rg-budget-guard --yes
rm -f ~/.budget-stop-webhook

What this does not stop

  • Anything outside lab-* groups except running VMs. Storage accounts, databases and public IPs in other groups keep billing. Put every test resource in a lab- group from the start.
  • Charges in the 1 to 2 days of delay. Size the limit for that.
  • Reservations, marketplace purchases and support plans, which a runbook cannot undo.

References

Official reference

learn.microsoft.com ↗

Technical steps are original explanations; consult the upstream documentation for version-specific details.

Behavior differs by distribution and tool version. Commands are examples for authorized systems; review output for secrets before sharing.

Found this useful?

Follow us on YouTube for video explainers, and find us on Facebook to keep up with what is new.