Azure Automation runbooks
-
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
An Azure Automation runbook is a PowerShell or Python script that Azure runs for you on a schedule, from a webhook or when an alert fires, so you don’t need a server of your own. Stopping dev VMs every evening, rotating a secret and cleaning up old snapshots are all typical runbook jobs.
For a lot of teams, runbooks are the first place they automate their own work. They’re also where old scripts from the internet break, because most of them use the “Run As account”, which was retired in 2023 in favour of managed identities.
In the lab you’ll build an Automation account with a managed identity and write a runbook that stops your lab VMs, schedule it for 19:30 IST, and then fix a permissions error and a legacy Run As script.
| Time | You need | Cost | By the end you can |
|---|---|---|---|
| About 40 minutes | The CLI and the portal, web01 and win01 | No charge within the first 500 job minutes a month; this lab uses a few minutes | Create runbooks that authenticate with a managed identity, schedule them, and troubleshoot failed jobs |
What it is, in one line
A runbook is a script Azure Automation runs for you, on a schedule or trigger, using the Automation account’s identity.
In Simple Words
The school caretaker’s evening checklist
Every evening at 7:30 the school caretaker goes round with a checklist, switching off lights in empty rooms, shutting windows and locking doors. Nobody has to remind him because it’s on his schedule, and that’s a runbook with a schedule.
He carries his own set of keys that the school issued to him, rather than borrowing the head teacher’s, and those keys are the managed identity.
If the school changes a lock and forgets to give him the new key, he still does his round but can’t get in to switch off the lights in that room, which is the first thing you’ll break in this lesson.
Engineer's View
How Azure Automation runs your scripts
- Automation account: this holds your runbooks, schedules, variables, credentials and modules, along with the account’s managed identity.
- Runbook types: PowerShell (5.1 and 7.x runtimes, including 7.4), Python 3 and graphical. You choose the runtime when you create the runbook.
- Authentication:
Connect-AzAccount -Identitywith the account’s system-assigned identity or a user-assigned managed identity, plus Azure RBAC on whatever it touches. Run As accounts, which used certificates, were retired on 30 September 2023. - Triggers: a schedule (with a time zone), a webhook, an Azure Monitor alert through an action group, or a manual start.
- Where it runs: by default on sandboxes that Azure manages, or on a Hybrid Runbook Worker (a VM or Arc server) when it needs to reach private networks.
- Limits and cost: sandbox jobs have a fair-share limit of about 3 hours before they get unloaded, and the first 500 job minutes each month cost nothing.
- Output: every job keeps its output, errors and warnings as streams, which you can read in the portal or through the API.
How it works, step by step
When the schedule fires at 19:30 IST, this is what happens:
- The schedule starts a new Stop-LabVMs job with its parameters.
- Azure loads a sandbox with the runtime and modules the runbook needs.
- The script signs in with the account’s managed identity.
- It lists the VMs in rg-saat-vms and deallocates the ones that are running, using the identity’s RBAC rights.
- The output and any errors are saved with the job, which ends as Completed, Failed or Suspended.
Most failures happen at step 3 and step 4, either because there’s no identity or because the identity has no rights where the script tries to act.
Give the identity the smallest role at the smallest scope it needs, so Virtual Machine Contributor on one resource group rather than Contributor on the whole subscription.
Hands-on lab: an Azure Automation runbook that stops lab VMs
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.
Load your subscription ID:
$sub = az account show --query id -o tsv1Create the Automation account with a managed identity
Run this:
az automation account create --resource-group rg-saat-core --name aa-saat --location centralindia -o none
$aaId = az automation account show --resource-group rg-saat-core --name aa-saat --query id -o tsv
az resource update --ids $aaId --set identity.type=SystemAssigned -o none
$aaPid = az resource show --ids $aaId --query identity.principalId -o tsv
$aaPidYou should get back a GUID, which is the principal ID of the account’s identity.
2Create the runbook
In the portal, open aa-saat, go to Process Automation, then Runbooks, and choose Create a runbook. Call it Stop-LabVMs, with type PowerShell and runtime version 7.4. Paste in this script, Save it, then Publish.

param([string]$ResourceGroup = 'rg-saat-vms')
Connect-AzAccount -Identity | Out-Null
$vms = Get-AzVM -ResourceGroupName $ResourceGroup -Status
foreach ($vm in $vms) {
if ($vm.PowerState -eq 'VM running') {
Write-Output "Stopping $($vm.Name)"
Stop-AzVM -ResourceGroupName $ResourceGroup -Name $vm.Name -Force -NoWait | Out-Null
}
else {
Write-Output "$($vm.Name) is already $($vm.PowerState)"
}
}3Start it once by hand
Click Start, leave the default parameter as it is, and open the job, which finishes after about a minute. Since your VMs are already deallocated from earlier lessons, you’d probably expect two “already deallocated” lines.
Read on.

Check the job from the CLI as well:
az automation job list --resource-group rg-saat-core --automation-account-name aa-saat --query "[0].{runbook:runbook.name, status:status}" -o tableYou should see something like this:
Runbook Status
------------ --------
Stop-LabVMs FailedIt failed on its very first run. That’s Break It step 1, and it’s worth fixing before you set up the schedule, so go there now and come back to step 4 afterwards.
4Schedule it every evening at 19:30 IST
Once it’s fixed, go to Stop-LabVMs and choose Link to schedule, then Create a new schedule. Name it daily-1930-ist, set it to start tomorrow at 19:30 in the India Standard Time (UTC+05:30) time zone, recurring every 1 day, and save.

Now check when it will run next:
az automation schedule show --resource-group rg-saat-core --automation-account-name aa-saat --name daily-1930-ist --query "{next:nextRun, timeZone:timeZone, frequency:frequency}" -o tableYou should see something like this:
Next TimeZone Frequency
------------------------- ------------- -----------
2026-10-22T19:30:00+05:30 Asia/Calcutta DayThe time zone matters, because a schedule saved in UTC would fire at 01:00 IST, by which point the VMs would have run five and a half extra hours. Azure might show the zone as Asia/Calcutta, which is the same thing as India Standard Time.

✅ Checkpoint: Stop-LabVMs runs with the account’s managed identity, completes, and is scheduled daily at 19:30 IST.
Break It, Then Fix It
Both of these breaks come down to identity: one is missing a role, and the other comes from before managed identities existed.
1Break it: the identity with no rights
Open the failed job from step 3 and read its Errors tab, or ask the CLI for the exception:
$job = az automation job list --resource-group rg-saat-core --automation-account-name aa-saat --query "[0].name" -o tsv
az automation job show --resource-group rg-saat-core --automation-account-name aa-saat --name $job --query exception -o tsvYou’ll see something like this:
The client '3f6a...' with object id '3f6a...' does not have authorization to perform action 'Microsoft.Compute/virtualMachines/read' over scope '/subscriptions/.../resourceGroups/rg-saat-vms' or the scope is invalid. If access was recently granted, please refresh your credentials.The sign-in worked and the identity exists, but it has no role on rg-saat-vms, so even listing the VMs gets refused (AuthorizationFailed, Lesson 7). You’ll see runbooks fail this way whenever someone forgets the role assignment or moves the target resource group.
To fix it, grant the smallest role that will do the job at the resource group level, and then start the runbook again in the portal:
az role assignment create --assignee-object-id $aaPid --assignee-principal-type ServicePrincipal --role "Virtual Machine Contributor" --scope "/subscriptions/$sub/resourceGroups/rg-saat-vms" -o none
az vm start --resource-group rg-saat-vms --name web01Start Stop-LabVMs again, and the Output tab should show something like this:
Stopping web01
win01 is already VM deallocatedAbout a minute later web01 is deallocated. Role changes can take a few minutes to kick in, so if it still fails, wait a bit and run it again.
If you want to see what an Azure Automation runbook is allowed to do, list the roles on its identity with az role assignment list --assignee $aaPid --all --query "[].{role:roleDefinitionName, scope:scope}" -o table. There should be just one line: Virtual Machine Contributor on rg-saat-vms.
Before publishing changes to a runbook, try them in the Test pane of the portal editor. It runs the draft version against real resources, so treat it as production, but you get to see output and errors without replacing the published runbook the schedule uses. Only publish once the test run comes out clean.
2Break it: the Run As script from the internet
Create a second runbook called Get-LabVMs-Old (PowerShell, 7.4) using this script, copied from an old blog post, then publish and start it.
$conn = Get-AutomationConnection -Name 'AzureRunAsConnection'
Connect-AzAccount -ServicePrincipal -Tenant $conn.TenantId -ApplicationId $conn.ApplicationId -CertificateThumbprint $conn.CertificateThumbprint
Get-AzVM -ResourceGroupName 'rg-saat-vms' -Status | Select-Object Name, PowerStateThe job fails with something like this:
Get-AutomationConnection: The connection asset 'AzureRunAsConnection' was not found.
Connect-AzAccount: ... (no valid credentials)Run As accounts were retired in 2023 and you can’t create them any more, yet thousands of published scripts still begin with these lines, and they fail on every new Automation account.
To fix it, swap the first two lines for the managed identity sign-in, then publish and start it again:
Connect-AzAccount -Identity | Out-Null
Get-AzVM -ResourceGroupName 'rg-saat-vms' -Status | Select-Object Name, PowerStateThis time the output should list web01 and win01 along with their power state.
To clean up, keep aa-saat and Stop-LabVMs with its schedule, since from now on they’ll stop your lab VMs every evening, and delete the old runbook:
az automation runbook delete --resource-group rg-saat-core --automation-account-name aa-saat --name Get-LabVMs-Old --yes
✅ Checkpoint: Your runbook signs in with a managed identity, has the right role, and runs every evening. The legacy Run As script is fixed and deleted.
This happened at work
The cleanup runbook that stopped on 1 October 2023
An engineering company had a nightly runbook that deleted VM snapshots older than 30 days, and it had been working quietly for four years. Then in early 2024 someone from finance asked why snapshot costs had tripled.
When the team opened the job history, they found the runbook had failed every night since Run As accounts were retired on 30 September 2023. Its first line looked for AzureRunAsConnection, which didn’t exist any more, and because nobody watched the job history and there was no alert on failed jobs, nobody had noticed.
What they changed: all runbooks moved to managed identities, with roles scoped to one resource group. Failed jobs now send diagnostic logs to Log Analytics and an alert fires on any failed or suspended job. Each runbook owner goes through the job history once a month, and a new runbook needs a test run before its schedule gets linked.
Common mistakes and troubleshooting
| Mistake | What you see | What to do |
|---|---|---|
| No role for the managed identity | AuthorizationFailed in the Error stream | Assign the smallest role at the right scope. |
| Old Run As code | “AzureRunAsConnection” not found | Use Connect-AzAccount -Identity. |
| Schedule saved in UTC | Runbook runs hours off | Set the schedule’s time zone. |
| Contributor on the subscription | Runbook could break anything | Scope roles to one resource group. |
| No alert on failed jobs | Silent failures for months | Send the job logs to Log Analytics and alert on them. |
| Long jobs on sandboxes | Jobs unloaded around 3 hours | Use checkpoints, split jobs, or a Hybrid Worker. |
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 an Azure Automation runbook?
Why they ask this: To check the basic concept.
How you might answer: It’s a PowerShell or Python script kept in an Automation account, and Azure runs it on a schedule, from a webhook or an alert, or on demand, so you don’t have to manage a server for it.
2. How should a runbook authenticate to Azure?
Why they ask this: A current best-practice check.
How you might answer: With the Automation account’s managed identity, signing in with Connect-AzAccount -Identity, and Azure RBAC roles for whatever it needs to touch. Run As accounts were retired in 2023, so they’re not an option any more.
3. What triggers can start a runbook?
Why they ask this: They want the options.
How you might answer: Schedules, webhooks, Azure Monitor alerts through action groups, other runbooks, and manual starts from the portal, the CLI or the API.
2–5 years experience
4. A runbook job failed. How do you find out why?
Why they ask this: A real troubleshooting path.
How you might answer: I’d open the job’s Errors and All Logs streams and read the exception first. Then I’d check the identity’s role assignments and their scope, the module versions in the runtime, and whether the target resources were moved or renamed.
5. When would you use a Hybrid Runbook Worker?
Why they ask this: They want architecture sense.
How you might answer: When the runbook has to reach resources in a private network or on-premises, needs tools installed locally, or runs longer than a sandbox allows. The worker is a VM or an Arc server registered to the Automation account.
6. How do you migrate old Run As runbooks?
Why they ask this: A common real task.
How you might answer: I’d enable a managed identity on the account and give it the roles the Run As principal had, ideally fewer. Then I’d replace the Get-AutomationConnection and service principal sign-in with Connect-AzAccount -Identity, test it, and finally delete the old certificates and app registrations.
Senior level
7. How do you make automation safe at scale?
Why they ask this: They want governance.
How you might answer: Keep runbooks in source control and deploy them through a pipeline, use least-privilege identities per account or purpose, and require approval for anything destructive. Then logs and alerts on failures, and regular reviews of roles and schedules.
8. Automation runbooks, Functions or Logic Apps: how do you choose?
Why they ask this: They want trade-offs.
How you might answer: I’d use runbooks for scheduled admin scripts in PowerShell, Functions for event-driven code that needs low latency and scale, and Logic Apps for workflows that tie lots of services together with little code. In the end it comes down to the trigger, the language and who’s going to maintain it.
9. How would you auto-remediate an alert with a runbook?
Why they ask this: They want end-to-end.
How you might answer: The alert rule calls an action group with an Automation runbook action and passes the alert payload along. The runbook parses that, checks some safety conditions, fixes the problem using a scoped identity, and then logs or notifies the result. I’d always test it with a fake alert first.
Quick quiz
Q1. How should a runbook sign in to Azure today?
- Run As account
- Managed identity
- A user’s password
- A storage key
Show answer
B — Connect-AzAccount -Identity.
Q2. When were Run As accounts retired?
- 2020
- 30 September 2023
- 2026
- Never
Show answer
B — They were retired on 30 September 2023.
Q3. A runbook fails with AuthorizationFailed on virtualMachines/read. Fix?
- Restart the account
- Give the identity a role on the scope
- Use Python
- Change the schedule
Show answer
B — The identity needs RBAC rights.
Q4. How many job minutes a month have no charge?
- 50
- 100
- 500
- Unlimited
Show answer
C — The first 500 minutes each month.
Q5. Why set a time zone on a schedule?
- It’s required for Python
- So it runs at the local time you mean
- To save cost
- To use webhooks
Show answer
B — Otherwise times are in UTC.
Quick recap
You now have automation running in your subscription, and you know why runbooks fail.
- Runbooks run scripts in Azure on schedules, webhooks or alerts.
- Sign in with Connect-AzAccount -Identity, because Run As is retired.
- Give the identity the smallest role at the smallest scope.
- Set the schedule’s time zone.
- Alert on failed jobs, and read the Error stream first.
Next lesson
Lesson 44: Azure cost management: budgets, Advisor, savings → You find what costs money in your subscription and cut it with budgets, Advisor and reservations.
Further reading: Azure Automation runbook
Want to go deeper into Azure Automation runbook? See Microsoft’s Azure Automation overview and Use a system-assigned managed identity for an Automation account. You can also see the full plan for this course on the Azure Cloud Administration course page.
