You are currently viewing Build an AI incident assistant on Azure with Logic Apps, Azure OpenAI and Terraform

Build an AI incident assistant on Azure with Logic Apps, Azure OpenAI and Terraform

Summary: When an Azure Monitor alert fires, this assistant reads the last 15 minutes of your app’s logs, asks Azure OpenAI to explain what is going on, and emails the on-call engineer a short incident note: what is wrong, the likely cause with the real error message, the evidence, who is affected and what to check first. It is built with a Logic App (Consumption), Azure OpenAI and Azure Communication Services, deployed with Terraform through GitHub Actions, and it uses a managed identity for every call, so there are no keys to leak. It only reads and reports; it never changes anything. This guide takes you through every step, from an empty subscription to your first real incident email, using the code in my public GitHub repo.

The first five minutes of an incident are usually spent doing the same thing: open the portal, find the logs, write a query, scroll, work out which error matters. I wanted that part done before I even open my laptop. So when an alert fires, the email that tells me about it already contains the answer to “what broke and why”.

I built this to watch my Policy Assistant (an Azure OpenAI app I wrote about in an earlier guide), then broke that app on purpose to prove it works. Everything below is what I actually ran. The code is at github.com/Ositau/ai-incident-assistant.

What you’ll end up with

A real email from one of my tests. I switched off the AI model the Policy Assistant depends on, and about three minutes later this arrived:

An incident email: high failure rate on /api/selftest due to a missing deployment, with the likely cause, evidence, impact and next steps
A real incident note. The likely cause quotes the exact error from the app’s logs, and the evidence has counts and times.

Every note has the same parts:

  • Title and summary: what is wrong and since when.
  • Likely cause: the most likely cause, quoting the actual error message from the logs.
  • Evidence: three to five facts with numbers and times.
  • Impact: which endpoints are affected, and whether it is real users or test traffic.
  • Next steps: what to check first.
  • Confidence: low, medium or high. When the logs don’t show a problem, it says so and sets confidence to low instead of inventing one.

When the alert clears, you get one short “resolved” email instead of a second essay.

How it works

Diagram: your app sends logs to Log Analytics, Azure Monitor alert rules call an action group, which calls the Logic App; the Logic App queries the logs, asks Azure OpenAI for a note and sends it by email
The whole system. Everything in the purple box is one Logic App, kept in Git as a JSON file.
  1. Your app writes logs to a Log Analytics workspace through Application Insights: every request, every exception, plus platform events such as a new revision starting.
  2. Two Azure Monitor alert rules check those logs every 5 minutes. One fires when any request fails with a 5xx error. The other fires when the average response time goes over 5 seconds.
  3. An action group passes the alert to the Logic App.
  4. The Logic App replies to Azure Monitor straight away (so it doesn’t retry and send duplicates), then:
  5. if the alert is a “resolved” notice, sends a one-paragraph email and stops;
  6. otherwise runs three read-only log queries for the 15 minutes before the alert: requests by endpoint, exceptions, and platform events;
  7. sends the alert and that evidence to Azure OpenAI, which must answer in a fixed JSON shape;
  8. if the AI call fails, builds a plain fallback note with the raw evidence, so you still get an email;
  9. emails the note through Azure Communication Services.

The Logic App runs as its own managed identity (an identity Azure manages, with no password or key). It has exactly three roles: read the logs, call Azure OpenAI, send email. It cannot restart, scale or change anything, and the tests in the repo check that it only ever calls those three services.

Why Logic Apps and not Azure Functions

I compared both before building. For this job, the Logic App wins:

Logic Apps (Consumption) Azure Functions
What you write A workflow definition (JSON), no code to host Code, packages and a deployment
Calling Azure services with a managed identity Built into the HTTP action, one setting Add the Azure SDK and handle tokens in code
Seeing what happened in a run Every step’s inputs and outputs are in the run history Only what you log yourself
Cost at this volume Per action run: fractions of a penny per incident Also pennies on the Consumption plan
Testing Harder, so I added static checks on the JSON Easier: normal unit tests

The run history was the deciding factor: when a note looks wrong, I can open the run and see exactly what evidence the model was given. I avoided Logic Apps Standard, which has a fixed monthly plan charge (well over £100 a month at the smallest size when I checked), because Consumption only charges when something runs.

Before you start

You need:

  • An Azure subscription where you are Owner (the setup script creates resource groups and assigns roles).
  • Permission to create an app registration in Microsoft Entra ID. Most personal and test tenants allow this by default.
  • A GitHub account.
  • An app to watch that sends its logs to a Log Analytics workspace through workspace-based Application Insights. I use the Policy Assistant from my earlier guide; if you build that first, everything below works exactly as written. If you watch your own app, see “Watching your own app” near the end.
  • An Azure OpenAI resource with a gpt-4o-mini deployment. The Policy Assistant already has one, and I reuse it.
  • On your machine: Azure CLI, Git, Python 3.10 or later and the GitHub CLI (gh). You don’t need Terraform locally: GitHub Actions runs it.

On Windows, run the commands in Git Bash and run export MSYS_NO_PATHCONV=1 first. Without it, Git Bash rewrites anything starting with /subscriptions/ into a Windows path and the Azure commands fail.

What it costs

  • Logic App: charged per action run. One incident runs about 15 actions, which costs a fraction of a penny.
  • Azure OpenAI: one note uses roughly 2,000 to 4,000 tokens, about £0.0005 with gpt-4o-mini.
  • Email: about £0.0002 per message.
  • Alert rules: the only fixed cost. Log alert rules are billed per rule per month depending on how often they run; at a 5-minute check it is roughly $1.50 a month each at list price. Check the Azure Monitor pricing page for your region.
  • Terraform state storage: pennies a month.

Step 1: Get your own copy of the code

Fork Ositau/ai-incident-assistant to your GitHub account (the Fork button, top right). On your fork, open the Actions tab and click I understand my workflows, go ahead and enable them, because GitHub switches workflows off on new forks.

Then clone it:

git clone https://github.com/<your-github-user>/ai-incident-assistant.git
cd ai-incident-assistant

What’s in it:

Path What it is
workflow/definition.json The Logic App, as code
infra/ Terraform: the Logic App, its identity and three roles, the email service, the alert rules and the action group
scripts/bootstrap.sh One-time setup: resource groups, Terraform state storage, and the identity GitHub Actions signs in with
tests/test_definition.py Static checks on the workflow, run on every pull request
tests/send_sample_alert.py Sends a test alert to the deployed Logic App and checks the note (used after every deploy)
tests/fault_drill.py Breaks the watched app on purpose and waits for the real alert and email
.github/workflows/deploy.yml The pipeline: checks and an AI review of the plan on pull requests; apply and a test on main

Step 2: Run the one-time setup script

Sign in with the Azure CLI and pick the subscription:

az login
az account set --subscription "<your subscription name or ID>"

Then run the setup script. Set WATCHED_RG to the resource group of the app you’re watching (the one with its Log Analytics workspace and Azure OpenAI resource):

export MSYS_NO_PATHCONV=1   # Git Bash on Windows only
GITHUB_OWNER=<your-github-user> GITHUB_REPO=ai-incident-assistant \
WATCHED_RG=rg-policy-assistant-demo \
bash scripts/bootstrap.sh

It takes two or three minutes and does five things:

  1. Registers the resource providers this project uses (Communication, Logic, Insights, OperationalInsights, Storage). A new subscription doesn’t have them all, and the pipeline identity isn’t allowed to register them itself.
  2. Creates two resource groups: rg-incident-assistant for the assistant, and rg-incident-assistant-tfstate for Terraform’s state.
  3. Creates a storage account for Terraform state with storage keys switched off, so only Entra ID sign-ins can read it.
  4. Creates the identity GitHub Actions signs in with: an app registration called “AI incident assistant (GitHub Actions)” with two federated credentials, one for pull requests and one for the main branch. GitHub proves who it is with a short-lived token, so there is no client secret to store or rotate.
  5. Gives that identity only what it needs: Contributor on its own resource group, Reader on the watched app’s resource group, permission to call Azure OpenAI (for the AI review of each plan), access to the state container, and a limited role administrator role that can only hand out the three roles the Logic App needs.
READ MORE  Test your AI assistant before every release: a simple evaluation gate in Azure DevOps

You should see a list of values to copy at the end:

Terminal: the setup script finishes and prints the five GitHub variables; a role listing shows the pipeline identity's six role assignments, two of them limited
The end of the setup script, and the pipeline identity’s roles. ‘Limited’ means the role administrator can only assign three specific roles.

The script is safe to run again: it reuses the app registration and skips anything that already exists.

Step 3: Collect the details of the app you’re watching

Terraform needs four values: the watched workspace, the Azure OpenAI resource and its endpoint, and the email address that gets the notes. Get the first three with:

az monitor log-analytics workspace list -g rg-policy-assistant-demo --query "[0].id" -o tsv
az cognitiveservices account list -g rg-policy-assistant-demo \
  --query "[?kind=='OpenAI'] | [0].{id:id, endpoint:properties.endpoint}" -o json

Put them together as one JSON value. Keep it on one line:

{"watched_workspace_id": "/subscriptions/<sub>/resourceGroups/rg-policy-assistant-demo/providers/Microsoft.OperationalInsights/workspaces/<workspace>", "openai_account_id": "/subscriptions/<sub>/resourceGroups/rg-policy-assistant-demo/providers/Microsoft.CognitiveServices/accounts/<openai>", "openai_endpoint": "https://<openai>.openai.azure.com/", "alert_email": "you@example.com"}

The other settings have sensible defaults in infra/variables.tf: the region (swedencentral), the model deployment name (gpt-4o-mini), the app’s friendly name used in alert titles (Policy Assistant) and where email data is stored (UK). To change one, add it to the same JSON, for example "watched_app_name": "My App".

Step 4: Add the GitHub repository variables

The pipeline reads everything from repository variables. None of these values is a secret: they are IDs and names, and sign-in happens through the federated credential.

With the GitHub CLI, from inside your clone:

gh variable set AZURE_CLIENT_ID       --body "<AZURE_CLIENT_ID from the script>"
gh variable set AZURE_TENANT_ID       --body "<AZURE_TENANT_ID from the script>"
gh variable set AZURE_SUBSCRIPTION_ID --body "<AZURE_SUBSCRIPTION_ID from the script>"
gh variable set TF_STATE_RG           --body "rg-incident-assistant-tfstate"
gh variable set TF_STATE_ACCOUNT      --body "<TF_STATE_ACCOUNT from the script>"
gh variable set AZURE_OPENAI_ENDPOINT --body "https://<openai>.openai.azure.com/"
gh variable set TF_VARS_JSON          --body '<the one-line JSON from step 3>'

Or add them in the browser under Settings > Secrets and variables > Actions > Variables > New repository variable. You should end up with seven:

GitHub repository variables: AZURE_CLIENT_ID, AZURE_OPENAI_ENDPOINT, AZURE_SUBSCRIPTION_ID, AZURE_TENANT_ID, TF_STATE_ACCOUNT, TF_STATE_RG and TF_VARS_JSON, with values masked
The seven repository variables (values masked). AZURE_OPENAI_ENDPOINT is used by the AI review of each Terraform plan.

Step 5: Deploy

In your fork, open Actions > deploy > Run workflow, keep the branch as main, and click Run workflow. (Any later push to main deploys too.)

On main the pipeline runs two jobs:

  1. checks: the static tests on the workflow definition. They catch typos in action names and expressions, make sure every HTTP call uses the managed identity, and make sure the Logic App only calls the logs, Azure OpenAI and email.
  2. apply: terraform apply, a 90-second pause so the new role assignments take effect, then a post-deploy test: it sends a sample alert to the deployed Logic App in dry-run mode (no email), waits for the run and checks the note has every part.
GitHub Actions run summary: checks passed, plan skipped, apply passed, total 1 minute 31 seconds
A deploy from main. Plan only runs on pull requests; apply runs on main.

The first deploy takes a few minutes longer because it creates the email service. When it finishes, open the apply job and expand the last step. The sample alert is sent while nothing is actually wrong, so a good note says exactly that:

The post-deploy test output: a note with confidence low saying there is no evidence of failures and the alert may be a false alarm, then PASSED
The post-deploy test. Nothing was failing, and the note says ‘no evidence of any failures’, low confidence. PASSED means every part of the note was there.

That is the behaviour I care most about. An on-call tool that confidently invents a cause for a false alarm will be ignored after the second time.

What Terraform created

az resource list -g rg-incident-assistant --query "[].{Name:name, Type:type}" -o table
Terminal: eight resources in rg-incident-assistant: communication service, email service and its managed domain, the Logic App, the action group, two alert rules and the managed identity
Everything the assistant needs, in its own resource group.
Resource What it does
la-incident-assistant The Logic App
id-incident-assistant The Logic App’s managed identity (user-assigned, so its roles never change when the workflow is edited)
ecs-incident-assistant + AzureManagedDomain The email service, with a free Azure-managed sending domain (no DNS records to set up)
acs-incident-assistant-xxxxxx The Communication Services resource that sends the email
ag-incident-assistant The action group that calls the Logic App
alert-failing, alert-slow The two alert rules on the watched app’s logs

Terraform also gives the identity its three roles on the watched workspace, the Azure OpenAI resource and the email service.

Emails come from DoNotReply@<random-id>.azurecomm.net. The first one may land in your junk folder: mark it as not junk.

Step 6: Make changes through pull requests

Every change goes through a pull request. On a pull request, the pipeline runs the checks, then terraform plan, then an AI review of the plan using my AI Terraform reviewer, which posts a comment explaining what will change and flags anything risky:

Pull request comment: Terraform plan review, medium risk, 0 to create, 3 to update, 0 to replace, 0 to delete, with a table of concerns
The plan review on one of my pull requests: three in-place updates, nothing replaced or deleted.

The line to read first is the count. Editing the workflow should always be “1 to update” (plus anything you changed on purpose). If a workflow edit ever plans to replace role assignments, stop: that would briefly remove the Logic App’s access. That is exactly why the Logic App uses a user-assigned identity: its ID is known before the plan runs, so editing the workflow never touches the roles.

READ MORE  Test your AI assistant before every release: a simple evaluation gate in Azure DevOps

You can run the same static checks locally before you push:

python -m venv .venv
.venv/Scripts/pip install pytest      # on macOS/Linux: .venv/bin/pip
.venv/Scripts/python -m pytest -q

Step 7: Give your app a safe way to break

To prove the assistant works you need real failures, but you don’t want to break the app for real users. The Policy Assistant has a self-test endpoint for this, GET /api/selftest, and the code is in its repo (app/selftest.py). If you built the Policy Assistant from my earlier guide, pull the latest code and redeploy it to get it.

The self-test runs one fixed check against the real services: it turns a question into an embedding with Azure OpenAI and runs one search in Azure AI Search. It returns no policy content, only whether the check worked and how long it took. An app setting called FAULT_MODE makes it fail in realistic ways:

FAULT_MODE What the self-test does What you’ll see in the logs
off (default) Normal check Fast 200 responses
errors Searches an index that doesn’t exist Azure AI Search “index not found” errors, 500 responses
slow Waits 8 seconds first Slow 200 responses
ai Asks for an embedding model that doesn’t exist Azure OpenAI “deployment does not exist” errors, 500 responses

Three details keep it safe:

  • Only the self-test is affected. Signed-in users of the chat page never see the fault.
  • It is excluded from sign-in, like a health check, so monitoring can call it. Everything else still needs a signed-in user.
  • It is rate-limited to one call every two seconds, so an open endpoint can’t run up an Azure OpenAI bill.
Terminal: /api/selftest returns status ok with HTTP 200; a second call straight away returns 429 Too many self-tests; /api/me without sign-in returns 401
The self-test answers without sign-in, refuses a second call within two seconds, and the rest of the app still needs sign-in.

Step 8: Run a fault drill

tests/fault_drill.py does the whole test for you:

  1. Sets FAULT_MODE on the Container App (this starts a new revision).
  2. Waits until the self-test shows the fault.
  3. Calls the self-test about every 10 seconds, so there is real traffic in the logs.
  4. Waits for Azure Monitor to fire the alert and for the Logic App to run. This run sends a real email.
  5. Prints the alert and the incident note.
  6. Always sets FAULT_MODE back to off, even if something goes wrong.

Get the two values it needs, then run it:

export MSYS_NO_PATHCONV=1   # Git Bash on Windows only
az extension add -n containerapp --upgrade -y
WF=$(az resource show -g rg-incident-assistant -n la-incident-assistant \
  --resource-type Microsoft.Logic/workflows --query id -o tsv)
APP=https://$(az containerapp show -g rg-policy-assistant-demo -n ca-policy-assistant \
  --query properties.configuration.ingress.fqdn -o tsv)

python tests/fault_drill.py --mode errors --app-url "$APP" \
  --app-rg rg-policy-assistant-demo --app-name ca-policy-assistant --workflow-id "$WF"

The script only uses Python’s standard library, and your Azure CLI sign-in needs permission to update the Container App and read the Logic App (Owner on the subscription covers both).

Here is the errors drill. The fault went live at 21:03, the alert fired about a minute later, and the note named the exact error from Azure AI Search:

Terminal: the errors drill, with 7 failed self-tests, the Logic App run Succeeded, and a note whose likely cause is the ResourceNotFoundError: the index policies-missing was not found
The errors drill. The likely cause quotes the real error, the impact says it is synthetic traffic, and FAULT_MODE goes back to off at the end.

And the ai drill, where the app’s embedding model “disappears”:

Terminal: the ai drill, with 19 failed self-tests and a note whose likely cause is openai.NotFoundError: the API deployment for this resource does not exist
The ai drill. Same alert rule, a completely different cause, and the note finds it.

That is the email at the top of this post. --mode slow works the same way and fires the “slow responses” alert instead.

Two things to know before you run several drills:

  • An alert rule won’t fire again while its alert is still active. Azure Monitor resolves it automatically once the logs look normal again, which took about 20 minutes in my tests. Run the next drill on the same rule after that.
  • Leave about 20 minutes between drills. The note is written from the last 15 minutes of logs, so a drill straight after another one also contains the first drill’s errors. The note handles this (see below), but separate drills are easier to read.

Step 9: When the alert clears

When Azure Monitor resolves the alert, it calls the Logic App again. Instead of running the investigation a second time, the Logic App sends one short email and stops, with no log queries and no AI call:

A short email: Policy Assistant: requests failing (Sev1) is resolved; nothing to do unless it fires again
The resolved notice. The note for the original alert is in the earlier email.

You can see every run in the Azure portal: open the Logic App la-incident-assistant and select the Run history tab on its overview page.

Azure portal: the la-incident-assistant Logic App overview, 1 trigger and 18 actions, 24 successful runs in the last 24 hours, and the run history list
The Logic App in the portal. Every alert, test and resolved notice is a run.

Click a run to see the workflow as a diagram, with a green tick and a duration on every step that ran. This is the ai drill’s run: the three log queries ran side by side, Ask OpenAI took 2 seconds, and Fallback note was skipped because the AI answered.

The run diagram: When an alert fires, Acknowledge, Alert, Is resolved, Window, then Errors, Platform events and Requests in parallel, Evidence, Ask OpenAI, Note, Incident note, Email html and Send unless dry run, all with green ticks; Fallback note skipped
One incident from start to finish: about 3.5 seconds in total.

Click any step to see exactly what went in and what came out. This is the most useful view when a note looks wrong. The Evidence step shows everything the model was given, starting with the alert and its description:

The run diagram with the Evidence step selected; the details pane shows its inputs, starting with the alert: condition Fired, the rule description, the fired time and the rule name
The Evidence step’s inputs: the alert and its description, followed by the three query results.

Here is a summary of my runs from one round of drills:

Table of Logic App runs: fired alerts produce an AI note and send an email, resolved alerts send a short resolved email with no AI, and the post-deploy tests are dry runs
Fired alerts get an AI note and an email; resolved alerts get a short email; post-deploy tests are dry runs.

How the note stays honest

A model given a pile of logs will happily blame the most dramatic line in them. Most of the work in this project went into making sure the note is about the right thing. These are the parts that do it, all in workflow/definition.json:

  • The real error text, not a summary of it. Python apps that log with logger.exception("selftest_failed") store “selftest_failed” as the message, and the real error (“The index ‘policies-missing’ … was not found”) only appears in the last line of the stack trace. The exceptions query pulls out that last line, so the model can quote it.
  • Facts are worked out in the query, not left to the model. Each request and exception row carries its first and last time and a label: “still happening when this alert fired” or “none in the 3 minutes before this alert fired”. A small model is bad at comparing timestamps and good at reading a label.
  • Each alert rule says what it measures. The rule’s description (“It is about slow responses, not failures”) travels with the alert, so the note answers the question that alert is asking.
  • Synthetic traffic is called synthetic. The prompt knows /api/selftest is monitoring traffic, so the impact line never claims real users are affected when they aren’t.
  • A fixed answer shape. The model runs at temperature 0 and must return JSON with exactly the seven fields, so the email always has the same layout.
  • A fallback. If Azure OpenAI is down or times out, you still get an email with the raw evidence and confidence “low”.
  • No actions. The prompt says it only describes the incident, and the tests make sure the Logic App can only read logs, call the model and send email.

Watching your own app

The assistant isn’t tied to the Policy Assistant. To point it at another app:

  1. The app must send telemetry to a workspace-based Application Insights, so the AppRequests and AppExceptions tables exist in Log Analytics.
  2. Set watched_workspace_id and watched_app_name in TF_VARS_JSON, and run bootstrap.sh with WATCHED_RG set to that app’s resource group.
  3. If the app is not on Azure Container Apps, the platform events query finds no ContainerAppSystemLogs_CL table. The note is still written from the other two queries, but you can change that query in workflow/definition.json to whatever your platform logs.
  4. The prompt mentions /api/selftest as synthetic traffic. Change it to your own health or test endpoint.
  5. Adjust the alert thresholds in the alerts block of infra/main.tf (any 5xx in 5 minutes, and an average over 5 seconds).

Clean up

To remove everything this guide created:

az group delete -n rg-incident-assistant --yes
az group delete -n rg-incident-assistant-tfstate --yes
az ad app delete --id "<AZURE_CLIENT_ID>"

The role assignments the setup script made on the watched app’s resource group belong to the app registration, so they stop working when it is deleted; remove them under Access control (IAM) on that resource group to tidy up. The watched app itself is untouched.

Summary

You now have an assistant that turns an Azure Monitor alert into a plain-English incident note within a few minutes, quoting the real error and saying how sure it is, for a few pennies per incident and about $3 a month in alert rules. It runs with no keys, it can only read and report, and every change to it goes through a pull request with a plan review and a test after deploy.

The parts I’d reuse in any AI-on-call setup: give the model the real error line, do the time comparisons in the query, test with a false alarm as well as real failures, and keep a fallback so the email arrives even when the AI doesn’t.

The code is at github.com/Ositau/ai-incident-assistant. If you build it and get stuck, use the contact form and tell me which step.

Leave a Reply