# Connect Azure

Step 1 of `https://infrapilot.fly/docs/onboard.md`. You create an app registration scoped to the project's resource group (or subscription), let it trust Infrapilot for this one workspace, and submit its ids. There is no secret: nothing is created, copied or stored that could leak.


## Before you start

```bash
az account show --query "{subscription_id:id, tenant_id:tenantId, name:name}" -o json
az group list --query "[].{name:name, location:location}" -o table
```

Confirm the subscription and resource group with the person. One resource group is the usual scope. You need Owner or User Access Administrator on it, and permission to register applications in the tenant.

If the spec declares workloads, the resource group must exist and its providers be registered:

```bash
az group create -n <resource group> -l <location>      # only if it does not exist yet
for ns in Microsoft.App Microsoft.ServiceBus Microsoft.Storage Microsoft.Insights Microsoft.Web \
          Microsoft.Network Microsoft.OperationalInsights Microsoft.ManagedIdentity \
          Microsoft.DBforPostgreSQL Microsoft.Cache; do
  az provider register --namespace $ns
done
```

A spec with workloads also needs the build access below instead of `Contributor`: see "Access to build".

## 1. Create the app registration and let it trust Infrapilot

```bash
SUB=<subscription id>
RG=<resource group>
APP_ID=$(az ad app create --display-name "infrapilot-agent-$RG" --query appId -o tsv)
az ad sp create --id $APP_ID

# The federated credential for this workspace, exactly as Infrapilot gives it:
curl -s $INFRAPILOT_URL/api/v1/setup -H "Authorization: Bearer $INFRAPILOT_TOKEN" \
  | jq '.connection.trust.federated_credential' > credential.json
az ad app federated-credential create --id $APP_ID --parameters credential.json

az role assignment create --assignee $APP_ID --role Contributor --scope "/subscriptions/$SUB/resourceGroups/$RG"
az role assignment create --assignee $APP_ID --role "Monitoring Reader" --scope "/subscriptions/$SUB"
```

`credential.json` holds four values: `issuer` (Infrapilot's address), `subject` (this workspace's own), `audiences` (`api://AzureADTokenExchange`) and a `name`. Don't edit them: Entra compares issuer, subject and audience exactly, case included.

**How it works:** to act, Infrapilot signs a five-minute token as that issuer with that subject, and Entra exchanges it for a one-hour access token because your app registration says it trusts exactly that pair. Infrapilot signs a workspace's subject for that workspace only, so no other Infrapilot workspace can sign in to your app, even one that names your tenant and app id. The signing key never enters the sandbox Pilot runs in.

**For level observe**, assign `Reader` instead of `Contributor`, keep `Monitoring Reader`, and submit the connection with `"access": "observe"` (step 2). Pilot then reviews the resource group and the engine refuses every change before it is attempted.

| Role | Scope | Why |
| --- | --- | --- |
| `Contributor` | the resource group | read and change resources. Cannot grant access. Includes reading what the group costs. For a spec with workloads use the narrower build access below instead. |
| `Monitoring Reader` | the subscription | read-only: Activity Log (who changed what outside Infrapilot), metrics, resource providers |

With no workloads, the person can use `Reader` plus a custom role with only these writes, for the services the fleet has:

| The fleet has | Actions |
| --- | --- |
| Container Apps | `Microsoft.App/containerApps/write`, `Microsoft.App/containerApps/listSecrets/action`, `Microsoft.App/managedEnvironments/join/action` |
| Container Apps jobs | `Microsoft.App/jobs/write`, `Microsoft.App/jobs/listSecrets/action`, `Microsoft.App/managedEnvironments/join/action` |
| Autoscale settings | `Microsoft.Insights/autoscalesettings/write` |
| App Service plans, web apps and function apps | `Microsoft.Web/serverfarms/write`, `Microsoft.Web/serverfarms/join/action`, `Microsoft.Web/sites/write` |
| Service Bus | `Microsoft.ServiceBus/namespaces/write`, `Microsoft.ServiceBus/namespaces/queues/write` |
| Cosmos DB | `Microsoft.DocumentDB/databaseAccounts/sqlDatabases/throughputSettings/write`, `Microsoft.DocumentDB/databaseAccounts/sqlDatabases/containers/throughputSettings/write` |
| Azure Cache for Redis, Azure Managed Redis | `Microsoft.Cache/redis/write`, `Microsoft.Cache/redisEnterprise/write` (used only after a person approves a change of size) |
| PostgreSQL flexible server | `Microsoft.DBforPostgreSQL/flexibleServers/write` |
| Application Gateway | `Microsoft.Network/applicationGateways/write`, `Microsoft.Network/virtualNetworks/subnets/join/action`, `Microsoft.Network/publicIPAddresses/join/action` |
| Front Door | `Microsoft.Cdn/profiles/write`, `Microsoft.Cdn/profiles/originGroups/write` |

Pilot never reads keys or data: no `listKeys` on a cache, a Cosmos DB account or a storage account is needed, and none is used.

### Access to build

When the spec declares workloads, give Pilot a custom role and one conditioned grant instead of `Contributor`. Both documents come from the setup API, filled in for this workspace:

```bash
curl -s $INFRAPILOT_URL/api/v1/setup -H "Authorization: Bearer $INFRAPILOT_TOKEN" \
  | jq '.connection.trust.build' > build.json
jq '.role' build.json > role.json
az role definition create --role-definition role.json
az role assignment create --assignee $APP_ID --role "Infrapilot build" --scope "/subscriptions/$SUB/resourceGroups/$RG"
az role assignment create --assignee $APP_ID --role "Role Based Access Control Administrator" \
  --scope "/subscriptions/$SUB/resourceGroups/$RG" \
  --condition-version 2.0 --condition "$(jq -r '.grants.condition' build.json)"
az role assignment create --assignee $APP_ID --role "Monitoring Reader" --scope "/subscriptions/$SUB"
```

| Grant | What it allows | Why |
| --- | --- | --- |
| `Infrapilot build` (custom role) on the resource group | read everything; write and delete only the resource types the blueprints create (listed under "What each workload becomes") | build the workloads, remove what a failed create left behind, and run what it built |
| the same role: `Microsoft.Network/virtualNetworks/subnets/join/action`, `Microsoft.Network/virtualNetworks/join/action`, `Microsoft.Network/privateDnsZones/join/action` | attach to the fleet's own network and private DNS zones | the environment, the database and the cache's private endpoint live in that network |
| the same role: `Microsoft.App/managedEnvironments/join/action`, `Microsoft.ManagedIdentity/userAssignedIdentities/assign/action`, `Microsoft.Cache/redisEnterprise/privateEndpointConnectionsApproval/action` | put apps in the environment, give a service its identity, connect the cache's endpoint | wiring between resources Pilot built |
| the same role: `Microsoft.App/containerApps/listSecrets/action`, `Microsoft.App/jobs/listSecrets/action`, `Microsoft.App/containerApps/listCustomHostNameAnalysis/action`, `Microsoft.OperationalInsights/workspaces/sharedKeys/action` | keep an app's secrets across a write; ask whether a domain's DNS records are in place; let Azure point a diagnostic setting at the log workspace | see "Why `listSecrets`"; the last one is asked for by Azure and never called by Pilot |
| `Role Based Access Control Administrator` with a condition, on the resource group | assign two roles and no others, to managed identities only: `Key Vault Secrets User` and `Azure Service Bus Data Receiver` | each service's identity reads the secrets its spec names and receives from its own queue |

The custom role holds no right to assign roles, read keys or touch data. The condition is enforced by Azure: an attempt to assign any other role, or to assign one to a user or group, is refused there. Pilot's engine and adapter refuse the same before anything is sent, and they also hold each assignment to a single Key Vault secret or a single queue.

If you would rather not let Pilot assign roles at all, leave the second grant out. Then either Pilot asks you to run each `az role assignment create` (it gives you the command), or you create one identity per service yourself, grant it what it needs, and name it in the workload: `spec.identity: <resource ID of the user-assigned identity>`.

**Why `listSecrets`:** Azure requires a Container App's or job's secrets on every write but never returns them on read. Right before a change, the sandbox reads them and sends them back unchanged. They stay in memory for that call only, never reach the ledger, dashboard or model, and Pilot can't set a secret's value.

### What it costs: the actual bill

Pilot reads what the resource group was billed from Azure Cost Management and shows it beside its own estimate, with the part no fleet resource explains (shared network, untagged resources). `Reader` and `Contributor` already allow that. With a custom role that leaves `Reader` out, add:

```bash
az role assignment create --assignee $APP_ID --role "Cost Management Reader" --scope "/subscriptions/$SUB/resourceGroups/$RG"
```

Nothing else needs turning on. Figures arrive 8 to 72 hours after the usage. Sponsorship and student subscriptions have no cost data in Cost Management; Pilot says so and keeps to its estimates. The fleet's share is what carries the fleet's tag (step 3).

## 2. Submit the connection

```bash
TENANT=$(az account show --query tenantId -o tsv)
curl -s -X POST $INFRAPILOT_URL/api/v1/setup/cloud \
  -H "Authorization: Bearer $INFRAPILOT_TOKEN" -H "Content-Type: application/json" \
  -d "{\"kind\": \"azure_federated\", \"tenant_id\": \"$TENANT\", \"client_id\": \"$APP_ID\",
       \"subscription_id\": \"$SUB\", \"resource_group\": \"$RG\", \"region\": \"<location, e.g. eastus>\"}"
```

`resource_group` is where Pilot finds and builds resources. Leave it out to cover the whole subscription; then grant the roles at subscription scope, and each workload's `spec` must name its group (`resourceGroup: <name>`). `region` is a short location name like `eastus`.

| Check | Needs |
| --- | --- |
| `token` | the federated credential on the app registration, unedited, and the right tenant and app id |
| `subscription read` | any role on the subscription or a group in it |
| `resource list by tag` | `Reader` (in `Contributor`) |
| `provider metadata` | the same |
| `metrics read` | `Monitoring Reader` |
| `activity log read` | `Monitoring Reader` on the subscription |

A new federated credential or role assignment can take a few minutes to work. If `token` fails with `AADSTS70021` or `subscription read` fails right after creation, wait a minute and resubmit.

## 3. Tag what Pilot should adopt

```bash
az tag update --resource-id "<resource id>" --operation Merge \
  --tags infrapilot:fleet=shop infrapilot:name=api
```

- `Merge` keeps other tags. `infrapilot:fleet` must equal `fleet` in the spec; `infrapilot:name` is the logical name.
- Autoscale settings on an adopted resource are adopted automatically as `<name>-autoscale`. Don't tag them.
- Service Bus queues can't be tagged. Tag the namespace; its queues come with it under their own names.
- A tagged web app or function app brings its App Service plan, as `<app name>-plan`.
- Cosmos DB databases and containers can't be tagged. Tag the account; the throughput of each database (`<account name>-<database>`) and container (`<account name>-<container>`) that has its own comes with it.

## What Pilot understands on Azure

Full list: `curl -s $INFRAPILOT_URL/api/types/azure`.

| Service | Type | Common objectives |
| --- | --- | --- |
| Container Apps | `Microsoft.App/containerApps` | `ResponseTime` (average, ms), `Requests`, `Requests5xx`, `Replicas` |
| Container Apps environments | `Microsoft.App/managedEnvironments` | (nothing to tune) |
| App Service plans | `Microsoft.Web/serverfarms` | `CpuPercentage`, `MemoryPercentage`, `HttpQueueLength` |
| Autoscale settings | `Microsoft.Insights/autoscalesettings` | (tuned instead of the instance count) |
| Web apps | `Microsoft.Web/sites` | `Http5xx`, `HttpResponseTime`, `Requests` |
| Function apps on Flex Consumption | `Microsoft.Web/sites` | `Http5xx`, `OnDemandFunctionExecutionCount`, `InstanceCount` |
| Container Apps jobs | `Microsoft.App/jobs` | `failed_24h`, `last_duration_s` (live, from the job's executions) |
| Cosmos DB accounts | `Microsoft.DocumentDB/databaseAccounts` | `Throttled` (requests answered 429), `NormalizedRUConsumption`; observed, not changed |
| Cosmos DB throughput | `Microsoft.DocumentDB/databaseAccounts/sqlDatabases/throughputSettings`, `Microsoft.DocumentDB/databaseAccounts/sqlDatabases/containers/throughputSettings` | `Throttled`, `NormalizedRUConsumption`, per database or container |
| Azure Cache for Redis | `Microsoft.Cache/redis` | `usedmemorypercentage`, `serverLoad`, `evictedkeys` |
| Azure Managed Redis | `Microsoft.Cache/redisEnterprise` | `usedmemorypercentage`, `percentProcessorTime`, `evictedkeys`; live `connection` |
| Service Bus queues | `Microsoft.ServiceBus/namespaces/queues` | `backlog` (live), `ActiveMessages`, `DeadletteredMessages` |
| Service Bus namespaces | `Microsoft.ServiceBus/namespaces` | (the tier its queues share) |
| PostgreSQL flexible server | `Microsoft.DBforPostgreSQL/flexibleServers` | `cpu_percent`, `memory_percent`, `storage_percent`, `active_connections`; live `connection` |
| Storage accounts | `Microsoft.Storage/storageAccounts` | observed only |
| Application Gateway | `Microsoft.Network/applicationGateways` | `ApplicationGatewayTotalTime` (average, ms), `Responses5xx`, `HealthyHostCount` |
| Front Door | `Microsoft.Cdn/profiles`, `Microsoft.Cdn/profiles/originGroups` | `TotalLatency`, `Percentage5XX`, `ByteHitRatio` |
| Managed certificates | `Microsoft.App/managedEnvironments/managedCertificates` | live `state` (Pending while Azure validates the domain) |
| What a build adds around a workload | `Microsoft.Network/virtualNetworks`, `Microsoft.OperationalInsights/workspaces`, `Microsoft.Insights/diagnosticSettings`, `Microsoft.ManagedIdentity/userAssignedIdentities`, `Microsoft.Authorization/roleAssignments`, `Microsoft.Network/privateDnsZones`, `Microsoft.Network/privateDnsZones/virtualNetworkLinks`, `Microsoft.Network/privateEndpoints`, `Microsoft.Network/privateEndpoints/privateDnsZoneGroups`, `Microsoft.Cache/redisEnterprise/databases`, `Microsoft.Cache/redisEnterprise/databases/accessPolicyAssignments`, `Microsoft.DBforPostgreSQL/flexibleServers/administrators` | observed, priced, not tuned |

The container app or web app behind a gateway or Front Door origin is linked to it, so Pilot meets a latency goal there by scaling the app. Pilot changes only probes, timeouts and autoscale limits; listeners, routes, certificates and origins stay yours.

Good to know:

- **No percentiles.** Azure Monitor has none for platform metrics; use `Average` or `Maximum`. A percentile objective is rejected.
- **Paths start at the flattened properties:** `api.template.scale.maxReplicas`, `plan.sku.capacity`.
- Other types in the group are adopted and watched, and changed only when `boundaries.manage` is `all`.
- **A Container App's `configuration` (ingress, registries, revisions mode) is watched** for outside changes like `template`, and a change shows with who made it. Secrets appear by name only; their values are never read into the graph or the ledger.
- **Cosmos DB:** the lever is the autoscale maximum (`<node>.resource.autoscaleSettings.maxThroughput`) or, without autoscale, `<node>.resource.throughput`. Raising it is online. Bound it in the intent: it sets the top of the bill.
- **Caches and database servers don't scale themselves**, and resizing one interrupts clients. Pilot proposes a change of size with the numbers; it is applied only when a person approves it, whatever the intent's level.
- **PostgreSQL, checked on a live server on 17 Nov 2026:** an update never touches the administrator login or password; storage grows only (a smaller size is refused with `DiskSizeUnsupported`); a change of compute size from B1ms to B2s took about 7 minutes, with a restart.
- **A job's schedule and trigger are yours.** Pilot tunes the replica timeout, retries, parallelism and replica size.
- **A function app is told from a web app by its `functionAppConfig`** (Flex Consumption). Its levers are `functionAppConfig.scaleAndConcurrency.maximumInstanceCount` and `instanceMemoryMB`; a web app's capacity is its plan's.
- **Plain environment variables are recorded** as part of `template`. Keep secrets in Container App secrets or Key Vault via `secretRef`.

## What each workload becomes

Declare workloads in the spec (`https://infrapilot.fly/docs/manifest.md`) and Pilot builds them into the resource group in checked transactions, what others depend on first. The kinds and their `spec` keys are the same on every cloud. On Azure:

| Kind | Becomes | Notes |
| --- | --- | --- |
| `http-service` | a Container App with HTTPS ingress, in the fleet's Container Apps environment, with its own managed identity | `cpu` and `memory_mb` are rounded up to the Consumption plan's steps: quarter vCPUs with 2 Gi each (the default is 0.5 vCPU, 1 Gi). `health_path` becomes the liveness and readiness probes. A new image that does not become ready is undone. |
| `worker` | a Container App without ingress, with its own managed identity | with `queue: <a queue workload>` it scales on that queue's length and its identity may receive from that queue and no other |
| `schedule` | a Container Apps job with a schedule trigger | with `image` it is a workload of its own; with `target: <service>` it runs that service's image, settings and identity with its own `command`, and a deploy to the service moves it too. The cron is in UTC: see below. |
| `database` | an Azure Database for PostgreSQL flexible server | `size`: `small` is Standard_B2s (Burstable, 2 vCores, 4 GiB), `medium` Standard_D2ds_v5 (General Purpose, 2 vCores, 8 GiB), `large` Standard_D4ds_v5 (4 vCores, 16 GiB). Storage is at least 32 GiB (Azure's minimum) and grows by itself. Seven days of backups. `high_availability` adds a standby in another zone and doubles the price; a Burstable server cannot have one, so `small` is then built as `medium`. |
| `cache` | an Azure Managed Redis cache with one database | the smallest Balanced size with at least `memory_gb`: B0 (0.5 GB), B1 (1), B3 (3), B5 (6), B10 (12), B20 (24), B50 (60), B100 (120); two nodes (high availability), TLS only |
| `queue` | a Service Bus namespace (Basic) and a queue | |
| `bucket` | a storage account, private | |

Around them, once per fleet: a virtual network, a Log Analytics workspace, the Container Apps environment and the setting that sends its logs to the workspace. Per database: a private DNS zone and its link to the network. Per cache: a private endpoint, its DNS zone, link and records. Per service: a user-assigned managed identity and its role assignments. Everything is tagged for the fleet and priced in the review; the network, the identities, the role assignments and the certificates cost nothing.

### What the blueprint assumes

- **The resource group is yours to fill.** Azure has no default network, so Pilot creates one small virtual network for the fleet: `10.90.0.0/16` with three subnets (the environment, the database, private endpoints). It has no gateway, no NAT, no peering and no firewall, and Pilot adds none. If that range collides with a network you need to reach, or a workload must reach another network, Pilot asks you instead of guessing.
- **A database and a cache have no public endpoint.** The server sits in the network's own subnet; the cache is reached through a private endpoint. Only what runs in the fleet's environment can connect. To load data from outside (a dump from your old provider), run the restore as a job in the fleet, or open a path yourself.
- **No password or key exists.** Azure keeps no administrator password on your behalf, and Pilot never types one, so a database Pilot builds accepts Microsoft Entra logins only, and a cache has its access keys turned off. Each service that uses them (every service, worker and schedule by default, or the names in the database's or cache's `spec.clients`) logs in as its managed identity. On the database that identity is an Entra administrator of the server, because Azure offers no narrower login through its management API; create narrower roles in SQL if you need them.
- **Deletion.** Azure has no deletion protection switch on a server. Pilot never deletes a database or a cache, and a delete by anyone through Infrapilot needs a named approver. For a lock in Azure itself: `az lock create --name keep --lock-type CanNotDelete --resource <server ID>`.
- **Schedules run in UTC.** Container Apps jobs take no time zone. With `timezone` set to anything else Pilot asks you for the cron in UTC instead of converting it, which would be wrong after the next daylight saving change.
- **Redis, not Valkey.** For `engine: valkey` Pilot asks you: Azure Managed Redis speaks the same protocol.

### Connecting a service to its database and cache

Pilot does not wire a database's or a cache's address or credentials into a service. The review shows where each one is (its `connection`: host, port, database, user, and where the credential is kept, never a value). Put the host and user in the service's `env:`. They follow from the names: `<fleet>-<database>.postgres.database.azure.com`, user `<fleet>-id-<service>`; `<fleet>-<cache>.<region>.redis.azure.net`, port 10000. The password is a Microsoft Entra token the application requests when it starts, as the identity named in the `AZURE_CLIENT_ID` variable Pilot sets on every container.

If an application must have a password or a ready-made connection string, that part is yours: enable password authentication on the server, create the connection secret in Key Vault, and reference it under the service's `secrets:`. Pilot then grants the service's identity read access to that one secret, as for any other.

### Secrets

`secrets:` maps an environment variable to a Key Vault secret URL: `STRIPE_KEY: https://<vault>.vault.azure.net/secrets/<name>`. You create the vault in the fleet's resource group, with Azure role-based access control, and put the values in. Pilot builds the service with a Key Vault reference (never a value), and gives the service's identity `Key Vault Secrets User` on exactly the secrets its spec names. Plain `env:` values are not secret by declaration: what you write in the spec is recorded with the spec. Never put a secret there.

### Custom domains

`domains: [api.example.com]` on an `http-service` (subdomains; for an apex domain Pilot asks you). Azure accepts a name only after its owner has added two DNS records, so:

1. Pilot builds the service. The review shows the records to add: a TXT record `asuid.<domain>` that proves the domain is yours, and a CNAME from the domain to the app's address.
2. You add them at your DNS provider. Until then the build is complete and the domain is reported as pending, not failed.
3. Pilot sees the records (it asks Azure, which checks them), adds the name to the app, requests a free managed certificate, waits while Azure validates it (minutes, reported as pending), and binds it. The service then answers on `https://<domain>`. Azure renews the certificate.

### Logs and deploys

Each service and job has a logs link in the dashboard: its Logs page in the Azure portal, a Log Analytics query over the fleet's workspace. `infrapilot deploy <workload> <image>` works on services, workers and schedules. A service's new revision must become ready or the deploy is undone; a job's image must be one Azure can pull, and whether it runs shows at its next execution (`failed_24h`).

## Revoking access

```bash
az ad app delete --id $APP_ID      # or remove only the trust: az ad app federated-credential delete --id $APP_ID --federated-credential-id infrapilot
```

Access ends at once; everything keeps running as left.
