---
title: Deploy an enterprise reference architecture
summary: Deploy a production-shaped Azure AI Gateway environment from modular Bicep or Terraform, with a keyless Foundry backend, models and MCP tools behind RBAC, a key per app, layered policies, and monitoring. Then promote it from dev to prod with a GitHub Actions workflow that signs in with OpenID Connect and smoke-tests every deployment.
category: production
level: Advanced
duration: 60
tracks: [iac, terraform]
order: 21
illustration: diagrams/enterprise-reference.svg
tags: [Bicep, Terraform, modules, reference architecture, managed identity, RBAC, policy layering, environments, GitHub Actions, OpenID Connect, smoke test]
objectives:
  - Explain the identity, policy, observability, and naming decisions behind a production AI Gateway deployment
  - Deploy a modular, subscription-scope Bicep template or Terraform configuration, with separate settings files for dev and prod
  - Layer gateway-wide baseline policies, applied by a merge-safe script, on top of model policies declared in code
  - Automate preview, deployment, baselines, and a smoke test in GitHub Actions with OpenID Connect
  - Verify the model and MCP tool paths end to end, and clean up every resource
prereqs:
  - 09-gateway-baselines
  - 13-monitoring
  - 12-backend-identity
---

# Deploy an enterprise reference architecture

You've built every piece by hand in earlier labs: a keyless Foundry backend, aliases, MCP servers, per-caller
limits, a gateway-wide baseline, and monitoring. Now the platform team wants the whole setup as code. Dev and
prod should differ only in their parameters, every change should go through a pull request, and a pipeline
should deploy it without a stored secret. In this lab you deploy a modular reference architecture, apply the
baseline, prove it works with a smoke test, and wire it all into GitHub Actions.

![GitHub Actions deploys two resource groups: the gateway with its alias, model provider, MCP server, keys, and monitoring, and a Foundry account with key authentication disabled](../assets/diagrams/enterprise-reference.svg "One pipeline signs in with OpenID Connect, previews, deploys, applies the gateway baseline, and runs a smoke test. The gateway reaches Foundry with its managed identity.")

<!-- widget: policy-layers -->

## Before you begin

<!-- setup: tools sign-in extension providers clone -->

- Complete [Set gateway-wide policy baselines](../09-gateway-baselines/README.md),
  [Monitor usage, cost, and traces](../13-monitoring/README.md), and
  [Call backends with managed identities](../12-backend-identity/README.md). This lab builds on what you learned
  there, not on the resources you created: it deploys a new, separate environment.
- For the Terraform track: Terraform 1.9 or later, as in
  [Deploy a lab with Terraform](../SETUP.md#deploy-a-lab-with-terraform).
- The Azure CLI installs Bicep the first time you deploy. The telemetry script and the smoke test read the gateway
  with the `aigateway` extension. Its `az aigateway policy` commands take each setting as a flag, not a policy array,
  so to apply the whole baseline from a file, the baseline script calls the management API with `az rest`.
- **Owner**, or **Contributor** plus **Role Based Access Control Administrator**, on the subscription. The
  template creates two resource groups and several role assignments.
- Quota for `gpt-5-mini` with the `GlobalStandard` SKU in the region you deploy to. The dev environment uses
  50 capacity units (50,000 tokens per minute).
- For [Automate deployments with GitHub Actions](#automate-deployments-with-github-actions): a GitHub
  repository where you can create environments and variables, the [GitHub CLI](https://cli.github.com/) signed
  in with `gh auth login`, and permission to create an app registration in Microsoft Entra ID.

Run every command from this lab's folder, `~/aigateway/labs/21-enterprise-reference`, so the `infra/` paths
resolve. The Terraform track moves into `terraform/` to deploy, then back. Set these variables once:

```bash title="Bash"
# Set the region and the deployment name that the template and the rest of the lab use
export LOCATION="eastus2"            # deployment metadata, the Foundry account, and the monitoring resources
export ENV_NAME="aigw-dev"           # deployment name, the same as environmentName in main.bicepparam
echo "📝 Deployment $ENV_NAME in $LOCATION"

# Read your own object ID: main.bicepparam, or TF_VAR_principal_id on the Terraform track, gives you data-plane
# access to the Foundry account, the alias, and the MCP server
export AZURE_PRINCIPAL_ID="$(az ad signed-in-user show --query id -o tsv)"
echo "👤 Your principal ID: $AZURE_PRINCIPAL_ID"

# Show the subscription that you deploy to, so that you can check it before you go on
echo "🆔 Subscription that you deploy to:"
az account show --query "{subscription:name, id:id}" -o table
```

```powershell title="PowerShell"
# Set the region and the deployment name that the template and the rest of the lab use
$env:LOCATION = "eastus2"            # deployment metadata, the Foundry account, and the monitoring resources
$env:ENV_NAME = "aigw-dev"           # deployment name, the same as environmentName in main.bicepparam
Write-Host "📝 Deployment $env:ENV_NAME in $env:LOCATION"

# Read your own object ID: main.bicepparam, or TF_VAR_principal_id on the Terraform track, gives you data-plane
# access to the Foundry account, the alias, and the MCP server
$env:AZURE_PRINCIPAL_ID = az ad signed-in-user show --query id -o tsv
Write-Host "👤 Your principal ID: $env:AZURE_PRINCIPAL_ID"

# Show the subscription that you deploy to, so that you can check it before you go on
Write-Host "🆔 Subscription that you deploy to:"
az account show --query "{subscription:name, id:id}" -o table
```

## How it works

One subscription-scope template, `infra/main.bicep`, creates two resource groups and composes small modules.
Each module owns one concern, so the people who own that concern can review and change it on their own, and no
module outputs a secret. Parameter files hold everything that differs between environments. The Terraform track
has the same shape: a root module, `terraform/main.tf`, calls one module in `terraform/modules/` per Bicep module,
and `dev.tfvars` and `prod.tfvars` replace the parameter files.

Gateway-wide policies aren't in Bicep or Terraform. They live on the gateway's `default` workspace, and declaring
that workspace in a template would replace it. Instead, a script merges them in after each deployment, as in
[Set gateway-wide policy baselines](../09-gateway-baselines/README.md).

| File | Resource group | Deploys |
|---|---|---|
| `modules/monitoring.bicep` | `…-gateway` | Log Analytics workspace and a workspace-based Application Insights component, `<gateway>-insights`, with OTLP ingestion on |
| `modules/foundry.bicep` | `…-foundrymodels` | Foundry account with key authentication turned off, and the `gpt-5-mini` deployment |
| `modules/gateway.bicep` | `…-gateway` | The AI Gateway (`Microsoft.ApiManagement/aigateways`, system-assigned identity) and **Foundry User** for the identity on the Foundry account |
| `modules/models.bicep` | `…-gateway` | A Foundry model provider that authenticates with the managed identity, the backend model with a token limit and content safety, the alias `chat`, and **AI Gateway Models User** on the alias |
| `modules/tools.bicep` | `…-gateway` | The Microsoft Learn MCP server `learn`, and **AI Gateway Tools User** on it |
| `modules/keys.bicep` | `…-gateway` | One runtime API key per app: `web-chat` and `batch-jobs` |
| `modules/telemetry.bicep` | `…-gateway` | The gateway's OpenTelemetry exporter to the component, with the recommended token claims. `scripts/connect-telemetry.sh` deploys it |
| `scripts/connect-telemetry.sh` | Not applicable | Waits for the component's OTLP endpoints, grants the gateway's identity **Monitoring Metrics Publisher** on its Data Collection Rule, then deploys `modules/telemetry.bicep` |
| `scripts/apply-baselines.sh` | Not applicable | Gateway scope **Request rate limit** and **Cost limit** from `baselines.json` |

On the Terraform track, each module is a folder with the same name, such as `terraform/modules/gateway`. The
`telemetry` module also does what `connect-telemetry.sh` does, so `terraform apply` connects telemetry in the same
run. Both tracks apply the baseline with `scripts/apply-baselines.sh`.

## Make the architecture decisions

Each decision below is already built into the templates. In your own environment, change the parameters first,
and change the shape only when your organization needs something different.

### Identity: no secrets between services or in the pipeline

Each trust boundary uses its own mechanism, and none of them needs a stored secret:

| Boundary | Mechanism | Where |
|---|---|---|
| Gateway to Foundry | The gateway's system-assigned identity has **Foundry User** on the account. The account sets `disableLocalAuth: true`, so Foundry keys don't work at all. | `gateway.bicep`, `foundry.bicep` |
| Apps to gateway | One runtime API key per app, so every app gets its own policy counters, its own row in **Monitoring**, and its own rotation. Or keyless Microsoft Entra calls through **AI Gateway Models User** on the alias and **AI Gateway Tools User** on the MCP server, granted to groups. | `keys.bicep`, `models.bicep`, `tools.bicep` |
| Pipeline to Azure | An OpenID Connect federated credential. GitHub exchanges a short-lived token for an Azure token, so there's no client secret to rotate or leak. | `deploy-workflow.yml` |

Roles are granted at the narrowest scope that works: the alias instead of the whole gateway, and one MCP server
instead of every tool. Templates output key **names** only, never key values. The smoke test reads a key with
`az aigateway api-key list-secrets` when it needs one.

### Policies: a gateway floor plus model limits

| Layer | Declared in | Policies | Counted per |
|---|---|---|---|
| Gateway | `baselines.json`, applied by `scripts/apply-baselines.sh` | **Request rate limit**: 120 calls per 60 seconds, on models and MCP servers. **Cost limit**: $20 per day, one budget across all models. | Caller identity |
| Model | `models.bicep` | **Token rate limit**: 20,000 tokens per minute in dev. **Content safety**: **Balanced** (`Medium`) for all four categories. | Caller identity |

The gateway evaluates every applicable policy before it forwards a request, and any one of them can block it.
The platform team owns the gateway floor, and app teams tune the model layer through parameters. Blocked calls
get `429` from a rate limit, `403` with `LlmCostQuotaExceeded` from the cost limit, and `400` from content
safety.

The baseline script reads the workspace's `policies` array, updates policies of the same type in place, appends
missing ones, and writes the array back with `PATCH`. Updating in place keeps a cost limit's `id`, its
portal-only overrides, and the spend it has already counted.

> [!NOTE]
> The portal writes `"scope": "workspace"` on Gateway scope rate and cost limits, so `baselines.json` does too.
> If the API rejects a field, create the policy once in the portal at **Gateway** scope, read the Gateway scope
> policies with `az aigateway policy list -g "$RG" --gateway-name "$GATEWAY"`, and copy that shape into
> `baselines.json`.

### Observability: the destination in Bicep, the exporter after it

`monitoring.bicep` creates the Log Analytics workspace and the Application Insights component, with retention
set per environment, and turns on OTLP ingestion. A few minutes after the deployment, Azure creates the component's
OTLP endpoints and a Data Collection Rule in a managed resource group. The gateway's OpenTelemetry exporter, in
`telemetry.bicep`, needs those endpoints, and the gateway's managed identity needs **Monitoring Metrics Publisher**
on the rule before the exporter is created. Bicep can't wait for the endpoints, and it can't assign the role,
because the managed resource group has a deny assignment that blocks deployments. So `scripts/connect-telemetry.sh`
runs after each deployment: it waits for the endpoints, assigns the role with the Azure CLI, then deploys
`telemetry.bicep`. The result matches the portal's **Configure telemetry** wizard: metrics, logs, and traces, with
the recommended token claims.

Terraform can wait, so on the Terraform track the `telemetry` module does the same work inside `terraform apply`.
It runs the same wait with the Azure CLI, reads the endpoints once and keeps them in the state, assigns the role,
then creates the exporter.

The exporter sends to the component's OTLP endpoints and doesn't link to the Application Insights resource, yet
the **Monitoring** dashboard still reads its data. The other exporter type, `ApplicationInsights`, which the
reference sample uses, is legacy: the portal flags it because it no longer activates the OTLP signals the dashboard
needs. An exporter's type can't change, so the script replaces an `ApplicationInsights` exporter that an earlier
deployment created.

### Naming, tags, and resource groups

- **Deterministic names.** A resource token, the first eight characters of
  `uniqueString(subscription, environmentName, location)`, goes into every name. Deploying again updates the
  same resources instead of creating new ones.
- **Two resource groups.** `rg-<env>-<token>-gateway` holds the gateway and its monitoring, and
  `rg-<env>-<token>-foundrymodels` holds model capacity. You can secure, scale, and delete them separately, and
  only the gateway's identity needs access to Foundry.
- **A unique gateway name.** The gateway is `aigw-<token>`. Its runtime URL starts with the name's first 10
  characters and a hash, like `https://aigw-abcde-k3v7qz2m9xw4p.eastus2-01.ai.gateway.azure.com`. Set `aiGatewayName` to choose your own: up to 24
  letters, digits, and hyphens, starting with a letter.
- **Tags.** Resource groups and top-level resources get `environment` and `workload: ai-gateway`, plus the
  `tags` from the parameter file, such as `costCenter`.
- **Regions.** `aiGatewayLocation` defaults to `eastus2`. Set it to any region where AI Gateway is available, as in
  [Find the available regions](../SETUP.md#find-the-available-regions). The other resources follow the deployment's
  `--location`, so pick one where the model is available.
- **On the Terraform track**, the token is six characters of a hash of the subscription, the environment name,
  and the location. The resource groups are `rg-<env>-gateway` and `rg-<env>-foundrymodels`, the environment tag
  is `environment-name`, and the gateway's region, `ai_gateway_location`, defaults to `location`, so one region
  drives every resource.

### Environments: one template, two parameter files

| Setting | `main.bicepparam` (dev) | `prod.bicepparam` (prod) |
|---|---|---|
| `environmentName` | `aigw-dev` | `aigw-prod` |
| Developer access (`principalId`) | You, from `AZURE_PRINCIPAL_ID` | None |
| Model capacity (`modelCapacity`) | 50 | 200 |
| Tokens per minute per caller (`tokensPerMinutePerCaller`) | 20,000 | 50,000 |
| Microsoft Entra access (`modelUsers`, `toolUsers`) | Your user only | Groups you add |
| Log retention (`logRetentionInDays`) | 30 days | 90 days |
| `costCenter` tag | `dev` | `platform` |

The Terraform track's `dev.tfvars` and `prod.tfvars` set the same values, with the variable names in snake case,
such as `model_capacity` and `tokens_per_minute_per_caller`. Their environment names are `aigw-dev-tf` and
`aigw-prod-tf`, so a Terraform deployment never touches a Bicep one.

> [!TIP]
> Put prod in its own subscription so quotas, role assignments, and Azure Policy stay isolated from dev. The
> template is subscription-scoped, so it works unchanged. Use a separate deployment identity for each
> subscription.

### Delivery: GitHub Actions with OpenID Connect

The workflow installs the `aigateway` extension, previews every change with `what-if`, deploys, connects
telemetry, applies the baseline, and runs the smoke test. A `prod` GitHub environment with required reviewers gates production, and a
concurrency group per environment stops two runs from deploying to the same environment at once. The deployment
identity needs **Contributor** and **Role Based Access Control Administrator** on the subscription, because the
template creates role assignments. To narrow that, you can add a condition that only lets it assign the roles the
template needs, as described in
[Delegate Azure access management to others](https://learn.microsoft.com/azure/role-based-access-control/delegate-role-assignments-overview).
With Terraform, the same workflow runs `terraform plan` and `terraform apply` instead of `what-if` and the
deployment, and keeps the Terraform state in an Azure Storage container that every run shares.

## Review the templates

<!-- track: iac | Bicep -->

`main.bicep` wires the modules together and passes outputs from one to the next, so Bicep deploys them in the
right order: monitoring and Foundry first, then the gateway, then models, tools, and keys.

<!-- include: infra/main.bicep -->

On GitHub, open [infra/main.bicep](infra/main.bicep).

`gateway.bicep` is the only module that declares the gateway itself. The others reference it as `existing` and
only add child resources to it.

<!-- include: infra/modules/gateway.bicep -->

On GitHub, open [infra/modules/gateway.bicep](infra/modules/gateway.bicep).

> [!WARNING]
> Each deployment sends a `PUT` for the gateway with exactly the properties in `gateway.bicep`. If you change
> gateway settings outside Bicep, add them to this module. Otherwise, the next deployment can reset them.
> Outbound virtual network integration and **Public network access** are the exceptions: a deployment that
> doesn't set them keeps the gateway's current values. `gateway.bicep` accepts the integration subnet as
> `backendSubnetId`, but `main.bicep` doesn't pass it. To
> use it, add a parameter to `main.bicep`, or set it in the portal under **Networking** or with
> `az aigateway network update --subnet`. See
> [Lock down backend traffic with private networking](../18-private-networking/README.md).

`models.bicep` declares the model-level policies right on the backend model, so they're versioned with it:

<!-- include: infra/modules/models.bicep -->

On GitHub, open [infra/modules/models.bicep](infra/modules/models.bicep).

The gateway floor is a plain policy file that goes through code review like any template:

<!-- include: infra/baselines.json -->

On GitHub, open [infra/baselines.json](infra/baselines.json).

The other files are short. Open them on GitHub:
[monitoring.bicep](infra/modules/monitoring.bicep), [foundry.bicep](infra/modules/foundry.bicep),
[foundry-user-role.bicep](infra/modules/foundry-user-role.bicep), [tools.bicep](infra/modules/tools.bicep),
[keys.bicep](infra/modules/keys.bicep), [telemetry.bicep](infra/modules/telemetry.bicep),
[types.bicep](infra/modules/types.bicep), [main.bicepparam](infra/main.bicepparam), and
[prod.bicepparam](infra/prod.bicepparam).

<!-- track: terraform | Terraform -->

`terraform/main.tf` is the root module. It creates the two resource groups, then calls the modules in
`terraform/modules/` and passes outputs from one to the next, so Terraform creates them in the same order as Bicep:
monitoring and Foundry first, then the gateway, then models, tools, keys, and telemetry. Like the Bicep modules,
the AI Gateway resources go through the `azapi` provider at API version `2026-11-01`, and no output holds a key.

<!-- include: terraform/main.tf -->

On GitHub, open [terraform/main.tf](terraform/main.tf).

The `gateway` module declares the gateway itself and the **Foundry User** role for its identity, with a 60-minute
create timeout, because activation can take longer than the `azapi` default of 30 minutes. The other modules only
add child resources to it.

The `models` module declares the token limit and content safety right on the backend model, like `models.bicep`:

<!-- include: terraform/modules/models/main.tf -->

On GitHub, open [terraform/modules/models/main.tf](terraform/modules/models/main.tf).

The `telemetry` module replaces `connect-telemetry.sh`. A `terraform_data` resource runs the script's wait with the
Azure CLI, a `GET` reads the endpoints and the Data Collection Rule once, then the module assigns
**Monitoring Metrics Publisher** and creates the exporter:

<!-- include: terraform/modules/telemetry/main.tf -->

On GitHub, open [terraform/modules/telemetry/main.tf](terraform/modules/telemetry/main.tf).

The baseline stays a script on this track too, `infra/scripts/apply-baselines.sh` with `infra/baselines.json`,
because a resource that declares the `default` workspace's policies would replace the ones that are already there.

The other files are short. Open them on GitHub:
[variables.tf](terraform/variables.tf), [outputs.tf](terraform/outputs.tf), [dev.tfvars](terraform/dev.tfvars),
[prod.tfvars](terraform/prod.tfvars), [monitoring](terraform/modules/monitoring/main.tf),
[foundry](terraform/modules/foundry/main.tf), [gateway](terraform/modules/gateway/main.tf),
[tools](terraform/modules/tools/main.tf), and [keys](terraform/modules/keys/main.tf).

<!-- /tracks -->

## Deploy the dev environment

Deploy from your machine first, so you see each stage before you automate it.

<!-- track: iac | Bicep -->

### Preview the changes

```bash title="Bash"
# Preview what the deployment would create or change, with the dev parameters, without changing anything
echo "📊 What deployment $ENV_NAME would change:"
az deployment sub what-if -n "$ENV_NAME" -l "$LOCATION" \
  -f infra/main.bicep -p infra/main.bicepparam
```

```powershell title="PowerShell"
# Preview what the deployment would create or change, with the dev parameters, without changing anything
Write-Host "📊 What deployment $env:ENV_NAME would change:"
az deployment sub what-if -n $env:ENV_NAME -l $env:LOCATION `
  -f infra/main.bicep -p infra/main.bicepparam
```

On a first run, the preview lists the two resource groups and the resources in them as new. On later runs, it
shows only what your change would modify. Paste it into the pull request so reviewers see the effect, not just
the diff.

### Deploy

```bash title="Bash"
# Deploy the subscription-scope template with the dev parameters, and keep only its provisioning state
STATE="$(az deployment sub create -n "$ENV_NAME" -l "$LOCATION" \
  -f infra/main.bicep -p infra/main.bicepparam \
  --query properties.provisioningState -o tsv)" &&
  echo "🚀 Deployment $ENV_NAME finished: $STATE"
```

```powershell title="PowerShell"
# Deploy the subscription-scope template with the dev parameters, and keep only its provisioning state
$state = az deployment sub create -n $env:ENV_NAME -l $env:LOCATION `
  -f infra/main.bicep -p infra/main.bicepparam `
  --query properties.provisioningState -o tsv
if ($?) { Write-Host "🚀 Deployment $env:ENV_NAME finished: $state" }
```

Provisioning the gateway and the model deployment takes about three minutes. The command prints
`🚀 Deployment aigw-dev finished: Succeeded` when everything is in place.

### Load the outputs

Read the deployment outputs into the variables the scripts and the rest of the lab use:

```bash title="Bash"
# Read the deployment's outputs as JSON
OUTPUTS="$(az deployment sub show -n "$ENV_NAME" --query properties.outputs -o json)"

# Define a helper that reads one output: output names can come back with a different first-letter casing,
# so it matches them case-insensitively
out() { jq -r --arg k "$1" 'to_entries[] | select((.key | ascii_upcase) == $k) | .value.value' <<<"$OUTPUTS"; }

# Read the gateway, the alias, and the Foundry account into the variables that the scripts and later steps use
export RG="$(out AI_GATEWAY_RESOURCE_GROUP)"
export GATEWAY="$(out AI_GATEWAY_NAME)"
export AI_GATEWAY_URL="$(out AI_GATEWAY_URL)"
export AI_GATEWAY_MODEL="$(out AI_GATEWAY_MODEL)"
export AI_GATEWAY_LOCATION="$(out AI_GATEWAY_LOCATION)"
export AI_GATEWAY_PRINCIPAL_ID="$(out AI_GATEWAY_PRINCIPAL_ID)"
export FOUNDRY_RG="$(out FOUNDRY_MODELS_RESOURCE_GROUP)"
export FOUNDRY_NAME="$(out FOUNDRY_MODELS_NAME)"
export FOUNDRY_ID="$(out FOUNDRY_MODELS_RESOURCE_ID)"
echo "📝 Gateway $GATEWAY in $RG"
echo "🌐 Runtime URL: $AI_GATEWAY_URL"
echo "🔖 Model alias: $AI_GATEWAY_MODEL"
echo "🏭 Foundry account $FOUNDRY_NAME in $FOUNDRY_RG"
```

```powershell title="PowerShell"
# Read the deployment's outputs
$outputs = az deployment sub show -n $env:ENV_NAME --query properties.outputs -o json | ConvertFrom-Json

# Read the gateway, the alias, and the Foundry account into the variables that the scripts and later steps use
# (PowerShell matches the output names case-insensitively)
$env:RG                      = $outputs.AI_GATEWAY_RESOURCE_GROUP.value
$env:GATEWAY                 = $outputs.AI_GATEWAY_NAME.value
$env:AI_GATEWAY_URL          = $outputs.AI_GATEWAY_URL.value
$env:AI_GATEWAY_MODEL        = $outputs.AI_GATEWAY_MODEL.value
$env:AI_GATEWAY_LOCATION     = $outputs.AI_GATEWAY_LOCATION.value
$env:AI_GATEWAY_PRINCIPAL_ID = $outputs.AI_GATEWAY_PRINCIPAL_ID.value
$env:FOUNDRY_RG              = $outputs.FOUNDRY_MODELS_RESOURCE_GROUP.value
$env:FOUNDRY_NAME            = $outputs.FOUNDRY_MODELS_NAME.value
$env:FOUNDRY_ID              = $outputs.FOUNDRY_MODELS_RESOURCE_ID.value
Write-Host "📝 Gateway $env:GATEWAY in $env:RG"
Write-Host "🌐 Runtime URL: $env:AI_GATEWAY_URL"
Write-Host "🔖 Model alias: $env:AI_GATEWAY_MODEL"
Write-Host "🏭 Foundry account $env:FOUNDRY_NAME in $env:FOUNDRY_RG"
```

Expected output:

```text
📝 Gateway aigw-<token> in rg-aigw-dev-<token>-gateway
🌐 Runtime URL: https://aigw-abcde-k3v7qz2m9xw4p.eastus2-01.ai.gateway.azure.com
🔖 Model alias: chat
🏭 Foundry account aimodels-<token> in rg-aigw-dev-<token>-foundrymodels
```

### Connect telemetry

Run the telemetry script. It waits until Azure has created the component's OTLP endpoints, grants the gateway's
identity **Monitoring Metrics Publisher** on the Data Collection Rule, then deploys `modules/telemetry.bicep`. Right
after the first deployment, the wait can take a few minutes.

```bash title="Bash"
# Wait for the OTLP endpoints, let the gateway's identity publish to them, then deploy the OpenTelemetry exporter
./infra/scripts/connect-telemetry.sh &&
  echo "📊 Telemetry is connected for $GATEWAY"
```

```powershell title="PowerShell"
# Wait for the OTLP endpoints, let the gateway's identity publish to them, then deploy the OpenTelemetry exporter
./infra/scripts/connect-telemetry.ps1
if ($?) { Write-Host "📊 Telemetry is connected for $env:GATEWAY" }
```

On GitHub, open [infra/scripts/connect-telemetry.sh](infra/scripts/connect-telemetry.sh) or
[infra/scripts/connect-telemetry.ps1](infra/scripts/connect-telemetry.ps1).

Expected output:

```text
⏳ Waiting for the OTLP endpoints of aigw-<token>-insights
🆔 Data Collection Rule: managed-aigw-<token>-insights-dcr
🔐 The gateway can publish to the Data Collection Rule
📊 The gateway sends metrics, logs, and traces to aigw-<token>-insights
📊 Telemetry is connected for aigw-<token>
```

The role assignment needs the same rights as the deployment. Run the script after each deployment: running it again
gives the same result.

<!-- track: terraform | Terraform -->

**What you need:** Terraform 1.9 or later, as in [Deploy a lab with Terraform](../SETUP.md#deploy-a-lab-with-terraform),
and the variables from **Before you begin**. The configuration creates its own resource groups,
`rg-aigw-dev-tf-gateway` and `rg-aigw-dev-tf-foundrymodels`, so it doesn't touch a Bicep deployment.

### Preview the changes

Move into the lab's Terraform folder, pass your region and your object ID to the configuration, then plan the dev
environment from `dev.tfvars`:

```bash title="Bash"
# Move into the lab's Terraform folder
cd ~/aigateway/labs/21-enterprise-reference/terraform &&
  echo "📂 Terraform folder: $(pwd)"

# Deploy to the Azure CLI's current subscription, in the region from Before you begin, and give yourself
# data-plane access, like main.bicepparam does
export ARM_SUBSCRIPTION_ID="$(az account show --query id --output tsv)"
export TF_VAR_location="$LOCATION"
export TF_VAR_principal_id="$AZURE_PRINCIPAL_ID"
echo "📍 Subscription $ARM_SUBSCRIPTION_ID, region $TF_VAR_location"

# Download the providers, then plan the dev environment and save the plan, without changing anything
terraform init &&
  terraform plan -var-file dev.tfvars -out tfplan &&
  echo "📊 The plan for aigw-dev-tf is saved in tfplan"
```

```powershell title="PowerShell"
# Move into the lab's Terraform folder
Set-Location ~/aigateway/labs/21-enterprise-reference/terraform
if ($?) { Write-Host "📂 Terraform folder: $(Get-Location)" }

# Deploy to the Azure CLI's current subscription, in the region from Before you begin, and give yourself
# data-plane access, like main.bicepparam does
$env:ARM_SUBSCRIPTION_ID = az account show --query id --output tsv
$env:TF_VAR_location     = $env:LOCATION
$env:TF_VAR_principal_id = $env:AZURE_PRINCIPAL_ID
Write-Host "📍 Subscription $env:ARM_SUBSCRIPTION_ID, region $env:TF_VAR_location"

# Download the providers, then plan the dev environment and save the plan, without changing anything
terraform init
if ($?) { terraform plan -var-file dev.tfvars -out tfplan }
if ($?) { Write-Host "📊 The plan for aigw-dev-tf is saved in tfplan" }
```

On a first run, the plan ends with `Plan: 23 to add, 0 to change, 0 to destroy.` On later runs, like `what-if`, it
shows only what your change would modify. Paste it into the pull request so reviewers see the effect. The gateway
gets the same region as the other resources. To put it in another region, also set `TF_VAR_ai_gateway_location`.

### Deploy with terraform apply

```bash title="Bash"
# Apply the saved plan: the resource groups, monitoring, Foundry, the gateway, models, tools, keys, and telemetry
terraform apply tfplan &&
  echo "🚀 Gateway deployed: $(terraform output -raw ai_gateway_url)"
```

```powershell title="PowerShell"
# Apply the saved plan: the resource groups, monitoring, Foundry, the gateway, models, tools, keys, and telemetry
terraform apply tfplan
if ($?) { Write-Host "🚀 Gateway deployed: $(terraform output -raw ai_gateway_url)" }
```

It usually takes a few minutes, most of it while the gateway activates and Terraform creates the role
assignments. Activation can take more than half an hour, and the `gateway` module waits up to an hour for it. The
`telemetry` module waits up to 10 minutes for the OTLP endpoints, but they're usually ready by the time the
gateway is. The apply ends with `Apply complete! Resources: 23 added, 0 changed, 0 destroyed.`

### Load the outputs

Read the Terraform outputs into the variables the scripts and the rest of the lab use, then go back to the lab
folder:

```bash title="Bash"
# Read the gateway, the alias, and the Foundry account into the variables that the scripts and later steps use
export RG="$(terraform output -raw ai_gateway_resource_group)"
export GATEWAY="$(terraform output -raw ai_gateway_name)"
export AI_GATEWAY_URL="$(terraform output -raw ai_gateway_url)"
export AI_GATEWAY_MODEL="$(terraform output -raw ai_gateway_model)"
export AI_GATEWAY_LOCATION="$(terraform output -raw ai_gateway_location)"
export AI_GATEWAY_PRINCIPAL_ID="$(terraform output -raw ai_gateway_principal_id)"
export FOUNDRY_RG="$(terraform output -raw foundry_models_resource_group)"
export FOUNDRY_NAME="$(terraform output -raw foundry_models_name)"
export FOUNDRY_ID="$(terraform output -raw foundry_models_resource_id)"
echo "📝 Gateway $GATEWAY in $RG"
echo "🌐 Runtime URL: $AI_GATEWAY_URL"
echo "🔖 Model alias: $AI_GATEWAY_MODEL"
echo "🏭 Foundry account $FOUNDRY_NAME in $FOUNDRY_RG"

# Go back to the lab folder, where the scripts and the later steps run
cd .. && echo "📂 Lab folder: $(pwd)"
```

```powershell title="PowerShell"
# Read the gateway, the alias, and the Foundry account into the variables that the scripts and later steps use
$env:RG                      = terraform output -raw ai_gateway_resource_group
$env:GATEWAY                 = terraform output -raw ai_gateway_name
$env:AI_GATEWAY_URL          = terraform output -raw ai_gateway_url
$env:AI_GATEWAY_MODEL        = terraform output -raw ai_gateway_model
$env:AI_GATEWAY_LOCATION     = terraform output -raw ai_gateway_location
$env:AI_GATEWAY_PRINCIPAL_ID = terraform output -raw ai_gateway_principal_id
$env:FOUNDRY_RG              = terraform output -raw foundry_models_resource_group
$env:FOUNDRY_NAME            = terraform output -raw foundry_models_name
$env:FOUNDRY_ID              = terraform output -raw foundry_models_resource_id
Write-Host "📝 Gateway $env:GATEWAY in $env:RG"
Write-Host "🌐 Runtime URL: $env:AI_GATEWAY_URL"
Write-Host "🔖 Model alias: $env:AI_GATEWAY_MODEL"
Write-Host "🏭 Foundry account $env:FOUNDRY_NAME in $env:FOUNDRY_RG"

# Go back to the lab folder, where the scripts and the later steps run
Set-Location ..
if ($?) { Write-Host "📂 Lab folder: $(Get-Location)" }
```

Expected output:

```text
📝 Gateway aigw-<token> in rg-aigw-dev-tf-gateway
🌐 Runtime URL: https://aigw-abcde-k3v7qz2m9xw4p.eastus2-01.ai.gateway.azure.com
🔖 Model alias: chat
🏭 Foundry account aimodels-<token> in rg-aigw-dev-tf-foundrymodels
📂 Lab folder: /home/<user>/aigateway/labs/21-enterprise-reference
```

Telemetry is already connected: the apply created the exporter, `appinsights`, after the role assignment. To check
for drift later, run `terraform plan -var-file dev.tfvars` from `terraform/` again. It prints
`No changes. Your infrastructure matches the configuration.`

<!-- /tracks -->

On both tracks, apply the gateway baseline from the lab folder with the same script.

<!-- steps -->

### Preview the gateway baseline

Print the merged policy array without changing anything:

```bash title="Bash"
# Print the merged policy array without changing anything: with DRY_RUN=1, the script stops before it writes
DRY_RUN=1 ./infra/scripts/apply-baselines.sh &&
  echo "🔐 Baseline preview finished: the policies on $GATEWAY are unchanged"
```

```powershell title="PowerShell"
# Print the merged policy array without changing anything: with -DryRun, the script stops before it writes
./infra/scripts/apply-baselines.ps1 -DryRun
if ($?) { Write-Host "🔐 Baseline preview finished: the policies on $env:GATEWAY are unchanged" }
```

The output shows a `requestRateLimit` entry and a `costLimit` entry with a newly generated `id`, plus any
Gateway scope policies the gateway already has.

### Apply the gateway baseline

```bash title="Bash"
# Merge baselines.json into the gateway's Gateway scope policies, write them back, and list the policy types
./infra/scripts/apply-baselines.sh &&
  echo "🔐 Gateway baseline is applied to $GATEWAY"
```

```powershell title="PowerShell"
# Merge baselines.json into the gateway's Gateway scope policies, write them back, and list the policy types
./infra/scripts/apply-baselines.ps1
if ($?) { Write-Host "🔐 Gateway baseline is applied to $env:GATEWAY" }
```

<!-- include: infra/scripts/apply-baselines.sh -->

On GitHub, open [infra/scripts/apply-baselines.sh](infra/scripts/apply-baselines.sh) or
[infra/scripts/apply-baselines.ps1](infra/scripts/apply-baselines.ps1).

Expected output (end):

```text
Applied. Current gateway-scope policy types:
requestRateLimit
costLimit
🔐 Gateway baseline is applied to aigw-<token>
```

Run it again whenever `baselines.json` changes. It's idempotent: a second run gives the same array.

<!-- /steps -->

> **Checkpoint**
> On the Bicep track, the deployment printed `🚀 Deployment aigw-dev finished: Succeeded` and the telemetry script
> printed `📊 Telemetry is connected`. On the Terraform track, the apply printed
> `Apply complete! Resources: 23 added, 0 changed, 0 destroyed.` On both, `RG` and `GATEWAY` point at the new
> gateway, **Monitoring** shows the **Overview**, **Models**, **Tools**, **Policies**, and **Traces** tabs, and the
> baseline script lists `requestRateLimit` and `costLimit`.

## Automate deployments with GitHub Actions

Copy this lab's `infra/` folder to the root of your own repository, so the workflow finds `infra/main.bicep`. On
the Terraform track, also copy the `terraform/` folder. The workflow still runs the scripts and reads
`baselines.json` from `infra/`.
Then create an identity that GitHub Actions can sign in as, trust your repository's environments, and add the
workflow. Learn more in
[Authenticate to Azure from GitHub Actions by OpenID Connect](https://learn.microsoft.com/azure/developer/github/connect-from-azure-openid-connect).

Set the repository once:

```bash title="Bash"
# Set the GitHub repository that holds the workflow, in the form org/repo
export GITHUB_REPO="<github-org>/<github-repo>"
echo "📝 GitHub repository: $GITHUB_REPO"
```

```powershell title="PowerShell"
# Set the GitHub repository that holds the workflow, in the form org/repo
$env:GITHUB_REPO = "<github-org>/<github-repo>"
Write-Host "📝 GitHub repository: $env:GITHUB_REPO"
```

<!-- steps -->

### Create the deployment identity

Create an app registration and its service principal:

```bash title="Bash"
# Create the app registration that GitHub Actions signs in as, and keep its application (client) ID
export APP_ID="$(az ad app create --display-name "github-aigw-deploy" --query appId -o tsv)"
echo "👤 App registration github-aigw-deploy: $APP_ID"

# Create its service principal, the identity that gets the role assignments on your subscription
export SP_ID="$(az ad sp create --id "$APP_ID" --query id -o tsv)"
echo "👤 Service principal: $SP_ID"
```

```powershell title="PowerShell"
# Create the app registration that GitHub Actions signs in as, and keep its application (client) ID
$env:APP_ID = az ad app create --display-name "github-aigw-deploy" --query appId -o tsv
if ($?) { Write-Host "👤 App registration github-aigw-deploy: $env:APP_ID" }

# Create its service principal, the identity that gets the role assignments on your subscription
$env:SP_ID  = az ad sp create --id $env:APP_ID --query id -o tsv
if ($?) { Write-Host "👤 Service principal: $env:SP_ID" }
```

### Trust your GitHub environments

Add one federated credential per GitHub environment. The workflow's job declares `environment:`, so GitHub's
token subject is the repository's subject prefix followed by `:environment:<name>`, and it must match exactly.
The prefix is `repo:<github-org>/<github-repo>` for older repositories. Repositories created after July 15, 2026
use [immutable subject claims](https://docs.github.com/actions/reference/security/oidc#immutable-subject-claims),
which add the owner and repository IDs, as in `repo:<github-org>@<org-id>/<github-repo>@<repo-id>`. GitHub
returns the prefix that your repository uses, so read it instead of typing it.

```bash title="Bash"
# Read the subject prefix of your repository's OIDC tokens, with the immutable IDs if the repository uses them
export SUBJECT_PREFIX="$(gh api "repos/$GITHUB_REPO/actions/oidc/customization/sub" --jq .sub_claim_prefix)"
echo "🔖 Token subject prefix: $SUBJECT_PREFIX"

# For each GitHub environment, add a federated credential that trusts GitHub's tokens for that environment only
for ENV in dev prod; do
  # Write the credential to a file: its subject must match the workflow's environment exactly
  cat > "credential-$ENV.json" <<EOF
{
  "name": "github-$ENV",
  "issuer": "https://token.actions.githubusercontent.com",
  "subject": "$SUBJECT_PREFIX:environment:$ENV",
  "description": "GitHub Actions deployments to the $ENV environment",
  "audiences": [ "api://AzureADTokenExchange" ]
}
EOF
  # Add the credential to the app registration, then delete the file
  az ad app federated-credential create --id "$APP_ID" --parameters "credential-$ENV.json" -o none &&
    echo "👤 Federated credential github-$ENV trusts the $ENV environment of $GITHUB_REPO"
  rm "credential-$ENV.json"
done
```

```powershell title="PowerShell"
# Read the subject prefix of your repository's OIDC tokens, with the immutable IDs if the repository uses them
$env:SUBJECT_PREFIX = gh api "repos/$($env:GITHUB_REPO)/actions/oidc/customization/sub" --jq .sub_claim_prefix
Write-Host "🔖 Token subject prefix: $env:SUBJECT_PREFIX"

# For each GitHub environment, add a federated credential that trusts GitHub's tokens for that environment only
foreach ($envName in "dev", "prod") {
  # Write the credential to a file: its subject must match the workflow's environment exactly
  $file = "credential-$envName.json"
  @{
    name        = "github-$envName"
    issuer      = "https://token.actions.githubusercontent.com"
    subject     = "$($env:SUBJECT_PREFIX):environment:$envName"
    description = "GitHub Actions deployments to the $envName environment"
    audiences   = @("api://AzureADTokenExchange")
  } | ConvertTo-Json | Set-Content -Path $file
  # Add the credential to the app registration, then delete the file
  az ad app federated-credential create --id $env:APP_ID --parameters $file -o none
  if ($?) { Write-Host "👤 Federated credential github-$envName trusts the $envName environment of $env:GITHUB_REPO" }
  Remove-Item $file
}
```

### Grant access to the subscription

```bash title="Bash"
# Read your subscription ID, the scope of the role assignments
export SUBSCRIPTION_ID="$(az account show --query id -o tsv)"
echo "🆔 Subscription: $SUBSCRIPTION_ID"

# Give the service principal Contributor, to deploy the resources, and Role Based Access Control Administrator,
# because the template creates role assignments
for ROLE in "Contributor" "Role Based Access Control Administrator"; do
  az role assignment create --assignee-object-id "$SP_ID" --assignee-principal-type ServicePrincipal \
    --role "$ROLE" --scope "/subscriptions/$SUBSCRIPTION_ID" -o none &&
    echo "🔐 The deployment identity has the $ROLE role on the subscription"
done
```

```powershell title="PowerShell"
# Read your subscription ID, the scope of the role assignments
$env:SUBSCRIPTION_ID = az account show --query id -o tsv
Write-Host "🆔 Subscription: $env:SUBSCRIPTION_ID"

# Give the service principal Contributor, to deploy the resources, and Role Based Access Control Administrator,
# because the template creates role assignments
foreach ($role in "Contributor", "Role Based Access Control Administrator") {
  az role assignment create --assignee-object-id $env:SP_ID --assignee-principal-type ServicePrincipal `
    --role $role --scope "/subscriptions/$($env:SUBSCRIPTION_ID)" -o none
  if ($?) { Write-Host "🔐 The deployment identity has the $role role on the subscription" }
}
```

### Create the GitHub environments

In your repository on GitHub, select **Settings** › **Environments** › **New environment**, and create `dev`
and `prod`. On `prod`, turn on **Required reviewers** and add the people who approve production deployments.
On the GitHub Free, Pro, and Team plans, required reviewers are
[only available for public repositories](https://docs.github.com/actions/reference/workflows-and-actions/deployments-and-environments#required-reviewers).

Then store the sign-in details as environment variables. They identify the identity but can't authenticate
anyone on their own, so they're variables, not secrets.

```bash title="Bash"
# Read your tenant ID, the Microsoft Entra tenant that the workflow signs in to
TENANT_ID="$(az account show --query tenantId -o tsv)"
echo "🆔 Tenant: $TENANT_ID"

# Store the app's client ID, the tenant ID, and the subscription ID as variables of each GitHub environment
for ENV in dev prod; do
  gh variable set AZURE_CLIENT_ID --env "$ENV" --body "$APP_ID" -R "$GITHUB_REPO"
  gh variable set AZURE_TENANT_ID --env "$ENV" --body "$TENANT_ID" -R "$GITHUB_REPO"
  gh variable set AZURE_SUBSCRIPTION_ID --env "$ENV" --body "$SUBSCRIPTION_ID" -R "$GITHUB_REPO" &&
    echo "📝 The $ENV environment has AZURE_CLIENT_ID, AZURE_TENANT_ID, and AZURE_SUBSCRIPTION_ID"
done
```

```powershell title="PowerShell"
# Read your tenant ID, the Microsoft Entra tenant that the workflow signs in to
$tenantId = az account show --query tenantId -o tsv
Write-Host "🆔 Tenant: $tenantId"

# Store the app's client ID, the tenant ID, and the subscription ID as variables of each GitHub environment
foreach ($envName in "dev", "prod") {
  gh variable set AZURE_CLIENT_ID --env $envName --body $env:APP_ID -R $env:GITHUB_REPO
  gh variable set AZURE_TENANT_ID --env $envName --body $tenantId -R $env:GITHUB_REPO
  gh variable set AZURE_SUBSCRIPTION_ID --env $envName --body $env:SUBSCRIPTION_ID -R $env:GITHUB_REPO
  if ($?) { Write-Host "📝 The $envName environment has AZURE_CLIENT_ID, AZURE_TENANT_ID, and AZURE_SUBSCRIPTION_ID" }
}
```

<!-- /steps -->

<!-- track: iac | Bicep -->

### Add the workflow

In your repository, copy the sample workflow into `.github/workflows/`, then commit and push both folders:

```bash
# Create the workflows folder, and copy the sample workflow into it
mkdir -p .github/workflows
cp infra/deploy-workflow.yml .github/workflows/deploy-ai-gateway.yml &&
  echo "📄 Workflow file: .github/workflows/deploy-ai-gateway.yml"
```

<!-- include: infra/deploy-workflow.yml yaml -->

On GitHub, open [infra/deploy-workflow.yml](infra/deploy-workflow.yml).

A push to `main` that changes `infra/` deploys dev. Prod deploys only when you start the workflow manually and a
reviewer approves it.

<!-- track: terraform | Terraform -->

### Store the state in Azure

The pipeline runs on a new machine each time, so it can't read the `terraform.tfstate` file on yours. Keep the
state in an Azure Storage blob container instead, where you and the pipeline share it:

1. Create a storage account and a blob container named `tfstate`, as in
   [Store Terraform state in Azure Storage](https://learn.microsoft.com/azure/developer/terraform/store-state-in-azure-storage).
   Your machine and GitHub's runners must both reach it, so check your organization's network policies for
   storage accounts first.
2. Give the deployment identity, `$SP_ID`, and yourself the **Storage Blob Data Contributor** role on the
   container, so that both sign in to it with Microsoft Entra ID instead of an account key.

Then store the account's name and your object ID in GitHub, declare the backend, and move your local state into
the container. Run this in the lab's `terraform/` folder, where your local state is:

```bash title="Bash"
# Store the state's storage account in both GitHub environments. Store your object ID in dev only: the pipeline
# passes it to the configuration, so that dev keeps your developer roles
export TFSTATE_ACCOUNT="<storage-account-name>"
for ENV in dev prod; do
  gh variable set TFSTATE_STORAGE_ACCOUNT --env "$ENV" --body "$TFSTATE_ACCOUNT" -R "$GITHUB_REPO"
done
gh variable set DEVELOPER_PRINCIPAL_ID --env dev --body "$AZURE_PRINCIPAL_ID" -R "$GITHUB_REPO" &&
  echo "📝 GitHub has TFSTATE_STORAGE_ACCOUNT in dev and prod, and DEVELOPER_PRINCIPAL_ID in dev"

# Declare the azurerm backend with Microsoft Entra sign-in. The account, the container, and the state's name come
# from -backend-config, so the same file works for dev and prod
cd ~/aigateway/labs/21-enterprise-reference/terraform &&
  cat > backend.tf <<'EOF'
terraform {
  backend "azurerm" {
    use_azuread_auth = true
  }
}
EOF

# Copy the local state into the container as dev.tfstate: answer yes when Terraform asks
terraform init -migrate-state \
  -backend-config="storage_account_name=$TFSTATE_ACCOUNT" \
  -backend-config="container_name=tfstate" \
  -backend-config="key=dev.tfstate" &&
  echo "🔒 The dev state is in the tfstate container of $TFSTATE_ACCOUNT"

# Move back to the lab's folder, where Verify runs the scripts
cd .. && echo "📂 Lab folder: $(pwd)"
```

```powershell title="PowerShell"
# Store the state's storage account in both GitHub environments. Store your object ID in dev only: the pipeline
# passes it to the configuration, so that dev keeps your developer roles
$env:TFSTATE_ACCOUNT = "<storage-account-name>"
foreach ($envName in "dev", "prod") {
  gh variable set TFSTATE_STORAGE_ACCOUNT --env $envName --body $env:TFSTATE_ACCOUNT -R $env:GITHUB_REPO
}
gh variable set DEVELOPER_PRINCIPAL_ID --env dev --body $env:AZURE_PRINCIPAL_ID -R $env:GITHUB_REPO
if ($?) { Write-Host "📝 GitHub has TFSTATE_STORAGE_ACCOUNT in dev and prod, and DEVELOPER_PRINCIPAL_ID in dev" }

# Declare the azurerm backend with Microsoft Entra sign-in. The account, the container, and the state's name come
# from -backend-config, so the same file works for dev and prod
Set-Location ~/aigateway/labs/21-enterprise-reference/terraform
@'
terraform {
  backend "azurerm" {
    use_azuread_auth = true
  }
}
'@ | Set-Content -Path backend.tf

# Copy the local state into the container as dev.tfstate: answer yes when Terraform asks
terraform init -migrate-state `
  "-backend-config=storage_account_name=$($env:TFSTATE_ACCOUNT)" `
  "-backend-config=container_name=tfstate" `
  "-backend-config=key=dev.tfstate"
if ($?) { Write-Host "🔒 The dev state is in the tfstate container of $env:TFSTATE_ACCOUNT" }

# Move back to the lab's folder, where Verify runs the scripts
Set-Location ..
if ($?) { Write-Host "📂 Lab folder: $(Get-Location)" }
```

Copy `backend.tf` into the `terraform/` folder of your repository too. Don't commit the `.terraform/` folder, the
`terraform.tfstate` files, or `tfplan`: they're your local working files, so add them to your `.gitignore`. Move the state before the pipeline's
first run. Otherwise, its `terraform apply` starts from an empty state and fails because the resources already
exist.

### Add the workflow

In your repository, copy the sample workflow into `.github/workflows/`, as on the Bicep track:

```bash
# Create the workflows folder, and copy the sample workflow into it
mkdir -p .github/workflows
cp infra/deploy-workflow.yml .github/workflows/deploy-ai-gateway.yml &&
  echo "📄 Workflow file: .github/workflows/deploy-ai-gateway.yml"
```

Then make it run Terraform. The sign-in, the extension, the baseline, the smoke test, and the summary don't
change, because the scripts still use the Azure CLI:

1. Under `on.push.paths`, add `terraform/**`, so that a change to the configuration deploys dev.
2. Replace the job's `env` with the one below. `ARM_USE_OIDC` makes both providers and the backend sign in with
   GitHub's OpenID Connect token, like `azure/login` does. Set `TF_VAR_location` to the region you deployed from
   your machine: the token in the resource names depends on it.
3. Replace the **Preview changes** and **Deploy** steps with the Terraform steps below. **Deploy** keeps its `id`
   and its four outputs, so the later steps read them as before.
4. Delete the **Connect telemetry** step: the `telemetry` module connects it in `terraform apply`.

```yaml
    env:
      ARM_CLIENT_ID: ${{ vars.AZURE_CLIENT_ID }}
      ARM_TENANT_ID: ${{ vars.AZURE_TENANT_ID }}
      ARM_SUBSCRIPTION_ID: ${{ vars.AZURE_SUBSCRIPTION_ID }}
      ARM_USE_OIDC: true
      TF_VAR_location: eastus2
      TF_VAR_principal_id: ${{ vars.DEVELOPER_PRINCIPAL_ID }}
      VAR_FILE: ${{ (inputs.environment || 'dev') == 'prod' && 'prod.tfvars' || 'dev.tfvars' }}
      STATE_KEY: ${{ inputs.environment || 'dev' }}.tfstate
    steps:
      # Keep the checkout, sign-in, and extension steps here

      - name: Install Terraform
        uses: hashicorp/setup-terraform@v3
        with:
          terraform_wrapper: false

      - name: Connect to the state
        working-directory: terraform
        run: |
          terraform init -input=false \
            -backend-config="storage_account_name=${{ vars.TFSTATE_STORAGE_ACCOUNT }}" \
            -backend-config="container_name=tfstate" \
            -backend-config="key=$STATE_KEY"

      - name: Preview changes
        working-directory: terraform
        run: terraform plan -input=false -var-file "$VAR_FILE" -out tfplan

      - name: Deploy
        id: deploy
        working-directory: terraform
        run: |
          terraform apply -input=false tfplan
          {
            echo "resource-group=$(terraform output -raw ai_gateway_resource_group)"
            echo "gateway=$(terraform output -raw ai_gateway_name)"
            echo "gateway-url=$(terraform output -raw ai_gateway_url)"
            echo "alias=$(terraform output -raw ai_gateway_model)"
          } >> "$GITHUB_OUTPUT"

      # Keep the baseline, smoke test, and summary steps here
```

Unlike an incremental Bicep deployment, `terraform apply` deletes what the configuration no longer declares. That's
why the job passes `DEVELOPER_PRINCIPAL_ID` as `TF_VAR_principal_id`: without it, the dev run would remove your
developer roles. `prod.tfvars` sets `principal_id = ""`, and a value in a `-var-file` overrides an environment
variable, so prod never gets developer roles. The **Deploy** step applies the plan that **Preview changes** saved,
so it changes exactly what the log of the preview shows.

Commit and push `infra/`, `terraform/`, and the workflow. A push to `main` that changes `infra/` or `terraform/`
deploys dev. Prod deploys only when you start the workflow manually and a reviewer approves it.

<!-- /tracks -->

<!-- steps -->

### Run it

```bash
# Start the workflow for the dev environment
gh workflow run deploy-ai-gateway.yml -f environment=dev -R "$GITHUB_REPO" &&
  echo "⏳ The Deploy AI Gateway workflow is queued for dev"

# Watch the run's jobs and steps until it finishes
echo "⏳ Watching the run (Ctrl+C stops watching, not the run):"
gh run watch -R "$GITHUB_REPO"
```

Or, in GitHub, select **Actions** › **Deploy AI Gateway** › **Run workflow**. The pipeline deploys to the same
resource groups you created from your machine, because the resource token depends only on the subscription,
the environment name, and the location. On the Bicep track, the pipeline doesn't set `AZURE_PRINCIPAL_ID`, so it
doesn't declare your developer roles, and incremental deployments leave the ones you already have in place. On the
Terraform track, the pipeline reads and updates the state you moved to the container, so its plan starts from
what you deployed.

<!-- /steps -->

> **Checkpoint**
> The run's **Smoke test** step prints `Smoke test passed.`, and the run summary lists the gateway, its
> endpoint, and the alias `chat`.

## Verify

Prove that both runtime paths work, that the policy layers are in place, and that the identity boundaries hold.

<!-- steps -->

### Run the smoke test

The same script runs at the end of the pipeline. It calls the alias with the `web-chat` key, then runs the MCP
handshake and `tools/list` on the `learn` MCP server. New role assignments can take a few minutes to apply, so
it retries the model call for about a minute.

```bash title="Bash"
# Call the alias with the web-chat key, then run the MCP handshake and tools/list on the learn MCP server
echo "📊 Smoke test of the $AI_GATEWAY_MODEL alias and the learn MCP server:"
./infra/scripts/smoke-test.sh "$AI_GATEWAY_MODEL" web-chat learn
```

```powershell title="PowerShell"
# Call the alias with the web-chat key, then run the MCP handshake and tools/list on the learn MCP server
Write-Host "📊 Smoke test of the $env:AI_GATEWAY_MODEL alias and the learn MCP server:"
./infra/scripts/smoke-test.ps1 -Alias $env:AI_GATEWAY_MODEL -KeyName web-chat -Server learn
```

On GitHub, open [infra/scripts/smoke-test.sh](infra/scripts/smoke-test.sh) or
[infra/scripts/smoke-test.ps1](infra/scripts/smoke-test.ps1).

Expected output (the tool list can change as the Learn server evolves):

```text
📊 Smoke test of the chat alias and the learn MCP server:
Gateway: https://aigw-abcde-k3v7qz2m9xw4p.eastus2-01.ai.gateway.azure.com
Model  : HTTP 200, model=<model>, reply=ok, total_tokens=<n>
Tools  : HTTP 200, 3 tools on learn
         learn_microsoft_docs_search
         learn_microsoft_code_sample_search
         learn_microsoft_docs_fetch
Smoke test passed.
```

That one model call passed every layer: the Gateway scope request rate and cost limits, then the model's token
limit and content safety. The gateway called Foundry with its managed identity.

### Review the policy layers in the portal

Select **Policies**. **Request rate limit** and **Cost limit** show **Gateway** in the **Scope** column.
**Token rate limit** and **Content safety** show the backend model instead. Select **Models** to see that
model and the alias `chat`, and **MCP servers** to see `learn`.

### Call the alias with your Microsoft Entra identity

The dev parameters gave you **AI Gateway Models User** on the alias, so you can call it without a key:

```bash title="Bash"
# Get a Microsoft Entra token for AI Gateway, for your own identity
export AI_GATEWAY_TOKEN="$(az account get-access-token \
  --scope https://ai.gateway.azure.com/Data.All --query accessToken -o tsv)"
echo "👤 Token acquired: in AI_GATEWAY_TOKEN (${#AI_GATEWAY_TOKEN} characters, not shown)"

# Call the alias with the token instead of a key: your AI Gateway Models User role on the alias lets you in
curl -sS "${AI_GATEWAY_URL%/}/default/models/openai/v1/chat/completions" \
  -H "Authorization: Bearer $AI_GATEWAY_TOKEN" \
  -H "Content-Type: application/json" \
  -d "{\"model\":\"$AI_GATEWAY_MODEL\",\"messages\":[{\"role\":\"user\",\"content\":\"Say hello in five words.\"}]}" \
  | jq -r 'if .choices then "🤖 \(.choices[0].message.content)" else "🚨 \(.error.message // .)" end'
```

```powershell title="PowerShell"
# Get a Microsoft Entra token for AI Gateway, for your own identity
$env:AI_GATEWAY_TOKEN = az account get-access-token `
  --scope https://ai.gateway.azure.com/Data.All --query accessToken -o tsv
Write-Host "👤 Token acquired: in AI_GATEWAY_TOKEN ($($env:AI_GATEWAY_TOKEN.Length) characters, not shown)"

# Build the request: the alias in model, and one user message
$body = @{
  model    = $env:AI_GATEWAY_MODEL
  messages = @(@{ role = "user"; content = "Say hello in five words." })
} | ConvertTo-Json -Depth 5

# Call the alias with the token instead of a key: your AI Gateway Models User role on the alias lets you in
$response = Invoke-RestMethod -Method Post `
  -Uri "$($env:AI_GATEWAY_URL.TrimEnd('/'))/default/models/openai/v1/chat/completions" `
  -Headers @{ Authorization = "Bearer $($env:AI_GATEWAY_TOKEN)" } `
  -ContentType "application/json" -Body $body
if ($?) { Write-Host "🤖 $($response.choices[0].message.content)" }
```

The reply is a short greeting. Your Entra identity has its own counters, separate from the `web-chat` key's.

### Check the backend identity boundary

Confirm that the Foundry account rejects keys and that only the gateway's identity has **Foundry User** on it:

```bash title="Bash"
# Check that the Foundry account rejects keys: disableLocalAuth is true when key authentication is off
echo "🔑 disableLocalAuth on the Foundry account:"
az cognitiveservices account show -g "$FOUNDRY_RG" -n "$FOUNDRY_NAME" --query properties.disableLocalAuth

# List the roles that the gateway's managed identity has on the Foundry account
echo "🔐 Roles of the gateway's identity on the Foundry account:"
az role assignment list --scope "$FOUNDRY_ID" --assignee "$AI_GATEWAY_PRINCIPAL_ID" \
  --query "[].roleDefinitionName" -o tsv
```

```powershell title="PowerShell"
# Check that the Foundry account rejects keys: disableLocalAuth is true when key authentication is off
Write-Host "🔑 disableLocalAuth on the Foundry account:"
az cognitiveservices account show -g $env:FOUNDRY_RG -n $env:FOUNDRY_NAME --query properties.disableLocalAuth

# List the roles that the gateway's managed identity has on the Foundry account
Write-Host "🔐 Roles of the gateway's identity on the Foundry account:"
az role assignment list --scope $env:FOUNDRY_ID --assignee $env:AI_GATEWAY_PRINCIPAL_ID `
  --query "[].roleDefinitionName" -o tsv
```

Expected output:

```text
🔑 disableLocalAuth on the Foundry account:
true
🔐 Roles of the gateway's identity on the Foundry account:
Foundry User
```

### Watch the traffic in Monitoring

Select **Monitoring**. After a few minutes, **Overview** shows the smoke test's calls under the `web-chat` key
and your Entra call under your identity, and **Traces** shows each request with its policy spans. Run the smoke
test a few more times if the charts are still empty.

<!-- /steps -->

> **Checkpoint**
> The smoke test passed, **Policies** shows two **Gateway** scope policies plus the model's own, a keyless
> call with your Entra token worked, the Foundry account has `disableLocalAuth` set to `true`, and
> **Monitoring** shows the traffic.

## Go further

- **Add a content safety floor.** Add a `contentSafety` entry to `baselines.json` with the shape from
  [Set gateway-wide policy baselines](../09-gateway-baselines/README.md), so MCP servers and future models get
  it too.
- **Go keyless everywhere.** Remove entries from `appNames`, move apps to Entra groups in `modelUsers` and
  `toolUsers` (`app_names`, `model_users`, and `tool_users` in Terraform), and follow
  [Go keyless with Microsoft Entra ID and RBAC](../11-entra-rbac/README.md).
- **Keep backend traffic private.** Give the gateway outbound virtual network integration, and give the
  Foundry account a private endpoint, as in
  [Lock down backend traffic with private networking](../18-private-networking/README.md). Pass the integration
  subnet to `gateway.bicep` as `backendSubnetId` or to the Terraform `gateway` module as `backend_subnet_id`, or
  add it to the running gateway with `az aigateway network update --subnet`. To keep clients off the internet
  too, add an inbound private endpoint, which is in public preview and
  [requires approval](https://ai.gateway.azure.com/docs/networking/request-private-endpoint-access), then set
  **Public network access** to **Disabled**. See
  [Reach the gateway through an inbound private endpoint](../18-private-networking/README.md#reach-the-gateway-through-an-inbound-private-endpoint)
  and [Configure inbound access](https://ai.gateway.azure.com/docs/networking/private-endpoints).
- **Protect and govern tools.** Add [Agent 365 tool threat protection](../19-tool-threat-protection/README.md)
  to sensitive MCP servers in the portal, and [govern MCP servers with Agent 365](../20-agent-365-governance/README.md).
- **Charge back by team.** Attribute tokens and cost to callers with
  [Attribute tokens and cost with OpenTelemetry](../14-otel-chargeback/README.md).

## Clean up

The Foundry model deployment, Log Analytics, and Application Insights are billed normally, so delete what you
deployed.

<!-- track: iac | Bicep -->

### Delete the resource groups

Delete both resource groups. Each command waits until the group is gone, which can take several minutes:

```bash title="Bash"
# Delete the gateway's resource group, with the gateway, its keys, and the monitoring resources
az group delete -n "$RG" --yes &&
  echo "🚮 Resource group $RG is deleted"

# Delete the resource group with the Foundry account and its model deployment
az group delete -n "$FOUNDRY_RG" --yes &&
  echo "🚮 Resource group $FOUNDRY_RG is deleted"
```

```powershell title="PowerShell"
# Delete the gateway's resource group, with the gateway, its keys, and the monitoring resources
az group delete -n $env:RG --yes
if ($?) { Write-Host "🚮 Resource group $env:RG is deleted" }

# Delete the resource group with the Foundry account and its model deployment
az group delete -n $env:FOUNDRY_RG --yes
if ($?) { Write-Host "🚮 Resource group $env:FOUNDRY_RG is deleted" }
```

### Purge the Foundry account

Deleted Foundry accounts keep soft-delete records that hold their names. To reuse the name right away, purge
it. Purging is permanent.

```bash title="Bash"
# Purge the deleted Foundry account, so that you can reuse its name right away
az cognitiveservices account purge -g "$FOUNDRY_RG" -n "$FOUNDRY_NAME" -l "$LOCATION" &&
  echo "🚮 Foundry account $FOUNDRY_NAME is purged"
```

```powershell title="PowerShell"
# Purge the deleted Foundry account, so that you can reuse its name right away
az cognitiveservices account purge -g $env:FOUNDRY_RG -n $env:FOUNDRY_NAME -l $env:LOCATION
if ($?) { Write-Host "🚮 Foundry account $env:FOUNDRY_NAME is purged" }
```

<!-- track: terraform | Terraform -->

### Delete everything Terraform created

In the lab's `terraform/` folder, with the variables from **Preview the changes** still set, delete both resource
groups and everything in them. The [`azurerm` provider](../SETUP.md#delete-what-terraform-created) also purges the
soft-deleted Foundry account. It takes about three minutes.

```bash title="Bash"
# Delete everything that terraform apply created for dev, and purge the soft-deleted Foundry account
cd ~/aigateway/labs/21-enterprise-reference/terraform &&
  terraform destroy -auto-approve -var-file dev.tfvars &&
  echo "🚮 Everything in aigw-dev-tf is deleted"
```

```powershell title="PowerShell"
# Delete everything that terraform apply created for dev, and purge the soft-deleted Foundry account
Set-Location ~/aigateway/labs/21-enterprise-reference/terraform
if ($?) { terraform destroy -auto-approve -var-file dev.tfvars }
if ($?) { Write-Host "🚮 Everything in aigw-dev-tf is deleted" }
```

The command ends with `Destroy complete! Resources: 23 destroyed.` If you moved the state to Azure Storage,
`terraform destroy` reads and updates it there.

<!-- /tracks -->

If you set up GitHub Actions, remove the deployment identity's role assignments and the app registration, then
delete the `dev` and `prod` environments in **Settings** › **Environments**:

```bash title="Bash"
# Remove the deployment identity's role assignments on the subscription
az role assignment delete --assignee "$SP_ID" --scope "/subscriptions/$SUBSCRIPTION_ID" &&
  echo "🚮 The deployment identity's role assignments are deleted"

# Delete the app registration, with its federated credentials
az ad app delete --id "$APP_ID" &&
  echo "🚮 App registration github-aigw-deploy is deleted"
```

```powershell title="PowerShell"
# Remove the deployment identity's role assignments on the subscription
az role assignment delete --assignee $env:SP_ID --scope "/subscriptions/$($env:SUBSCRIPTION_ID)"
if ($?) { Write-Host "🚮 The deployment identity's role assignments are deleted" }

# Delete the app registration, with its federated credentials
az ad app delete --id $env:APP_ID
if ($?) { Write-Host "🚮 App registration github-aigw-deploy is deleted" }
```

If you deployed prod, repeat the clean-up with the `aigw-prod` deployment's outputs. On the Terraform track, run
`terraform init -reconfigure` with the same `-backend-config` options and `key=prod.tfstate`, then
`terraform destroy -var-file prod.tfvars`. Delete the state's storage account last, after you destroy every
environment whose state it holds.

## Next steps

- Keep backend traffic off the public internet with
  [Lock down backend traffic with private networking](../18-private-networking/README.md).
- Attribute usage to teams with
  [Attribute tokens and cost with OpenTelemetry](../14-otel-chargeback/README.md).
- Govern your MCP servers across the organization with
  [Govern MCP servers with Agent 365](../20-agent-365-governance/README.md).
- Read about every policy type and scope in the [AI Gateway policies documentation](https://ai.gateway.azure.com/docs/policies).
