Skip to content

Add Terraform samples for AI Gateway - #1202

Open
saanikaguptamicrosoft wants to merge 4 commits into
mainfrom
saanika/terraform-ai-gateway
Open

saanikaguptamicrosoft wants to merge 4 commits into
mainfrom
saanika/terraform-ai-gateway

Conversation

@saanikaguptamicrosoft

@saanikaguptamicrosoft saanikaguptamicrosoft commented Nov 27, 2026 •

Copy link
Copy Markdown
Contributor

What changed

Adds Terraform samples for AI Gateway, the Terraform counterparts of the Bicep AI Gateway tier sample
(infrastructure-setup-bicep/01-connections/ai-gateway-tier). New files only (36 files in three new folders);
no existing files change.

infrastructure/infrastructure-setup-terraform/
├── golden-path/README.md                 Terraform edition of the Foundry golden path
├── 01-connections/ai-gateway-tier/       Public path (hub + spoke)
│   ├── modules/ai-gateway/               gateway + Foundry User grant + MI provider + model (token limit) + alias + runtime key
│   ├── modules/ai-gateway-connection/    ModelGateway "Admin-connected models" connection
│   ├── hub/                              run once: Foundry account + model + hub project + gateway
│   └── connection/                       run per project: reads gateway host + key, creates the connection
└── 16-private-network-standard-agent-apim-setup-preview/extensions/ai-gateway-tier-private/
    └── code/                             one apply: private standard-agent foundation + private model account
                                          + VNet-integrated gateway + connection (reuses the modules)

The folders mirror the Bicep AI Gateway samples, and the golden-path README maps the same six steps to
Terraform: 41-standard-agent-setup for the account and project, these samples for the gateway and model
connection, and the existing public-byom-apim/samples/create-agent.py for the agent.

Why

There were no Terraform samples for AI Gateway. These use the Microsoft.ApiManagement/aigateways resource
type, because new Microsoft.ApiManagement/service + AIGateway SKU resources can no longer be created
(migration guide). Resource shapes and the
2025-09-01-preview API version follow the official AI Gateway labs.
Compared with the earlier service + AIGateway SKU form:

  • The runtime host comes from properties.frontend.defaultHostname (*.ai.gateway.azure.com).
  • The callable model name is an explicit alias.
  • The gateway's outbound (private routing) subnet is delegated to Microsoft.App/environments.
  • Keys are sent as Authorization: Bearer <key>; a request with both api-key and Authorization gets HTTP 400.

Design points:

  • The gateway key is read with an ephemeral listSecrets and sent as a write-only connection
    credential, so it is never stored in Terraform state (Terraform ≥ 1.11).
  • The connection/ root reads the gateway's runtime host and key itself, so there's no key copy-paste, and it
    works for a project in another subscription.
  • terraform destroy purges the soft-deleted Foundry accounts, so names and model quota are released immediately.
  • assign_foundry_user_role = false supports organizations where an administrator grants the gateway
    identity's Foundry User role separately (steps in the README).
  • The connection's auth header is configurable (auth_header_name / auth_header_format); the default is
    Authorization: Bearer {api_key}.

Security

  • No credentials in the repo; the gateway key never enters Terraform state. The gateway runtime key is read
    with an ephemeral listSecrets and sent to the Foundry connection as a write-only value; example .tfvars
    files contain only placeholders. All 36 files were scanned for keys, tokens, connection strings, private keys,
    emails, public IPs, and environment-specific identifiers: none found.
  • Terraform state still holds Storage and Cosmos DB keys. The azurerm provider always records these account
    keys in state (as in the other Terraform samples), but both services have key auth disabled here, so the keys
    can't access data. Treat state as sensitive anyway: use a secured remote backend (the backend "azurerm" {}
    block in versions.tf).
  • Keyless. Every account and data store has local / API-key auth disabled: both Foundry accounts, AI Search,
    Cosmos DB, and Storage (shared keys). Access is Entra ID + RBAC only; verified live, the agent account refuses
    to list keys.
  • Private by default (VNet sample). The model account and all data stores have public network access disabled
    and are reachable only through private endpoints; the gateway reaches the model over its VNet integration.
    AI Gateway's inbound endpoint is public (it doesn't support inbound private endpoints yet) and requires the
    runtime key.
  • Testing switches (foundry_allowed_ip_ranges, foundry_public_network_access_enabled) are off by default,
    mutually exclusive, and still require Entra ID.
  • Supply chain. No workflows or package manifests are added. The READMEs pin the agent-step Python packages
    to the tested versions (azure-ai-projects==2.11.0, azure-identity==1.27.0).

Notes for reviewers

  • Review feedback: the three Copilot review comments (AI Search local auth, Storage data-plane reads, and
    the testing-switch precedence) are addressed in 2f4554f; see each thread. The same commit also disables API
    keys on the agent's Foundry account and the Storage account's public endpoint.
    The two later comments (project endpoint subdomain, role grant on gateway recreate) are addressed in 3bc7d95
    and verified live on the public path, including terraform apply -replace of the gateway.
  • API version: the gateway and its child resources use 2025-09-01-preview, as in the official AI Gateway
    labs. The Bicep sample in this repo uses 2026-11-01 for the gateway and 2026-09-01-preview for its
    children. Azure Resource Manager still accepts all of them (re-checked 2026-11-27).
  • Region: the Terraform samples create their resource group, so location is an explicit variable, as in
    the other Terraform samples (default eastus2 for the hub, swedencentral for the private sample). They
    don't inherit the resource group's region the way the Bicep samples do since Samples inherit resource group instead of defaulting to eastus2 #1183.
  • No file overlap with Add Terraform for APIM and model gateway connections, plus Azure OpenAI, Foundry, Cosmos DB, and Bing snippets #1198, which adds other Terraform under 01-connections/ (apim/,
    model-gateway/) and edits 01-connections/README.md; this PR doesn't touch that README.

Validation

Static checks on the latest main (2026-11-27) for all three roots (hub/, connection/, private code/),
with Terraform 1.17.2, azapi 2.14.0, and azurerm 4.81.0:

  • terraform fmt -recursive -check — passed
  • terraform init -backend=false and terraform validate — passed
  • terraform plan — passed: hub/ 13 resources, private code/ 58 resources
  • plan with both testing switches set — fails with the intended validation error; with either one alone — passes
  • Relative links and script paths in the three READMEs — all 39 resolve
  • Azure Resource Manager still offers every API version the samples use (including
    Microsoft.ApiManagement/aigateways@2025-09-01-preview)

Live, private VNet sample after the security hardening (2026-11-27, Sweden Central):

  • terraform apply — passed: 58 resources in one apply, capability host Succeeded.
  • Verified in Azure: AI Search disableLocalAuth: true (no authOptions) and public access disabled; Storage
    public access disabled and shared keys off; Cosmos DB local auth off and public access disabled; model (hub)
    account keys off and public access disabled; agent account keys off (listKeys is refused).
  • A second terraform plan — No changes.
  • Direct POST <gateway>/default/models/openai/v1/chat/completions with Authorization: Bearer — returned a
    gpt-5.4 completion from the private model.
  • infrastructure-setup-bicep/01-connections/public-byom-apim/samples/create-agent.py --model ai-gateway/gpt-5.4
    (prompt agent, Responses API, Entra ID only) — answered on the first attempt through the agent data proxy →
    gateway → private model.
  • terraform destroy — removed every resource the sample created and purged both soft-deleted Foundry accounts. Only the resource group delete stopped, on NSGs that a tenant Azure Policy had added (not created by Terraform); after deleting the group, nothing from the test remains.

Live, public hub-and-spoke path (2026-11-18, East US 2; unchanged since apart from the README install line):

  • terraform apply in hub/ — passed (13 resources, about 3.5 minutes); a second terraform plan reports
    No changes.
  • terraform apply in connection/ — passed; a second plan reports No changes; the gateway key is not
    present in Terraform state.
  • Direct gateway call with Authorization: Bearer — returned a gpt-5.4 completion; a burst of requests returned
    HTTP 429 "Token limit is exceeded"; a request with both api-key and Authorization returned HTTP 400.
  • create-agent.py --model ai-gateway/gpt-5.4 — passed.
  • terraform destroy for both roots — passed; nothing left behind, account purged.

Fixes from the earlier live runs are included: the connection ignores the isSharedToAll read-back (so a second
plan shows no drift), the gateway subnet's NSG rules are standalone resources (so policy-injected rules don't
cause drift), and connection operations retry on transient etag conflicts.

Not checked: a spoke project in a different subscription from the hub (same code path, using absolute resource
IDs).

Copilot AI balanced review requested due to automatic review settings November 27, 2026 08:28

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

Search API-key authentication undermines the advertised Entra-only boundary, while default Storage data-plane reads can cause workstation Terraform applies to fail with HTTP 403.

3 open issues
What changed in this PR

Adds Terraform counterparts to the Bicep AI Gateway samples, integrating public hub-and-spoke and private-backend deployments into the Foundry golden path.

Changes:

  • Adds reusable gateway and project-connection modules, with separate public hub and spoke deployment roots.
  • Adds a self-contained private-network sample with agent infrastructure, private model access, and gateway integration.
  • Documents deployment, agent creation, permissions, testing, and cleanup.

Paths are relative to infrastructure/infrastructure-setup-terraform/.

File Description
golden-path/​README.md Maps the Foundry workflow to Terraform samples.
16-private-network-standard-agent-apim-setup-preview/​extensions/​ai-gateway-tier-private/​README.md Documents the private-network deployment and usage.
16-private-network-standard-agent-apim-setup-preview/​extensions/​ai-gateway-tier-private/​code/​versions.tf Declares Terraform and provider requirements.
16-private-network-standard-agent-apim-setup-preview/​extensions/​ai-gateway-tier-private/​code/​variables.tf Defines networking, model, and gateway inputs.
16-private-network-standard-agent-apim-setup-preview/​extensions/​ai-gateway-tier-private/​code/​terraform.tfvars.example Provides private deployment configuration examples.
16-private-network-standard-agent-apim-setup-preview/​extensions/​ai-gateway-tier-private/​code/​purge.tf Adds account purging and subnet-release cooldown.
16-private-network-standard-agent-apim-setup-preview/​extensions/​ai-gateway-tier-private/​code/​providers.tf Configures Azure providers and Storage authentication.
16-private-network-standard-agent-apim-setup-preview/​extensions/​ai-gateway-tier-private/​code/​outputs.tf Exposes project and gateway connection details.
16-private-network-standard-agent-apim-setup-preview/​extensions/​ai-gateway-tier-private/​code/​network.tf Creates the VNet and foundation subnets.
16-private-network-standard-agent-apim-setup-preview/​extensions/​ai-gateway-tier-private/​code/​main.tf Establishes resource naming and the resource group.
16-private-network-standard-agent-apim-setup-preview/​extensions/​ai-gateway-tier-private/​code/​gateway.tf Deploys the private model backend and integrated gateway.
16-private-network-standard-agent-apim-setup-preview/​extensions/​ai-gateway-tier-private/​code/​foundry.tf Creates the agent project, connections, roles, and runtime.
16-private-network-standard-agent-apim-setup-preview/​extensions/​ai-gateway-tier-private/​code/​dns.tf Configures private DNS and private endpoints.
16-private-network-standard-agent-apim-setup-preview/​extensions/​ai-gateway-tier-private/​code/​data-stores.tf Creates agent Storage, Cosmos DB, and AI Search resources.
01-connections/​ai-gateway-tier/​README.md Documents hub-and-spoke deployment and gateway testing.
01-connections/​ai-gateway-tier/​modules/​ai-gateway/​versions.tf Declares gateway module provider requirements.
01-connections/​ai-gateway-tier/​modules/​ai-gateway/​variables.tf Defines gateway, backend, and policy inputs.
01-connections/​ai-gateway-tier/​modules/​ai-gateway/​outputs.tf Exposes gateway identifiers, endpoints, and alias details.
01-connections/​ai-gateway-tier/​modules/​ai-gateway/​main.tf Creates the gateway, identity grant, model, alias, and key.
01-connections/​ai-gateway-tier/​modules/​ai-gateway-connection/​versions.tf Declares connection module requirements.
01-connections/​ai-gateway-tier/​modules/​ai-gateway-connection/​variables.tf Defines connection metadata and ephemeral credential inputs.
01-connections/​ai-gateway-tier/​modules/​ai-gateway-connection/​outputs.tf Exposes the connection and agent model reference.
01-connections/​ai-gateway-tier/​modules/​ai-gateway-connection/​main.tf Creates a ModelGateway connection with write-only credentials.
01-connections/​ai-gateway-tier/​hub/​versions.tf Declares public hub deployment requirements.
01-connections/​ai-gateway-tier/​hub/​variables.tf Defines hub resource and model settings.
01-connections/​ai-gateway-tier/​hub/​terraform.tfvars.example Provides example hub configuration.
01-connections/​ai-gateway-tier/​hub/​purge.tf Adds optional destroy-time account purging.
01-connections/​ai-gateway-tier/​hub/​providers.tf Configures the hub subscription provider.
01-connections/​ai-gateway-tier/​hub/​outputs.tf Exposes values needed by spoke deployments.
01-connections/​ai-gateway-tier/​hub/​main.tf Deploys the public Foundry account, model, project, and gateway.
01-connections/​ai-gateway-tier/​connection/​versions.tf Declares spoke deployment requirements.
01-connections/​ai-gateway-tier/​connection/​variables.tf Defines and validates spoke connection inputs.
01-connections/​ai-gateway-tier/​connection/​terraform.tfvars.example Provides example spoke configuration.
01-connections/​ai-gateway-tier/​connection/​providers.tf Configures the spoke subscription provider.
01-connections/​ai-gateway-tier/​connection/​outputs.tf Exposes SDK endpoint and model-reference values.
01-connections/​ai-gateway-tier/​connection/​main.tf Reads the gateway endpoint and ephemeral key to attach a project.

Review effort: Balanced

Terraform counterparts of the Bicep AI Gateway tier samples, built on the
Microsoft.ApiManagement/aigateways resource type.

- 01-connections/ai-gateway-tier: shared ai-gateway and
  ai-gateway-connection modules, a hub/ root (run once) and a connection/
  root (run per spoke project).
- 16-private-network-standard-agent-apim-setup-preview/extensions/
  ai-gateway-tier-private: self-contained network-secured variant (private
  standard-agent foundation + private model account + VNet-integrated
  gateway + connection) that reuses the same modules.
- golden-path/README.md: Terraform edition of the Foundry golden path.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
- AI Search: disable local (API key) auth so access is Entra ID only,
  governed by the project identity's Search RBAC roles.
- Agent Foundry account: disable local auth (Entra ID only), matching the
  private hub account.
- Storage: disable the public endpoint (private endpoint only) and set the
  azurerm storage.data_plane_available = false feature so plan and apply
  don't need data-plane access from outside the VNet.
- Make foundry_allowed_ip_ranges and foundry_public_network_access_enabled
  mutually exclusive (validation error instead of an ambiguous setting).
- READMEs: document the hardening and pin the agent-step Python packages to
  the tested versions.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
@saanikaguptamicrosoft
saanikaguptamicrosoft force-pushed the saanika/terraform-ai-gateway branch from 6f2d086 to 2f4554f Compare November 27, 2026 09:32
Copilot AI balanced review requested due to automatic review settings November 27, 2026 09:32

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

The endpoint output can point to the wrong hostname when the custom subdomain differs from the account name, and recreating the gateway can fail to restore backend access because the role assignment does not accommodate a changed principal ID.

2 open issues
3 resolved since last review

Review effort: Balanced

- ai-gateway-connection: build project_endpoint from the account's
  customSubDomainName instead of its ARM name, which can differ (for example
  when a sample adds a random suffix to the subdomain only).
- ai-gateway: include the gateway's principal ID in the Foundry User role
  assignment name, so recreating the gateway (new identity) replaces the
  grant instead of attempting an in-place update Azure doesn't allow.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Copilot AI balanced review requested due to automatic review settings November 27, 2026 10:53

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

Storage and Cosmos DB account keys remain in Terraform state, violating the no-credentials guarantee, while valid mixed-case project IDs can also break endpoint resolution.

1 open issue
1 previously missed issue

In code that hasn't changed since last review

High severity Storage and Cosmos DB keys remain in Terraform state

infrastructure/​infrastructure-setup-terraform/​16-private-network-standard-agent-apim-setup-preview/​extensions/​ai-gateway-tier-private/​code/​data-stores.tf:5

AzureRM's Storage credential handling and Cosmos DB read path persist account keys in Terraform state even when shared-key/local authentication is disabled; the Cosmos DB resource at line 25 has the same issue. This contradicts the PR's “no credentials in Terraform state” guarantee, and disabling optional Storage data-plane reads does not prevent these management-plane key reads. Manage both accounts through AzAPI with non-secret exports and update their consumers, or narrow the guarantee and document that state needs credential-level protection.

2 resolved since last review

Review effort: Balanced

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Copilot AI balanced review requested due to automatic review settings November 27, 2026 11:04
@saanikaguptamicrosoft

Copy link
Copy Markdown
Contributor Author

On the review summary's "Storage and Cosmos DB keys remain in Terraform state": correct, and the PR description's Security section is now worded precisely. The gateway runtime key never enters state (ephemeral read + write-only connection credential). The azurerm provider always records Storage and Cosmos DB account keys in state, as in the other Terraform samples; in this sample both services have key auth disabled (shared_access_key_enabled = false, local_authentication_enabled = false, verified live), so those keys cannot access data. The README's remote-backend guidance (backend "azurerm" {} in versions.tf) covers protecting state. Leaving the providers as-is to stay consistent with the existing Terraform samples.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Needs a closer look

Human assessment is needed to evaluate a credential-refresh gap that can leave gateway connections using deleted keys and cause authentication failures.

No open issues 🎉

1 resolved since last review

Review effort: Balanced

This branch was successfully deployed

1 active deployment
L4-validation — 5e3c7a1f Deployed Nov 27, 2026 by saanikaguptamicrosoft via trusted #1091
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants