Symptom
A scheduled runbook that used to work now shows Failed, Suspended, Stopped or Failed, waiting for resources. Or the job never leaves Queued on a Hybrid Worker group. The task it automates (start/stop VMs, clean-up, reporting) has silently not happened.
The job status alone tells you little. The cause is almost always in the job's Error or Exception stream, so start there.
Step 1: read the failed job's streams
$rg = "rg-ops"
$aa = "aa-ops-prod"
# Latest failed or suspended jobs for one runbook
Get-AzAutomationJob -ResourceGroupName $rg -AutomationAccountName $aa `
-RunbookName "Stop-NonProdVMs" |
Where-Object Status -in "Failed","Suspended","Stopped" |
Sort-Object CreationTime -Descending | Select-Object -First 5 JobId, Status, CreationTime, HybridWorker
# All streams for one job (Output, Warning, Error, Verbose if enabled)
$jobId = "<job-guid>"
Get-AzAutomationJobOutput -ResourceGroupName $rg -AutomationAccountName $aa -Id $jobId -Stream Any |
ForEach-Object {
Get-AzAutomationJobOutputRecord -ResourceGroupName $rg -AutomationAccountName $aa `
-JobId $jobId -Id $_.StreamRecordId
} | Select-Object Time, Type, @{n='Text';e={$_.Value.Values -join ' '}}
If you send Automation logs to Log Analytics (diagnostic setting categories JobLogs and JobStreams), you can see failures across the whole account:
AzureDiagnostics
| where ResourceProvider == "MICROSOFT.AUTOMATION" and Category == "JobLogs"
| where ResultType in ("Failed", "Suspended", "Stopped")
| summarize Failures = count(), LastFailure = max(TimeGenerated) by RunbookName_s, ResultType
| order by Failures desc
To read the error text, join to the streams:
AzureDiagnostics
| where ResourceProvider == "MICROSOFT.AUTOMATION" and Category == "JobStreams"
| where StreamType_s == "Error"
| project TimeGenerated, RunbookName_s, JobId_g, ResultDescription
| order by TimeGenerated desc
Column names in AzureDiagnostics come from the logged fields, so check your workspace's schema if a column doesn't resolve.
Step 2: match the error to the cause
| Error or status | Likely cause | Fix |
|---|---|---|
ManagedIdentityCredential authentication failed / No managed identity endpoint found | Identity not enabled on the Automation account, or the wrong client ID passed for a user-assigned identity | Enable the identity; use Connect-AzAccount -Identity -AccountId <clientId> for user-assigned |
AuthorizationFailed ... does not have authorization to perform action | Identity has no role at the target scope (common after a subscription move or new resource group) | Assign the narrowest role that covers the action |
The term 'Get-AzVM' is not recognized | Module not imported for the runtime version the runbook uses | Import the module into that runtime (5.1 vs 7.x are separate) |
Run As account / AzureRunAsConnection not found | Runbook still uses the retired Run As account | Rewrite the sign-in to use managed identity |
| Failed, waiting for resources | Job hit the three-hour fair share limit three times | Split the work, checkpoint, or move to a Hybrid Worker |
| Job Suspended with an exception | Terminating error in a PowerShell Workflow or graphical runbook | Fix the error, then resume or restart the job |
| Stuck in Queued on a Hybrid Worker group | No healthy worker in the group, or the worker can't reach Automation | See Step 5 |
| Fails at the same point, no clear error, large data sets | Sandbox memory, socket or output limits hit | Reduce output, page results, or use a Hybrid Worker |
Step 3: fix managed identity sign-in and permissions
Run As accounts were retired in September 2023. Every runbook should sign in with the Automation account's managed identity. The minimal pattern:
# Inside the runbook
Disable-AzContextAutosave -Scope Process | Out-Null
# System-assigned identity
$ctx = (Connect-AzAccount -Identity).Context
# User-assigned identity: pass its client ID instead
# $ctx = (Connect-AzAccount -Identity -AccountId "<client-id>").Context
Set-AzContext -SubscriptionId "<subscription-id>" -DefaultProfile $ctx | Out-Null
Disable-AzContextAutosave -Scope Process stops one job from picking up a context saved by another job in the same sandbox. Always set the subscription explicitly. A runbook that relies on the identity's "default" subscription breaks when the identity gets access to a second one.
Check the identity and its role assignments from your workstation:
# Principal ID of the system-assigned identity
PRINCIPAL_ID=$(az resource show -g rg-ops -n aa-ops-prod \
--resource-type Microsoft.Automation/automationAccounts \
--query identity.principalId -o tsv)
az role assignment list --assignee "$PRINCIPAL_ID" --all \
--query "[].{role:roleDefinitionName, scope:scope}" -o table
# Grant only what the runbook needs, at the narrowest scope
az role assignment create --assignee-object-id "$PRINCIPAL_ID" \
--assignee-principal-type ServicePrincipal \
--role "Virtual Machine Contributor" \
--scope "/subscriptions/<sub-id>/resourceGroups/rg-app-nonprod"
Tip
Role assignments can take several minutes to take effect. If a job fails with
AuthorizationFailedstraight after you assign a role, wait and rerun before you change anything else.
Step 4: fix module and runtime problems
Each PowerShell runtime version (5.1, 7.x) has its own module set. A runbook set to 7.x won't see a module imported only for 5.1, and the reverse is also true. In the portal, check the runbook's Runtime version (or its Runtime environment if your account uses the runtime environment experience), then check that environment's packages.
Things to look for:
- Version clashes. Az modules depend on a matching
Az.Accounts. If you import a newerAz.Computebut leave an oldAz.Accounts, sign-in or cmdlets fail with assembly-load errors. UpdateAz.Accountsfirst, then the rest. - Modules imported but still "Importing" or "Failed". Check the module's status before you test. A module that failed to import doesn't exist as far as the job is concerned.
- Local-only modules. Anything you use on your laptop (for example
SqlServerorMicrosoft.Graph.*) must be imported into the Automation account or installed on the Hybrid Worker.
Add this line at the top of a failing runbook to see what the job actually loaded:
Get-Module -ListAvailable Az.Accounts, Az.Compute | Select-Object Name, Version | Format-Table | Out-String | Write-Output
$PSVersionTable.PSVersion | Out-String | Write-Output
Step 5: long jobs and fair share
Jobs in Azure sandboxes are unloaded after three hours (fair share). PowerShell runbooks restart from the beginning, and PowerShell Workflow runbooks resume from their last checkpoint. After three such restarts the job ends as Failed, waiting for resources. Sandboxes also cap memory, disk, network sockets and output size. Check the current Automation limits page for the exact figures.
Your options:
- Split the work. A parent runbook enumerates targets and starts one child job per batch with
Start-AzAutomationRunbook. - Make it restartable. Write progress to a storage table or an Automation variable so that a restart skips completed items.
- Run on a Hybrid Runbook Worker. Hybrid Workers aren't subject to fair share or the sandbox limits.
Start-AzAutomationRunbook -ResourceGroupName $rg -AutomationAccountName $aa `
-Name "Invoke-PatchReport" -RunOn "hwg-ops-weu" `
-Parameters @{ SubscriptionId = "<sub-id>"; Batch = 3 }
Step 6: jobs stuck in Queued on a Hybrid Worker
Agent-based (Log Analytics agent) Hybrid Workers are retired. If you still have any, migrate them to extension-based workers first. On an extension-based worker, check the following:
- The extension. Look at
HybridWorkerExtensionprovisioning state on the VM or Arc server. Its detailed status usually names the problem. - The service. On Windows,
Get-Service HybridWorkerService. On Linux,systemctl status hwd. - Outbound access. The worker needs HTTPS (443) to the Automation account's job runtime endpoint (
*.azure-automation.net), or to its private endpoint if the account uses Private Link. If you use a private endpoint, check that the name resolves to the private IP. - Logs. On Windows, look in
C:\WindowsAzure\Logs\Plugins\Microsoft.Azure.Automation.HybridWorker.HybridWorkerForWindows\<version>and theMicrosoft-SMA/Operationalevent log. On Linux, look in/var/log/azure/Microsoft.Azure.Automation.HybridWorker.HybridWorkerForLinuxand/home/hweautomation/run/worker.log. Paths can change between extension versions.
# Extension state on an Azure VM
az vm extension list -g rg-ops-workers --vm-name vm-hrw-01 \
--query "[?contains(name,'HybridWorker')].{name:name, state:provisioningState, ver:typeHandlerVersion}" -o table
# On a Windows worker: service and recent job runtime events
Get-Service HybridWorkerService
Get-WinEvent -LogName "Microsoft-SMA/Operational" -MaxEvents 30 |
Select-Object TimeCreated, Id, LevelDisplayName, Message
Windows workers run jobs as Local System by default, and Linux workers run them as the hweautomation user. If a job works when you run it interactively but fails on the worker, the cause is usually permissions or a module that isn't installed for that account. Install modules machine-wide (Install-Module -Scope AllUsers), or set a Hybrid Worker credential on the group.
Warning
A single worker in a group is a single point of failure. If it's patched, deallocated or loses its extension, every job sent to that group sits in Queued and nobody is told. Run at least two workers per group, in different zones or hosts.
Step 7: the schedule never fired
If the job list shows no job at all for the expected time, the problem is the schedule, not the runbook:
Get-AzAutomationScheduledRunbook -ResourceGroupName $rg -AutomationAccountName $aa -RunbookName "Stop-NonProdVMs"
Get-AzAutomationSchedule -ResourceGroupName $rg -AutomationAccountName $aa -Name "weekday-1900" |
Select-Object Name, IsEnabled, NextRun, ExpiryTime, TimeZone, Frequency
Check four things: the schedule is still enabled, it hasn't passed its ExpiryTime, it's linked to this runbook, and the time zone is what you expect. Also check that the runbook is Published. Editing a runbook leaves a draft, and schedules always run the published version.
Prevent it next time
- Alert on failures. Create a log alert on the
JobLogsquery above (ResultType in ("Failed","Suspended")) that pages the runbook's owner. - Sign in with managed identity only. Grant roles at resource group scope and record them alongside the runbook in source control.
- Pin and test module versions in a non-production Automation account before you update production.
- Design every runbook to finish in well under three hours, or run it on a Hybrid Worker group with at least two workers.
- Add a dead-man check: a weekly query that flags any scheduled runbook with no Completed job in its expected window.
Get the weekly HubDatAI email
One email a week with everything new: posts, learning sessions and videos. Free, no spam, unsubscribe in one click. What you get