You are currently viewing Build it yourself: a secure Azure OpenAI policy assistant with Terraform and Azure DevOps, step by step

Build it yourself: a secure Azure OpenAI policy assistant with Terraform and Azure DevOps, step by step

Summary: This guide takes you from an empty Azure subscription to a working AI assistant that answers questions about company policy, cites its sources and never shows HR-only documents to staff who aren’t in HR. Everything is deployed from my public GitHub repo by Terraform and two Azure DevOps pipelines, with no passwords or API keys in the pipeline. Allow about two hours the first time, most of it waiting for deployments.

I wrote this from my own deployment of the project. Every command, setting name and error message below is the one I used or saw, and I’ve checked them against the code in the repo. If something on your screen doesn’t match, please open an issue on GitHub and I’ll update the guide.

If you want the reasons behind the design rather than the steps, I’ve written those up separately in a five-part series. I link to the relevant part as we go.

What you’ll end up with

A chat page, behind a Microsoft sign-in, where staff ask policy questions and get an answer with the policy section it came from:

The Policy Assistant answering a question about gifts, with a citation to the gifts policy
The finished app. The answer is written only from the cited policy section.

Behind it:

  • Azure Container Apps runs the app, with Microsoft Entra ID sign-in switched on in front of it.
  • Azure AI Search holds ten fictional policy documents, split into sections. Each section is tagged with the Entra ID group allowed to read it.
  • Azure OpenAI (gpt-4o-mini for answers, text-embedding-3-small for search) runs in the EU data zone.
  • Application Insights records every question: who asked, which group they’re in, and which documents the answer used.
  • Azure DevOps has two pipelines. One builds the infrastructure (with a manual approval), the other tests and releases the app.
Architecture: the user signs in to Container Apps, which queries AI Search and Azure OpenAI and logs to Application Insights; two Azure DevOps pipelines deploy it
The whole system. Everything on this page is created by Terraform or the pipelines.

Before you start

What you need

  • An Azure subscription where you are Owner. The setup creates role assignments, which Contributor can’t do.
  • Permission to create app registrations and security groups in Entra ID. In most personal and test tenants your account already has this. In a company tenant you may need the Application Developer and Groups Administrator roles, or someone who has them to run step 4.
  • Azure OpenAI access in that subscription, with a little quota in Sweden Central for gpt-4o-mini and text-embedding-3-small. The project asks for 30,000 tokens per minute of each. You can check in the Azure AI Foundry portal under Quotas.
  • No other free-tier Azure AI Search service in the subscription. Azure allows one free search service per subscription.
  • An Azure DevOps organisation. If it’s brand new, Microsoft-hosted build agents may not be enabled yet. You’ll see “No hosted parallelism has been purchased or granted” on your first run, and you can request the free grant through this Microsoft form. It can take a couple of working days, so ask early.
  • A GitHub account, to fork the repo.

Tools on your machine

Tool Version I used Check with
Azure CLI 2.86 az version
Terraform 1.14 (1.9 or later works) terraform version
Git any recent git --version
Python 3.12 (only for running tests locally, optional) python --version

I ran everything from Git Bash on Windows. The commands are the same in any Bash shell, including WSL, macOS and Linux.

Names you’ll use

Most names are fixed in the code, so you don’t need to invent anything. Keep this table handy, because the pipeline files expect these exact names:

Thing Name
Azure DevOps service connection sc-policy-assistant
Variable group policy-assistant
Environment for infrastructure (with approval) policy-assistant-demo
Environment for app releases policy-assistant-demo-app
App resource group rg-policy-assistant-demo
Terraform state resource group rg-policy-assistant-tfstate
Container App ca-policy-assistant

Storage, Key Vault, registry, OpenAI and Search names get a random five-letter ending so they don’t clash with anyone else’s. Terraform prints them for you when they’re needed.

Step 1: Fork and clone the repo

Fork Ositau/azure-openai-policy-assistant to your own GitHub account. Your pipelines will run from your fork, so you can change things without asking me.

The GitHub repository page with the Fork button
Fork the repo first. Azure DevOps will read the pipeline files from your copy.

Then clone your fork and sign in to Azure:

git clone https://github.com/<your-github-name>/azure-openai-policy-assistant.git
cd azure-openai-policy-assistant
az login
az account set --subscription "<your subscription name or ID>"

A quick tour of what’s inside:

Folder What it holds
infra/bootstrap Terraform you run once from your machine: state storage, Entra ID groups, the sign-in app, the pipeline’s identity and its permissions
infra Terraform the pipeline runs: Azure OpenAI, AI Search, Container Apps, monitoring
pipelines The two Azure DevOps pipelines and their shared templates
app The FastAPI app and chat page, plus its Dockerfile
docs/policies The ten fictional policy documents
scripts ingest.py loads the policies into search; evaluate.py runs the test questions
eval/questions.json 22 test questions with the expected answers
tests Unit tests that run without Azure

Step 2: Register the Azure resource providers

The pipeline’s identity is only allowed into one resource group, so it can’t switch on Azure services for the whole subscription. You do that once, up front. Most of these are probably registered already, and running the command again does no harm:

for p in Microsoft.App Microsoft.CognitiveServices Microsoft.Search \
         Microsoft.OperationalInsights Microsoft.Insights Microsoft.ContainerRegistry \
         Microsoft.KeyVault Microsoft.Storage Microsoft.ManagedIdentity; do
  az provider register --namespace $p
done

You should see: no output, or a note that registration is in progress. Check one with az provider show -n Microsoft.App --query registrationState -o tsv, which should say Registered after a minute or two.

Step 3: Create the Azure DevOps project and start the service connection

  1. In Azure DevOps, create a new private project. (The code is public on GitHub, but the project holds your pipeline runs and approvals, so keep it private.)
  2. Go to Project settings → Service connections → New service connection → Azure Resource Manager.
  3. Choose:
  4. Identity type: App registration or managed identity (manual)
  5. Credential: Workload identity federation
  6. Environment: Azure Cloud
  7. Directory (tenant) ID: your tenant ID (az account show --query tenantId -o tsv)
  8. Service connection name: sc-policy-assistant
  9. Click Next. Azure DevOps saves a draft and shows two values: Issuer and Subject identifier.
Azure DevOps new service connection form with workload identity federation selected
Step 1 of the form: manual identity type, workload identity federation, the connection name and your tenant ID.

After Next, the issuer and subject appear. Once the connection is finished, the same two values are shown on its overview page, which is where I took this from:

The service connection overview showing the Issuer and Subject identifier, masked
The workload identity federation details. Copy both values exactly. The connection’s ID is shown under its name.

Leave that browser tab open. Back in your clone, create infra/bootstrap/terraform.tfvars and paste the two values in:

ado_wif_issuer  = "https://login.microsoftonline.com/<tenant-id>/v2.0"
ado_wif_subject = "/eid1/c/pub/t/..../sc/..../..."

This file is ignored by git, so it won’t end up in your fork. Copy the values exactly as shown, especially the subject: one wrong character and the sign-in fails later with a “no matching federated identity record” error.

“Workload identity federation” means Azure trusts short-lived tokens that Azure DevOps issues to your pipeline, so there’s no client secret to store or rotate. The bootstrap layer sets up that trust in the next step.

Step 4: Apply the bootstrap layer

This is the one part a person runs by hand, because it creates things a pipeline shouldn’t have the power to create: Entra ID groups, app registrations and permissions.

terraform -chdir=infra/bootstrap init
terraform -chdir=infra/bootstrap apply

Read the plan, type yes, and wait about three minutes. Part of that is a deliberate 60-second pause, because Azure takes a moment to apply new permissions before Terraform can write the sign-in secret to Key Vault.

What it creates:

  • A resource group and storage account for Terraform’s state, with storage keys switched off (Entra ID sign-in only).
  • The empty app resource group, plus a Key Vault and a container registry in it.
  • Two Entra ID security groups: Policy Assistant – Staff and Policy Assistant – HR. You’re added to Staff.
  • The sign-in app registration for the web app. Its secret goes straight into Key Vault.
  • The pipeline’s identity, with the federated trust from step 3.
  • The pipeline’s permissions: Contributor on the app resource group only, permission to hand out six named roles there and no others, and access to the state container. (Part two explains the six-roles limit.)

You should see: Apply complete! and a list of outputs. Print the two you need next:

terraform -chdir=infra/bootstrap output service_connection
terraform -chdir=infra/bootstrap output variable_group
Terminal output of the bootstrap layer's service_connection and variable_group outputs, with IDs masked
The bootstrap outputs. None of these are secrets, but I’ve masked the IDs from my tenant.

You can see the two new groups in the Azure portal under Microsoft Entra ID → Groups (search for “Policy Assistant”):

Entra admin centre listing the Policy Assistant Staff and HR security groups
The two security groups. Which one you’re in decides which documents you can see.

Step 5: Finish the service connection

Go back to the service connection tab from step 3 and fill in the rest from the service_connection output:

  • Scope level: Subscription
  • Subscription ID and Subscription name: your subscription
  • Application (client) ID: the client_id value
  • Directory (tenant) ID: already filled in

Click Verify and save. Verification works now because the trust from step 4 exists.

Once it’s saved, open the connection. Its ID is shown under the name, and also in the browser’s address bar after resourceId=. Copy it: the pipelines need it in the next step.

Step 6: Create the variable group

Go to Pipelines → Library → + Variable group and name it policy-assistant. Add every key from the variable_group output, with exactly the same names, plus two more:

Variable Value
acrName from the output
appResourceGroup from the output
armClientId from the output
armSubscriptionId from the output
armTenantId from the output
demoUserObjectId from the output
groupHrId from the output
groupStaffId from the output
keyVaultName from the output
tfStateAccount from the output
tfStateContainer from the output
tfStateRg from the output
webClientId from the output
serviceConnectionName sc-policy-assistant
serviceConnectionId the ID you copied in step 5

That’s 15 variables. None of them are secrets, so leave the lock icon off. Locking only hides a value from the logs, which makes troubleshooting harder for no benefit here.

Azure DevOps variable group policy-assistant with 15 variables, values masked
The finished variable group. The names must match exactly; the pipelines look them up by name.

The names are case-sensitive. armClientId and ArmClientId are different variables, and a typo here shows up later as an empty value in a Terraform error, which is confusing to trace back.

Step 7: Create the two environments

Go to Pipelines → Environments → New environment and create two, both with Resource: None:

  1. policy-assistant-demo. Open it, then ⋮ → Approvals and checks → + → Approvals, and add yourself as the approver. This is the pause before any infrastructure change. I also added a one-line instruction for approvers, “Review the Terraform plan in the Plan stage log before approving”, which shows up on the approval prompt.
  2. policy-assistant-demo-app. No checks. App releases are protected by the test questions instead (step 10).
Azure DevOps environment Approvals and checks page showing an approval check
The approval check on the infrastructure environment. Nothing is applied until someone on this list approves the plan.

Step 8: Create the two pipelines

Go to Pipelines → New pipeline → GitHub. The first time, Azure DevOps asks to install its GitHub app; allow it only for your fork. Then:

  1. Pick your fork.
  2. Choose Existing Azure Pipelines YAML file, branch main, path /pipelines/infra.yml, and click Continue.
  3. On the review page, open the Run button’s drop-down arrow and choose Save instead of running.
  4. Repeat for /pipelines/app.yml.
Azure DevOps Select an existing YAML file dialog with /pipelines/infra.yml selected
Choose the existing YAML file. Do this twice, once for each pipeline.

Both pipelines get named after the repo by default. Rename them to something clearer (I used policy-assistant-infra and policy-assistant-app) under ⋮ → Rename/move on the pipeline page.

Step 9: Run the infrastructure pipeline

Run policy-assistant-infra. The first time, the run stops with “This pipeline needs permission to access resources before this run can continue”. Click View, then Permit for each item: the variable group, the service connection and the environment. Azure DevOps asks once per pipeline, by design, so a new pipeline can’t quietly use a connection it wasn’t given.

The run has three stages:

  1. Validate checks formatting, validates both Terraform layers and runs TFLint.
  2. Plan builds a first container image (the Container App can’t be created without one), then runs terraform plan and saves the plan file. The end of the plan step’s log lists every change.
  3. Apply waits for your approval.

Open the Plan stage log and read the plan before you approve. On a fresh deployment you should see 22 resources to add, and nothing to change or destroy:

Terraform plan output listing 22 resources to add, 0 to change, 0 to destroy
My first plan. If you see anything to change or destroy on a fresh setup, stop and check.

Then approve from the banner at the top of the run. The Apply stage applies exactly the plan file you reviewed, not a fresh plan, so what runs is what you approved. Mine took just under four minutes.

Azure DevOps infrastructure run with Validate, Plan and Apply all succeeded
A finished infrastructure run.

At the end of the Apply log are two lines you need:

App URL: https://ca-policy-assistant.<something>.swedencentral.azurecontainerapps.io
Sign-in redirect domain: <something>.swedencentral.azurecontainerapps.io

Copy the sign-in redirect domain.

Step 10: Tell the sign-in app its address

The sign-in app registration was created in step 4, before the app had an address. Entra ID only sends users back to addresses it knows, so add the domain to your terraform.tfvars:

redirect_domain = "<something>.swedencentral.azurecontainerapps.io"

and apply the bootstrap layer again:

terraform -chdir=infra/bootstrap apply

You should see: 1 changed, which is the sign-in app getting its redirect address. Keeping the value in terraform.tfvars rather than passing it with -var means later bootstrap applies won’t quietly remove it again.

This is the one chicken-and-egg step in the whole build. You only do it once.

Step 11: Run the app pipeline

Run policy-assistant-app and permit its resources the same way as before. It has four stages:

  1. Test runs the unit tests. They don’t need Azure.
  2. Build builds the image in your container registry.
  3. Evaluate loads the ten policies into AI Search, then asks the 22 test questions against the real services. If any answer is wrong, or any HR-only document is even retrieved for a Staff user, this stage fails and the release never happens. (Part four covers how the test works.)
  4. Release points the Container App at the new image.
Evaluation log in Azure DevOps showing 22 of 22 questions passed and no HR leaks
The Evaluate stage log. All 22 pass, with no HR documents retrieved for Staff.
Azure DevOps app pipeline run with Test, Build, Evaluate and Release succeeded
A finished app run, in under five minutes.

From now on this pipeline runs by itself whenever you push changes to the app, policies, scripts or tests. The infrastructure pipeline runs when anything in infra/ changes, and always stops for your approval.

Step 12: Try it

Open the app URL from step 9. You’ll be sent to the Microsoft sign-in page. The first time, you may be asked to consent to the app reading your basic profile; that’s the only permission it asks for.

Try a few questions as a Staff member:

  • Can I accept a £60 gift from a supplier? (answered from the gifts policy)
  • What is the hotel limit in London? (answered from the expenses policy)
  • What is the salary range for Grade 4? (refused: that’s in the HR-only pay policy, so the search never returns it to you)

If the app starts slowly, that’s expected: it scales to zero when nobody is using it, and the first request after a quiet spell takes a few seconds to start a copy.

See the HR view

To see what HR staff see, add yourself to the HR group:

terraform -chdir=infra/bootstrap apply -var 'demo_user_groups=["staff","hr"]'

Then sign out by going to https://<your app URL>/.auth/logout, and sign back in. Group membership is read when you sign in, so the change won’t show until you do. Now the Grade 4 question gets an answer:

The same pay question asked as Staff (refused) and as HR (answered)
Same question, different groups. The HR document is filtered out of the search for Staff, so the model never sees it.

Run the same command with '["staff"]' to switch back. (Part three explains how the filtering works.)

Step 13: Check the audit log

Every question is logged. In the Azure portal, open the Log Analytics workspace in rg-policy-assistant-demo (its name starts with log-policy-assistant-), choose Logs, switch to KQL mode and run:

AppTraces
| where Message == "policy_question"
| project TimeGenerated,
          User = tostring(Properties.user),
          Groups = tostring(Properties.user_groups),
          Question = tostring(Properties.question),
          Cited = tostring(Properties.cited_docs)
| order by TimeGenerated desc
Log Analytics query results showing user, group, question and cited documents for each question
The audit trail. Logs can take a few minutes to appear after you ask a question.

Each entry also records the retrieved documents, the token counts and how long the answer took.

Your resource group at the end

Azure portal showing the resources in rg-policy-assistant-demo
The app resource group after both pipelines have run: 11 resources. Azure OpenAI and AI Search are further down the list. I’ve blurred the random name endings and the subscription ID.

When things go wrong

These are the errors I hit, or that you’re most likely to hit, with the fix for each.

“There is no explicit reference to service connection … from current stage” A stage asked for a sign-in token without a task in that stage naming the service connection. The templates in the repo already handle this by running Terraform inside an AzureCLI@2 task. If you change the pipelines and see this, that’s the cause. (Part one.)

“The given role assignment condition is invalid” during the bootstrap apply The role list in the condition must be plain role IDs, not full role paths. The repo already passes plain IDs. You’d only see this if you change how the role list is built. (Part two.)

“No matching federated identity record found” when verifying the service connection, or in a pipeline The issuer or subject in terraform.tfvars doesn’t exactly match the service connection. Copy them again from the connection, re-apply the bootstrap, then verify again. Recreating the service connection gives it a new subject, so you’d need to update and re-apply after that too.

“No hosted parallelism has been purchased or granted” New Azure DevOps organisations need to request the free Microsoft-hosted agent grant. See Before you start.

The Apply stage fails creating the AI Search service You already have a free-tier search service in this subscription. Delete the other one, or change sku = "free" to "basic" in infra/main.tf (Basic is a paid tier).

The Apply stage fails deploying a model, with a quota error You don’t have enough gpt-4o-mini or embedding quota in Sweden Central for the Data Zone deployment type. Request more in the Foundry portal, or lower capacity in infra/variables.tf.

Sign-in fails with “The redirect URI … does not match” Step 10 hasn’t been done, or the domain was copied with https:// or the ca-policy-assistant. part at the front. The value should be only the part after the app name.

A Terraform error mentions an empty value, such as resource_group_name being empty A variable in the group is misspelled, so the pipeline passes nothing. Compare the names with the table in step 6.

The app works but every HR question is refused, even after adding yourself to HR Sign out at /.auth/logout and back in. The groups come from your sign-in token, which was issued before the change.

Running costs

While idle, mine costs about 15p a day, almost all of it the container registry (Basic tier). AI Search is on the free tier, the Container App scales to zero, Azure OpenAI charges per token (a full 22-question evaluation costs well under a penny), and Log Analytics has a 0.5 GB daily cap.

The sign-in secret expires after 90 days

The sign-in app’s secret is created with a 90-day lifetime. Before it expires, create a new one and restart the app so it reads the new value from Key Vault:

terraform -chdir=infra/bootstrap apply -replace=azuread_application_password.web
az containerapp revision restart -g rg-policy-assistant-demo -n ca-policy-assistant \
  --revision $(az containerapp show -g rg-policy-assistant-demo -n ca-policy-assistant --query properties.latestRevisionName -o tsv)

You can see the expiry date in Entra ID, under the Policy Assistant (demo) app registration, in Certificates & secrets.

Tearing it down

When you’re done, delete the app resource group first, then destroy the bootstrap layer:

az group delete -n rg-policy-assistant-demo --yes
terraform -chdir=infra/bootstrap destroy

Deleting the resource group removes the app, OpenAI, Search, the registry and Key Vault. The bootstrap destroy then removes the state storage, the Entra ID groups and both app registrations. Azure keeps deleted OpenAI accounts for 48 hours, and Key Vaults for 7 days, in case you want them back. The Key Vault is harmless to leave, since its name is unique. To remove yours straight away, purge it:

az cognitiveservices account list-deleted -o table
az cognitiveservices account purge -g rg-policy-assistant-demo -l swedencentral -n <oai-policy-assistant-xxxxx>

Finally, delete the two pipelines, the service connection, the variable group and the two environments in Azure DevOps.

I haven’t torn mine down yet, because I’m still using it for demos. This is the order I’ll use, and I’ll update this section if anything in it needs changing.

Where to go from here

The full code is on GitHub: Ositau/azure-openai-policy-assistant. The five-part series explains why it’s built this way:

  1. Fixing “There is no explicit reference to service connection” when Terraform uses OIDC in Azure DevOps
  2. Let your Azure DevOps pipeline create role assignments, but only for the roles you choose
  3. Secure RAG on Azure OpenAI: how to stop your AI assistant leaking documents people shouldn’t see
  4. Test your AI assistant before every release: a simple evaluation gate in Azure DevOps
  5. From an empty subscription to a live Azure OpenAI app, with no secrets in the pipeline

If you build it and get stuck, open an issue on the repo and tell me which step and what you saw. That’s the fastest way for me to fix the guide for the next person.

Leave a Reply