---
title: "Azure Monitor Alerts: Stop the Runbook Hunt with an AI Agent"
description: "Connect Azure Monitor alerts to an agent that picks the matching Automation runbook, runs read-only diagnostics, and drafts a fix for approval."
canonical: "https://adamtheautomator.com/azure-monitor-alert-runbook-agent/"
---

# Azure Monitor Alerts: Stop the Runbook Hunt with an AI Agent

> Connect Azure Monitor alerts to an agent that picks the matching Automation runbook, runs read-only diagnostics, and drafts a fix for approval.

Source: https://adamtheautomator.com/azure-monitor-alert-runbook-agent/

---

ATA Learning

Tap to hide

[

ATA Learning

](/)

*   [Home](/)
*   [Tutorials](/tutorials/)
*   [Instructors](/author/)
*   [Advertising](/advertising/)
*   [Recommended Resources](/resources/)
*   [About Adam](/about-adam/)

Search for:  

*   [](https://twitter.com/adbertram)
*   [](https://github.com/Adam-the-Automator)
*   [](https://www.linkedin.com/company/adam-the-automator-llc)
*   [](/feed/)

![Azure Monitor Alerts: Stop the Runbook Hunt with an AI Agent](https://adamtheautomator.com/wp-content/uploads/publisher/4225d9c85b2b819f94cedda2d4f3cc34/e7256366783dcf58f1257496fcade3a6481aa9ec717b34654846aae0c72cc9b1.webp)

# Azure Monitor Alerts: Stop the Runbook Hunt with an AI Agent

[![](https://secure.gravatar.com/avatar/d0b9d42e21e5622713f8b693aa5c0f9244d5f7dd200ed29b8398f52dee5de337?s=192&d=mm&r=g)Adam Bertram](https://adamtheautomator.com/author/adam-bertram/)26 November 202614 min. read

Categories: [AI Agents](/category/ai-agents/)

Tags:[Azure Automation](/tag/azure-automation/)[Azure Monitor](/tag/azure-monitor/)[PowerShell](/tag/powershell/)[AI](/tag/ai/)

Table of Contents

*   [Prerequisites](#prerequisites)
*   [How the Azure Monitor Alert-to-Runbook Flow Works](#how-the-azure-monitor-alert-to-runbook-flow-works)
*   [Step 1: Read the Alert and Pick a Runbook Definition](#step-1-read-the-alert-and-pick-a-runbook-definition)
*   [Read the Alert Payload](#read-the-alert-payload)
*   [Write the Runbook Definition](#write-the-runbook-definition)
*   [Step 2: Give the Agent Read-Only Diagnostics](#step-2-give-the-agent-read-only-diagnostics)
*   [Assign the Read-Only Role](#assign-the-read-only-role)
*   [Give the Model One Query Tool](#give-the-model-one-query-tool)
*   [Step 3: Let the Model Investigate and Draft the Fix](#step-3-let-the-model-investigate-and-draft-the-fix)
*   [Step 4: Wire the Alert to the Agent and Test It](#step-4-wire-the-alert-to-the-agent-and-test-it)
*   [Wire the Alert Rule to the Action Group](#wire-the-alert-rule-to-the-action-group)
*   [Replay a Fake Incident](#replay-a-fake-incident)
*   [Step 5: Approve and Launch the Remediation](#step-5-approve-and-launch-the-remediation)
*   [Azure SRE Agent or Your Own Agent](#azure-sre-agent-or-your-own-agent)
*   [What to Tighten Before Real Alerts Arrive](#what-to-tighten-before-real-alerts-arrive)

What do you want waiting for you when [Azure Monitor](https://learn.microsoft.com/en-us/azure/azure-monitor/overview) pages you at 2:47 a.m. about a web app you didn’t build? The matching runbook definition’s queries have run and a drafted fix is waiting for your approval by the time you open the page.

You build that as an [Azure Automation runbook](https://learn.microsoft.com/en-us/azure/automation/manage-runbooks). An Azure Monitor alert starts an Automation job, the job picks a runbook definition (a JSON document that lists the diagnostics to run and the one fix to propose) from the alert itself, and a model chooses among the read-only queries you wrote and drafts the remediation. The on-call engineer receives the proposal and the launch command for the fix.

## Prerequisites

To build this yourself, you need:

*   An Automation account with its [system-assigned managed identity](https://adamtheautomator.com/secure-azure-managed-identities/) enabled, described in the [Automation security overview](https://learn.microsoft.com/en-us/azure/automation/automation-security-overview), plus the `Az.Accounts` and `Az.OperationalInsights` modules [imported into the account](https://learn.microsoft.com/en-us/azure/automation/shared-resources/modules#import-az-modules). Confirm the identity with `(Get-AzAutomationAccount -ResourceGroupName <resource-group> -Name <account>).Identity.PrincipalId`.
    
*   A [Log Analytics workspace](https://learn.microsoft.com/en-us/azure/azure-monitor/logs/log-analytics-workspace-overview) that receives the tables your diagnostics read, like `AzureActivity` and `AzureMetrics`.
    
*   A model deployment on an [Azure OpenAI](https://learn.microsoft.com/en-us/azure/foundry/foundry-models/concepts/models-sold-directly-by-azure) resource that supports [function calling](https://learn.microsoft.com/en-us/azure/foundry/openai/how-to/function-calling) through the Chat Completions API.
    
*   A [remediation runbook](https://adamtheautomator.com/azure-powershell-runbook-create/) named `Restart-WebApp` that takes an `AppName` parameter, and an HTTPS endpoint that accepts the finished brief.
    
*   An Azure Monitor alert rule on a web app that can carry a custom property, plus [Az PowerShell](https://learn.microsoft.com/en-us/powershell/azure/install-azure-powershell?view=azps-17.0.0) and the [Azure CLI](https://learn.microsoft.com/en-us/cli/azure/install-azure-cli?view=azure-cli-latest) signed in with rights to create Automation variables, webhooks, and role assignments.
    

## How the Azure Monitor Alert-to-Runbook Flow Works

Two things here are called runbooks. A _runbook definition_ is the JSON you write: steps, diagnostic queries, and one fix. An _Automation runbook_ is an Azure Automation script. The agent is one Automation runbook, `Invoke-IncidentAgent`, whose model loop picks which of your queries to run next. Microsoft documents each piece below except the `runbook` custom property, a convention you set on the alert rule.

1.  An alert rule fires and calls an [action group](https://learn.microsoft.com/en-us/azure/azure-monitor/alerts/action-groups).
    
2.  The action group posts the alert to the script’s webhook.
    
3.  The script loads the runbook definition the alert names.
    
4.  The model calls read-only diagnostics and drafts a proposal.
    
5.  The engineer gets the proposal and a launch command.
    

The webhook sits in the middle because [Microsoft Learn lists its response](https://learn.microsoft.com/en-us/azure/automation/automation-webhooks) as 202 Accepted: “The request was accepted, and the runbook was successfully queued.” The [action groups reference](https://learn.microsoft.com/en-us/azure/azure-monitor/alerts/action-groups) says: “After retries attempted to call the webhook fail, no action group calls the endpoint for 15 minutes.” The docs give no caller timeout. The investigation runs in the queued job after the webhook answers.

The diagram shows the path and where a human takes over.

![Alert-to-agent architecture](https://adamtheautomator.com/wp-content/uploads/publisher/7ad178c4f6cb5e9f92aaba52a9a73812e66bcd8e1038441d4368b3b329be708f.png)

## Step 1: Read the Alert and Pick a Runbook Definition

The webhook body carries the alert’s `essentials` block and the `customProperties` you set on the alert rule.

### Read the Alert Payload

The [common alert schema](https://learn.microsoft.com/en-us/azure/azure-monitor/alerts/alerts-common-schema) gives every alert type one JSON shape. The page says you “can use the fields in the Essentials section to provide routing logic for all alert types.” The agent reads five.

| Field | What the agent does with it |
| --- | --- |
| `monitorCondition` | `Fired` starts an investigation. `Resolved` ends the job. |
| `alertTargetIDs` | The first entry is the resource to diagnose. |
| `severity` | `Sev0` to `Sev4`, copied into the brief for triage. |
| `originAlertId` | The alert instance’s ID from the monitoring service, usable as a de-duplication key. |
| `customProperties` | Key:value pairs set on the alert rule. The agent uses a `runbook` key to name the definition. |

Automation starts the runbook on every state change. Microsoft’s [alert-triggered runbook tutorial](https://learn.microsoft.com/en-us/azure/automation/automation-create-alert-triggered-runbook) tells you to “check the alert status in the runbook that is triggered.” Skipping `Resolved` keeps one incident from producing two briefs. The agent assumes a metric alert, where `alertTargetIDs` is the resource. For a log search alert on a workspace, the schema page says the target is the workspace. Read the affected resource from `configurationItems` or a dimension.

### Write the Runbook Definition

Keep every definition in one file, `definitions.json`, keyed by the value you set in the alert’s `runbook` property.

```json
{
  "app-service-5xx": {
    "steps": [
      "Call run_diagnostic with recent_changes to see what changed on the resource.",
      "Call run_diagnostic with metric_summary to see which metrics peaked."
    ],
    "stopConditions": [
      "If a deployment finished in the two hours before the alert, set action to null and name the deployment as the probable cause."
    ],
    "diagnostics": [
      {
        "name": "recent_changes",
        "kql": "AzureActivity | where _ResourceId =~ '{resourceId}' | where CategoryValue == 'Administrative' | project TimeGenerated, OperationNameValue, ActivityStatusValue, Caller | order by TimeGenerated desc"
      },
      {
        "name": "metric_summary",
        "kql": "AzureMetrics | where _ResourceId =~ '{resourceId}' | summarize Peak = max(Maximum), Average = avg(Average) by MetricName | order by Peak desc | take 10"
      }
    ],
    "remediation": {
      "runbook": "Restart-WebApp",
      "automationAccount": "<automation-account>",
      "resourceGroup": "<resource-group>",
      "allowedParameters": ["AppName"]
    }
  }
}
```

*   `steps` and `stopConditions` become the model’s instructions. The example stop condition withholds the restart when a deployment finished in the two hours before the alert, because a rollback is the likelier fix.
    
*   `diagnostics` holds named [Kusto Query Language (KQL)](https://learn.microsoft.com/en-us/kusto/query/) queries, the language Log Analytics uses. The script replaces `{resourceId}` before each query runs.
    
*   `remediation` names the one Automation runbook this definition may propose and the only parameters it may carry.
    

The first block of `Invoke-IncidentAgent` loads the alert and the definition. Later steps add blocks to the same script.

```powershell
param([object] $WebhookData)
$ErrorActionPreference = 'Stop'

$alert = ($WebhookData.RequestBody | ConvertFrom-Json).data
$essentials = $alert.essentials
if ($essentials.monitorCondition -ne 'Fired') {
    Write-Output "Ignoring a $($essentials.monitorCondition) notification."
    return
}

$resourceId = $essentials.alertTargetIDs[0]
if ($resourceId -notmatch '^/subscriptions/[0-9a-f-]{36}/resourceGroups/[\w.()-]+/providers/[\w./-]+$') {
    throw "Unexpected resource ID: $resourceId"
}

$key = $alert.customProperties.runbook
if (-not $key) { throw 'The alert has no runbook custom property.' }
$definition = (Get-AutomationVariable -Name 'RunbookDefinitions' | ConvertFrom-Json).$key
if (-not $definition) { throw "No runbook definition named '$key'." }
```

Automation passes the POST body in through `WebhookData.RequestBody`, as the [webhook documentation](https://learn.microsoft.com/en-us/azure/automation/automation-webhooks) describes. The resource ID check matters because that ID gets pasted into a query. Inside the job, `Get-AutomationVariable` reads [Automation variables](https://learn.microsoft.com/en-us/azure/automation/shared-resources/variables) instead of local files. Step 4 creates `RunbookDefinitions` from `definitions.json`.

## Step 2: Give the Agent Read-Only Diagnostics

Whatever query the model picks, Log Analytics runs it under the Automation account’s managed identity.

### Assign the Read-Only Role

| Actor | Identity | Role | Scope |
| --- | --- | --- | --- |
| `Invoke-IncidentAgent` | Automation account identity | Log Analytics Reader | One workspace |
| Approving engineer | [Microsoft Entra](https://learn.microsoft.com/en-us/entra/fundamentals/what-is-entra) user or group | Automation Job Operator | Automation account |
| Remediation runbook | A second identity, never the agent’s | Website Contributor (no built-in role is restart-only) | The web app |
| Action group webhook | None; the URL token | Not applicable | Not applicable |

Scope the Log Analytics Reader assignment for the `Invoke-IncidentAgent` identity to one workspace. The [workspace access documentation](https://learn.microsoft.com/en-us/azure/azure-monitor/logs/manage-access) says members of that role “can view all monitoring data and monitoring settings.” Scoping the role to the subscription would let one bad alert read unrelated workloads. Automation Job Operator lets the engineer start jobs for [every runbook in the Automation account](https://learn.microsoft.com/en-us/azure/automation/automation-role-based-access-control). And anything else you publish in that account is one command away from the approval role.

The remediation runbook needs its own identity. An Automation account has one system-assigned identity, so a `Restart-WebApp` runbook in the agent’s account that signs in with plain `Connect-AzAccount -Identity` would run as the read-only agent, and giving that identity a write role defeats the split. Host `Restart-WebApp` in a second Automation account and give that account’s system-assigned identity Website Contributor on the web app. The other option is to attach a user-assigned identity to one account and sign in with `Connect-AzAccount -Identity -AccountId <ClientId>`. That option is a convention rather than a boundary, because the identity is attached to the whole account and any runbook in it can sign in with it. With a second account, set `remediation.automationAccount` in `definitions.json` to the account that hosts `Restart-WebApp` (the Step 3 script builds the launch command from it), assign the engineer Automation Job Operator on that account, and use its name in the Step 5 job-check command. No built-in role grants only the restart action, and Website Contributor is the closest fit for a plain web app. A custom role is the only restart-only option.

```powershell
$resourceGroup = '<resource-group>'
$account = '<automation-account>'
$principalId = (Get-AzAutomationAccount -ResourceGroupName $resourceGroup -Name $account).Identity.PrincipalId
New-AzRoleAssignment -ObjectId $principalId -RoleDefinitionName 'Log Analytics Reader' -Scope '<workspace-resource-id>'
```

* * *

_**Warning: Check that the identity holds nothing else before the first alert fires. `Get-AzRoleAssignment -ObjectId $principalId | Select-Object RoleDefinitionName, Scope` should return one row, Log Analytics Reader on the workspace. Remove any write role that appears.**_

* * *

### Give the Model One Query Tool

The model’s only tool runs one named query.

```powershell
Disable-AzContextAutosave -Scope Process | Out-Null
Connect-AzAccount -Identity | Out-Null
$workspaceId = Get-AutomationVariable -Name 'WorkspaceId'  # Step 4 creates this variable

function Invoke-Diagnostic([string] $Name) {
    $diagnostic = $definition.diagnostics | Where-Object { $_.name -eq $Name }
    if (-not $diagnostic) { return "No diagnostic named '$Name'." }
    $kql = $diagnostic.kql.Replace('{resourceId}', $resourceId)
    $result = Invoke-AzOperationalInsightsQuery -WorkspaceId $workspaceId -Query $kql -Timespan (New-TimeSpan -Hours 2) -Wait 120
    $rows = @([System.Linq.Enumerable]::ToArray($result.Results) | Select-Object -First 20)
    if ($rows.Count -eq 0) { return 'The query returned no rows.' }
    return ($rows | ConvertTo-Json -Depth 4 -Compress)
}
```

[`Connect-AzAccount -Identity`](https://adamtheautomator.com/connect-azaccount/) signs in as the managed identity you just scoped. `Disable-AzContextAutosave -Scope Process` stops the job [inheriting a saved Azure context](https://learn.microsoft.com/en-us/azure/automation/enable-managed-identity-for-automation#authenticate-access-with-system-assigned-managed-identity). `-Timespan` sets the two-hour window that an `ago()` filter would otherwise set. `-Wait` sets how many seconds the query may run (service default 3 minutes, maximum 10 minutes) and, since Az.OperationalInsights 3.2.1, also sets the cmdlet’s own timeout. Raising it is the workaround the [Invoke-AzOperationalInsightsQuery reference](https://learn.microsoft.com/en-us/powershell/module/az.operationalinsights/invoke-azoperationalinsightsquery) suggests for “The request was canceled due to the configured HttpClient.Timeout of 100 seconds elapsing.” Capping rows with `Select-Object -First 20` also limits exposure, because log lines carry text outsiders influence. The function calling guide warns: “Untrusted data in a function’s output could be used to instruct the model to write function calls in a way other than you intended.” But poisoned log lines can still reorder the queries or bias the summary.

## Step 3: Let the Model Investigate and Draft the Fix

The model picks the order of your queries and turns their rows into a short root cause analysis and a proposal. Microsoft’s [function calling guide](https://learn.microsoft.com/en-us/azure/foundry/openai/how-to/function-calling) leaves execution to your application. Here the script runs each query and returns the rows to the model.

```powershell
$endpoint = (Get-AutomationVariable -Name 'AoaiEndpoint').TrimEnd('/')
$headers = @{ 'api-key' = (Get-AutomationVariable -Name 'AoaiKey') }
$deployment = Get-AutomationVariable -Name 'AoaiDeployment'

$tools = @(@{
    type = 'function'
    function = @{
        name = 'run_diagnostic'
        description = 'Run one named read-only diagnostic query for the alerted resource.'
        parameters = @{
            type = 'object'
            properties = @{ name = @{ type = 'string'; enum = @($definition.diagnostics.name) } }
            required = @('name')
        }
    }
})

$system = @(
    'You investigate one Azure Monitor alert. Follow these steps in order:'
    $definition.steps
    'Stop conditions:'
    $definition.stopConditions
    "You may propose only the runbook '$($definition.remediation.runbook)' with these parameters: $($definition.remediation.allowedParameters -join ', ')."
    'When you have enough evidence, reply with JSON only: {"summary": "", "probable_cause": "", "evidence": [""], "action": {"runbook": "", "parameters": {}}}. Use null for action if no fix is justified.'
) -join "`n"

$messages = @(
    @{ role = 'system'; content = $system }
    @{ role = 'user'; content = "Alert '$($essentials.alertRule)' ($($essentials.severity)) fired on $resourceId." }
)

for ($turn = 1; $turn -le 5; $turn++) {
    $body = @{ model = $deployment; messages = $messages; tools = $tools } | ConvertTo-Json -Depth 10
    $response = Invoke-RestMethod -Method Post -Uri "$endpoint/openai/v1/chat/completions" -Headers $headers -ContentType 'application/json' -Body $body
    $reply = $response.choices[0].message
    $messages += $reply
    if (-not $reply.tool_calls) { break }
    foreach ($call in $reply.tool_calls) {
        $toolArgs = $call.function.arguments | ConvertFrom-Json
        $messages += @{ role = 'tool'; tool_call_id = $call.id; content = (Invoke-Diagnostic $toolArgs.name) }
    }
}
if ($reply.tool_calls) { throw 'The model was still calling tools after 5 turns.' }
```

The request follows the [chat completions reference](https://learn.microsoft.com/en-us/rest/api/microsoft-foundry/azureopenai/chat): a `POST` to `{endpoint}/openai/v1/chat/completions` with the key in the `api-key` header. The script supplies every word of KQL; the `enum` only lets the model pick a diagnostic name. After five turns the job fails.

* * *

_**Reality Check: If no diagnostic can see the cause, the model still writes a confident summary from whatever rows it received. Read the evidence list before you run the launch command.**_

* * *

This block parses the JSON, enforces the allow list, and builds the engineer’s launch command.

```powershell
$proposal = $reply.content | ConvertFrom-Json
$fix = $definition.remediation
$launch = 'No remediation proposed. The engineer decides.'
if ($proposal.action) {
    if ($proposal.action.runbook -ne $fix.runbook) { throw "Unexpected runbook: $($proposal.action.runbook)" }
    $names = @($proposal.action.parameters.PSObject.Properties.Name | Where-Object { $_ })
    $outside = @($names | Where-Object { $fix.allowedParameters -notcontains $_ })
    if ($outside.Count -gt 0) { throw "Parameters outside the allow list: $($outside -join ', ')" }
    $pairs = $names | ForEach-Object { "'{0}' = '{1}'" -f $_, ([string]$proposal.action.parameters.$_).Replace("'", "''") }
    $launch = "Start-AzAutomationRunbook -ResourceGroupName '$($fix.resourceGroup)' -AutomationAccountName '$($fix.automationAccount)' -Name '$($fix.runbook)' -Parameters @{ $($pairs -join '; ') }"
}

$brief = [ordered]@{
    alert         = $essentials.alertRule
    severity      = $essentials.severity
    resource      = $resourceId
    summary       = $proposal.summary
    probableCause = $proposal.probable_cause
    evidence      = $proposal.evidence
    launch        = $launch
} | ConvertTo-Json -Depth 4
Write-Output $brief
Write-Output $launch
Invoke-RestMethod -Method Post -Uri (Get-AutomationVariable -Name 'BriefUrl') -ContentType 'application/json' -Body $brief | Out-Null
```

Invalid JSON makes `ConvertFrom-Json` throw, and so does any runbook name or parameter outside the definition. Doubled single quotes keep a stray apostrophe from breaking out of the generated command. `BriefUrl` can point at any HTTP endpoint you own, for example a [Logic Apps](https://learn.microsoft.com/en-us/azure/logic-apps/logic-apps-overview) workflow with a [“When a HTTP request is received”](https://learn.microsoft.com/en-us/azure/logic-apps/logic-apps-http-endpoint) trigger that posts to Teams. The brief also lands in the job output, where the Step 4 test reads it. Windows PowerShell 5.1 (the runbook runtime) makes `ConvertTo-Json` escape every single quote as `\u0027`, so the `launch` line inside the JSON can’t be pasted as-is. `Write-Output $launch` prints the same command as plain text at the end of the job output.

## Step 4: Wire the Alert to the Agent and Test It

Save Steps 1 to 3 as `Invoke-IncidentAgent.ps1`, then publish it and store its settings. The import uses `-Type PowerShell` (the PowerShell 5 runtime the [webhook page](https://learn.microsoft.com/en-us/azure/automation/automation-webhooks) recommends for webhook input) instead of `PowerShell72`. The key and brief URL go in as encrypted variables.

```powershell
$common = @{ ResourceGroupName = $resourceGroup; AutomationAccountName = $account }
Import-AzAutomationRunbook @common -Path ./Invoke-IncidentAgent.ps1 -Name Invoke-IncidentAgent -Type PowerShell -Published -Force

$settings = @{
    WorkspaceId        = '<workspace-id>'
    AoaiEndpoint       = 'https://<resource-name>.openai.azure.com'
    AoaiDeployment     = '<deployment-name>'
    RunbookDefinitions = (Get-Content ./definitions.json -Raw)
}
foreach ($name in $settings.Keys) {
    New-AzAutomationVariable @common -Name $name -Encrypted $false -Value $settings[$name]
}
New-AzAutomationVariable @common -Name AoaiKey -Encrypted $true -Value '<model-api-key>'
New-AzAutomationVariable @common -Name BriefUrl -Encrypted $true -Value '<https-endpoint-you-own>'
```

The webhook URL is the only credential on this path, and the [Azure Automation webhooks article](https://learn.microsoft.com/en-us/azure/automation/automation-webhooks) says: “The URL contains a security token that allows a third-party system to invoke the runbook with no further authentication. For this reason, you should treat the URL like a password.” `New-AzAutomationWebhook` returns the URL only once; `$uri` keeps it for the action group.

```powershell
$webhook = New-AzAutomationWebhook @common -Name incident-agent-hook -RunbookName Invoke-IncidentAgent -IsEnabled $true -ExpiryTime ([DateTimeOffset]::UtcNow.AddMonths(6)) -Force
$uri = $webhook.WebhookURI

az monitor action-group create --name ag-incident-agent --resource-group $resourceGroup --short-name incagent --action webhook incident-agent $uri usecommonalertschema
```

* * *

_**Warning: The Step 4 `New-AzAutomationVariable` and `New-AzAutomationWebhook` commands store a model key and create a webhook that can start a runbook. Every test bills your model deployment for tokens.**_

* * *

`usecommonalertschema` enables the common schema, set per action. Add the six-month expiry date to the on-call calendar. The [Automation webhook reference](https://learn.microsoft.com/en-us/azure/automation/automation-webhooks) warns: “Once a webhook has expired, you can’t reactivate it. You can only remove and then recreate it.”

### Wire the Alert Rule to the Action Group

The [`az monitor metrics alert update` reference](https://learn.microsoft.com/en-us/cli/azure/monitor/metrics/alert?view=azure-cli-latest) describes `--add-action` as an action group plus optional `KEY=VAL` webhook properties. This rule sends `runbook=app-service-5xx` as one of them.

```powershell
$actionGroupId = az monitor action-group show --name ag-incident-agent --resource-group $resourceGroup --query id --output tsv
az monitor metrics alert update --name '<alert-rule-name>' --resource-group '<app-resource-group>' --add-action "$actionGroupId runbook=app-service-5xx"
```

Pass the group ID and the property as one quoted argument. Azure CLI 2.85.0 exits without an error but drops the property when they are separate arguments. Confirm it landed:

```powershell
az monitor metrics alert show --name '<alert-rule-name>' --resource-group '<app-resource-group>' --query "actions[].webHookProperties"
```

The output is a list with one object:

```json
[
  {
    "runbook": "app-service-5xx"
  }
]
```

The error “The alert has no runbook custom property” means the pair didn’t reach `customProperties`. Keep your paging group on the rule in case the agent fails: [up to five action groups](https://learn.microsoft.com/en-us/azure/azure-monitor/alerts/action-groups) run concurrently on one rule.

### Replay a Fake Incident

Use a real web app with activity for the diagnostics to read.

```powershell
$testPayload = @'
{
  "schemaId": "azureMonitorCommonAlertSchema",
  "data": {
    "essentials": {
      "alertRule": "orders-api-5xx",
      "severity": "Sev2",
      "monitorCondition": "Fired",
      "alertTargetIDs": ["/subscriptions/<subscription-id>/resourceGroups/<app-resource-group>/providers/Microsoft.Web/sites/<app-name>"],
      "originAlertId": "test-0001"
    },
    "customProperties": { "runbook": "app-service-5xx" }
  }
}
'@
$response = Invoke-WebRequest -Method Post -Uri $uri -Body $testPayload -UseBasicParsing
$jobId = (ConvertFrom-Json $response.Content).JobIds[0]
do {
    Start-Sleep -Seconds 15
    $job = Get-AzAutomationJob @common -Id $jobId
} while ($job.Status -notin 'Completed', 'Failed', 'Stopped', 'Suspended')
$job.Status
Get-AzAutomationJobOutput @common -Id $jobId -Stream Output
```

A successful POST returns 202 and `{"JobIds":["<JobId>"]}`. The loop checks every 15 seconds until the job reaches a final status, then prints the brief, which has this shape (the `\u0027` sequences are how PowerShell 5.1 escapes single quotes):

```json
{
  "alert": "orders-api-5xx",
  "severity": "Sev2",
  "resource": "/subscriptions/<subscription-id>/resourceGroups/<app-resource-group>/providers/Microsoft.Web/sites/<app-name>",
  "summary": "<the model's short root cause analysis>",
  "probableCause": "<the cause the model names>",
  "evidence": ["<the rows the model cites>"],
  "launch": "Start-AzAutomationRunbook -ResourceGroupName \u0027<resource-group>\u0027 ... or: No remediation proposed. The engineer decides."
}
```

The job output ends with the `launch` value again as a plain line, but the console wraps it across indented lines. Run this command to print it as one string, then copy its output, not the escaped one inside the JSON:

```powershell
(Get-AzAutomationJobOutput @common -Id $jobId -Stream Output)[-1].Summary
```

`Failed` means a variable or the `runbook` property is missing, or the model hit the five-turn cap; `Get-AzAutomationJobOutput @common -Id $jobId -Stream Error` shows which. To tear down, run:

```powershell
az monitor metrics alert update --name '<alert-rule-name>' --resource-group '<app-resource-group>' --remove-actions $actionGroupId
Remove-AzAutomationWebhook @common -Name incident-agent-hook
'WorkspaceId', 'AoaiEndpoint', 'AoaiDeployment', 'RunbookDefinitions', 'AoaiKey', 'BriefUrl' | ForEach-Object { Remove-AzAutomationVariable @common -Name $_ }
Remove-AzRoleAssignment -ObjectId $principalId -RoleDefinitionName 'Log Analytics Reader' -Scope '<workspace-resource-id>'
az monitor action-group delete --name ag-incident-agent --resource-group $resourceGroup
```

## Step 5: Approve and Launch the Remediation

The `(Get-AzAutomationJobOutput @common -Id $jobId -Stream Output)[-1].Summary` command from Step 4 prints the launch command as one plain line, the same text as the brief’s `launch` field, shaped like this:

```powershell
Start-AzAutomationRunbook -ResourceGroupName '<resource-group>' -AutomationAccountName '<automation-account>' -Name 'Restart-WebApp' -Parameters @{ 'AppName' = '<app-name>' }
```

Approval happens when the engineer reads the evidence and runs that command. According to the [cmdlet reference](https://learn.microsoft.com/en-us/powershell/module/az.automation/start-azautomationrunbook), `Start-AzAutomationRunbook` returns a job by default and waits only with `-Wait`. Building an approval button would take a callback URL, stored approval state, and a second webhook. The engineer’s Automation Job Operator role is what lets them start the fix, provided they also have [read permission on the resource group that holds the Automation account](https://learn.microsoft.com/en-us/azure/automation/automation-role-based-access-control). Each identity in the diagram below holds a different permission.

![Agent approval swimlanes](https://adamtheautomator.com/wp-content/uploads/publisher/423f2da18b27b4681a0d1b9199a6253fec3486e78ad925495a05284f9f4abde1.png)

To confirm the fix ran, list the `Restart-WebApp` jobs from the last 10 minutes and look for `Completed`:

```powershell
Get-AzAutomationJob -ResourceGroupName '<resource-group>' -AutomationAccountName '<automation-account>' -RunbookName 'Restart-WebApp' -StartTime (Get-Date).AddMinutes(-10) | Select-Object JobId, Status
```

If the 5xx rate then drops and the rule resolves, Azure Monitor sends a `Resolved` notification, which `Invoke-IncidentAgent` logs and ignores.

Microsoft’s function calling guide also recommends [confirming an action before it runs](https://learn.microsoft.com/en-us/azure/foundry/openai/how-to/function-calling). The launch command plays that role here.

## Azure SRE Agent or Your Own Agent

Microsoft has a managed version of an alert-driven incident-response agent. The [Azure SRE Agent overview](https://learn.microsoft.com/en-us/azure/sre-agent/overview) describes it as finding probable causes for an incident and proposing mitigations, or running them when you configure it to.

| Decision | Custom agent (this post) | Azure SRE Agent |
| --- | --- | --- |
| Alert intake | Any alert that reaches an action group webhook | Azure Monitor Alerts, PagerDuty, or ServiceNow |
| Approval | Nothing runs until an engineer starts the remediation runbook | Review mode asks approval for Azure infrastructure operations |
| Your procedures | Runbook definitions you write and version | Skills, including marketplace runbooks, plus custom agents and hooks |
| Upkeep | You own the script, prompts, model key, and tests | You configure an incident response plan and permissions |

The [run modes page](https://learn.microsoft.com/en-us/azure/sre-agent/run-modes) says review mode shows approval buttons “only for Azure infrastructure operations.” Sending email or posting to Teams proceeds without one.

If you adopt the SRE Agent, the [run modes guidance](https://learn.microsoft.com/en-us/azure/sre-agent/run-modes) recommends starting in review mode and, after two to four weeks, moving only the triggers you consistently approve to Autonomous. When your incidents live in PagerDuty or ServiceNow, pick the SRE Agent. Your own build fits when Azure RBAC must gate a command you can read, or when your procedures exist as files.

## What to Tighten Before Real Alerts Arrive

The Step 4 test payload never exercises the duplicate deliveries and webhook expiry that real alert streams bring.

| Failure | What goes wrong | Guard |
| --- | --- | --- |
| Duplicate deliveries or an alert storm | Two jobs and two token bills for one incident, or one job per alert from a flapping rule | Store `originAlertId` in an Automation variable and skip repeats inside a cooldown window (not in the sample); key the same cooldown on `alertRule` and split alerts by dimension |
| Expired webhook | Alerts stop reaching the agent without an error, because an expired [webhook can’t be reactivated](https://learn.microsoft.com/en-us/azure/automation/automation-webhooks) | A rotation date, plus an alert on failed or missing jobs for `Invoke-IncidentAgent` |

Replay a payload for a resource with a recent deployment and confirm the stop condition withholds the restart. Track how often engineers approve the launch command, because that ratio shows whether your diagnostics can see the cause. Start with one definition on one rule and add the next once engineers approve its launch commands.

Share this article

[Share on X](https://twitter.com/intent/tweet?url=https%3A%2F%2Fadamtheautomator.com%2Fazure-monitor-alert-runbook-agent%2F&text=Azure%20Monitor%20Alerts%3A%20Stop%20the%20Runbook%20Hunt%20with%20an%20AI%20Agent)[Share on Facebook](https://www.facebook.com/sharer/sharer.php?u=https%3A%2F%2Fadamtheautomator.com%2Fazure-monitor-alert-runbook-agent%2F)[Share on LinkedIn](https://www.linkedin.com/sharing/share-offsite/?url=https%3A%2F%2Fadamtheautomator.com%2Fazure-monitor-alert-runbook-agent%2F)

## Related Posts

![](https://adamtheautomator.com/wp-content/uploads/publisher/3f25d9c85b2b81c28cc6c39755dac3c7/423d6296450a064f65dba039d6aec0339ac2ba3b86b2f0ef3706c81ff1e57223.webp)

### [Notion Automation: Pick the Right Tier Every Time](/notion-automation-agents-vs-workers/)

Pick the right Notion automation tier: compare database automations, Custom Agents, and Workers, and split ticket routing to cut credit costs.

![](https://adamtheautomator.com/wp-content/uploads/publisher/3f25d9c85b2b8114a4eaea746fdde119/3e64cba088977a23c019e580855960ecff3338dc2fbb3b87595bece2d6b6a02e.webp)

### [Notion Custom Agents: Automate Support Request Routing](/notion-custom-agents-support-routing/)

Build a Notion Custom Agent that reads each new support request, recommends an urgency, and assigns an owner from a routing directory you maintain.

![](https://adamtheautomator.com/wp-content/uploads/publisher/2e05d9c85b2b81feb24af1f04a889143/3eab14af9dabf46fbd333914ce6ccf46f84117d2394d3e7218c186cd249bb7e2.webp)

### [PowerShell or Power Automate: Stop Automation Mistakes](/powershell-vs-power-automate/)

Score six factors to choose between PowerShell and Power Automate: target system, complexity, data volume, team skills, cost, governance.

## Categories

*   [IT Ops](/category/it-ops/)
*   [Cloud](/category/cloud/)
*   [DevOps](/category/devops/)
*   [Home Ops](/category/home-ops/)
*   [Information Security](/category/infosec/)
*   [Software Development](/category/software-development/)

## Site

*   [Home](/)
*   [Tutorials](/tutorials/)
*   [Instructors](/author/)
*   [Advertising](/advertising/)
*   [Recommended Resources](/resources/)
*   [About Adam](/about-adam/)

Copyright 2026© ATA Learning | [Privacy Policy](/privacy/)
