Terraform on Azure
The Azure stack provisions a resource group and a VNet with compute, database and cache subnets, an Azure Database for PostgreSQL Flexible Server writer (zone-redundant by default) with a read replica on private access, an Azure Cache for Redis reached over a private endpoint and TLS only, a private storage account with Data Lake Gen2, a Key Vault holding the master key, the database password and assembled connection URLs, the Redis access key and the optional license and billing PEMs, a Log Analytics workspace, a Container Apps environment running the gateway, backend and ui apps with probes on the proxy health endpoints, a Container Apps job for the migration, and Azure Front Door Standard with HTTPS on day one and path routes that mirror the Helm ingress. A user-assigned managed identity reads the Key Vault for the apps. The shared inputs are on the Terraform overview.
cd terraform/spanway/azure/examples/default
cp terraform.tfvars.example terraform.tfvars
terraform init
terraform apply
terraform output lb_url
az must be logged in with rights to start Container Apps jobs, and the deploying principal must be able to create role assignments, since the stack grants itself Key Vault Secrets Officer to write the secrets and grants the runtime identity its data-plane roles. On a brand-new vault that first assignment can take a minute to propagate, so a 403 on the secret writes is fixed by applying again. Container Apps also creates a platform-managed resource group named <tenant>-spanway-<env>-infra next to the stack's own.
A real-world scenario
A platform team wants a production gateway on Azure with a managed database, cache and object store, created and changed through code review like the rest of their infrastructure. They run the stack from a CI runner that has the az CLI, review the plan, apply it, and sign in to the Admin UI at the load balancer URL.
Steps
-
Authenticate the
azCLI on the machine that runs Terraform, since the stack runs the migration through it. -
Run
terraform initandterraform applywith your inputs, as in the commands above. -
Read the URL and check the gateway.
curl "$(terraform output -raw lb_url)/health/readiness" -
Open the URL followed by
/uiand sign in asadminwith the master key from the secret store the stack used.
Expected result
terraform apply finishes after the migration task, /health/readiness reports the database as connected, and the Admin UI opens at the load balancer URL.
Inputs
Naming, network and domains
| Input | Default | What it does |
|---|---|---|
location | eastus | |
tenant, env | required | Resource name prefix |
tags | {} | |
vnet_cidr | 10.40.0.0/16 | |
lb_domains | [] | Custom domains on Front Door. Create the CNAME and _dnsauth TXT records from the outputs, then set this and apply again |
log_retention_days | 30 | Log Analytics retention |
Images and sizing
| Input | Default | What it does |
|---|---|---|
image_registry, image_tag | registry.spanway.ai, a pinned release tag | Compose the four image references. The images are private during the preview and the module passes no registry credentials, so the defaults do not pull. Mirror the four images into a private registry, such as Azure Container Registry, and point image_registry at it. The module's Container Apps have no registry block, so pulls from a private registry also need an edit in the module's container_apps.tf, described in Pull from a private registry. The registry address and pull credentials for the mirror step are in your onboarding pack. Override per component with gateway_image, backend_image, ui_image and migrations_image |
gateway_cpu, gateway_memory | 2, 4Gi | vCPU count and memory string |
backend_cpu, backend_memory | 1, 2Gi | |
ui_cpu, ui_memory | 0.25, 0.5Gi | |
gateway_min_replicas, gateway_max_replicas, gateway_concurrent_requests | 1, 10, 80 | Container Apps scaling. Lower the concurrency for long LLM streams |
backend_min_replicas, backend_max_replicas, backend_concurrent_requests | 1, 4, 80 | |
ui_min_replicas, ui_max_replicas, ui_concurrent_requests | 1, 3, 200 | |
gateway_num_workers | 1 | |
gateway_connection_pool_enabled, gateway_pool_max_db_connections, gateway_pool_max_client_conn | false, 20, 1000 |
Database and Redis
| Input | Default | What it does |
|---|---|---|
db_sku_name | GP_Standard_D2ds_v5 | Flexible Server SKU |
db_version | 16 | |
db_storage_mb | 32768 | |
db_high_availability_mode | ZoneRedundant | SameZone, or empty for a single instance |
db_name, db_username | spanway, spanway_app | The application user is the server administrator login |
redis_sku_name, redis_family, redis_capacity | Standard, C, 1 |
Secrets, observability and metering
| Input | Default | What it does |
|---|---|---|
gateway_extra_secrets, backend_extra_secrets | {} | Key Vault secret URIs, read by the runtime identity |
extra_secret_key_vault_ids | [] | Vaults other than the stack's own that hold those URIs. The identity is granted Key Vault Secrets User on each |
otel_endpoint, otel_exporter, otel_headers_secret, otel_environment_name, otel_capture_message_content | "", otlp_http, "", "", no_content | otel_headers_secret is a Key Vault secret URI |
billing_metrics_endpoint, billing_metrics_client_cert_pem, billing_metrics_client_key_pem, billing_metrics_ca_cert_pem | "" | The PEMs are stored in Key Vault |
collector_enabled, collector_port, collector_cpu, collector_memory, collector_buffer_size, collector_on_unavailable, collector_drain_timeout_seconds | false, 4010, 1, 2Gi, 1000, fallback, 10 |
There is no Prometheus sidecar input on Azure, because a Container App exposes one ingress port and /metrics stays on the gateway port. The proxy_config map is stored as a Container Apps secret named proxy-config and mounted at /etc/spanway/proxy-config, with a hash of it in the environment so an edit rolls a new revision. There is no force-destroy or deletion-protection input either, since Key Vault soft delete and Flexible Server automated backups cover both.
Workflow workers
| Input | Default | What it does |
|---|---|---|
workflow_worker_enabled | false | Adds a Container App named <name>-worker that runs workflow runner steps and makes the gateway and backend producers. Needs the workflow_runner and workflow_queue_workers license features |
workflow_worker_min_replicas, workflow_worker_max_replicas, workflow_worker_cpu_target | 2, 10, 70 | Replica bounds and the CPU scale rule. The minimum is at least 1 because nothing wakes a worker |
workflow_worker_cpu, workflow_worker_memory | 1, 2Gi | A Consumption pair |
workflow_worker_drain_seconds | 90 | How long a stopping worker keeps running its steps. The replica gets thirty seconds more, within the 600 second limit |
workflow_worker_extra_env | {} | Extra env vars for the worker |
The worker app has no ingress block, so nothing can reach it.
Pull from a private registry
Container Apps pull public images without any setup, but a private registry needs a registry block on each app, and the module does not add one. Until it does, edit container_apps.tf in your copy of the module before you apply.
- Grant the runtime identity (
azurerm_user_assigned_identity.runtime) theAcrPullrole on your Azure Container Registry. - Add
registry { server = "<name>.azurecr.io", identity = azurerm_user_assigned_identity.runtime.id }to thegatewayandbackendapps and themigrationsjob incontainer_apps.tf, and to theworkflow_workerapp inworkflow_worker.tfwhen you run workers. Theuiapp has no identity, so give it the username and password form from the next step, or add the runtime identity to it first. - For a registry that takes a username and password instead, add the password as a
secretblock on each app and useregistry { server = "<server>", username = "<user>", password_secret_name = "<secret name>" }. - Set
image_registryto the registry address and runterraform plan. The plan shows an in-place update of each app and job you edited.
Database authentication and migration
The stack uses password authentication. The Flexible Server administrator login is the application user, its random password is stored in Key Vault as db-password, and Terraform assembles DATABASE_URL and DATABASE_URL_READ_REPLICA with sslmode=require and stores them as Key Vault secrets. The gateway, the backend and the migration job read them as Key Vault references through the runtime identity. The migration runs as the spanway-migrations Container Apps job, triggered by bootstrap.tf during apply with az containerapp job start and polled until it finishes, and the apps wait for it.
TLS and custom domains
Front Door terminates TLS on its default *.azurefd.net hostname with a managed certificate and redirects HTTP to HTTPS, so there is no plaintext mode. For your own name, apply once, create a CNAME to front_door_hostname and a TXT record at _dnsauth.<domain> with the token from custom_domain_validation_tokens, then set lb_domains and apply again. The Container Apps keep their own public hostnames, protected by the same master key and virtual key authentication as any public ingress. Front Door's origin timeout is set to its 240-second maximum, which streaming responses keep alive while bytes flow.
Outputs
| Output | What it is |
|---|---|
front_door_hostname, lb_url | The default endpoint and the proxy URL, which switches to the first custom domain once set |
custom_domain_validation_tokens | Per-domain TXT record values |
gateway_fqdn, backend_fqdn, ui_fqdn | Direct Container Apps hostnames |
resource_group | The stack's resource group |
postgres_writer_fqdn, postgres_reader_fqdn, db_username, db_name | Database connection details |
redis_host, redis_port, redis_endpoint | Private endpoint details |
storage_account, storage_container | Exposed as AZURE_STORAGE_ACCOUNT_NAME and AZURE_STORAGE_FILE_SYSTEM |
key_vault_id, master_key_secret_id, db_password_secret_id | Where the secrets live. Read the master key with az keyvault secret show --id <uri> --query value -o tsv |
runtime_identity_principal_id, runtime_identity_client_id | The managed identity, exported to the containers as AZURE_CLIENT_ID |
migration_run_command | The az containerapp job start command that re-runs the migration |
Errors
| What you see | What it means | Fix |
|---|---|---|
local-exec fails with a missing command | The az CLI is not installed or not signed in where Terraform runs. | Install and authenticate it, or run the migration_run_command output by hand. |
| An app revision fails with an image pull error | The images are in a private registry and the apps have no registry block. | Follow Pull from a private registry. |
| The services never become healthy | The migration did not run, so the schema is missing. | Run terraform output migration_run_command and execute it. |
| The load balancer answers 502 or 503 | The gateway tasks are still starting or failing their health check. | Read the gateway logs in the cloud console. |
Logs
The Container Apps environment sends each app's output to its Log Analytics workspace. Open the workspace, choose Logs, and query ContainerAppConsoleLogs_CL for the gateway, backend or ui app, or open the <tenant>-spanway-<env>-migrations job and its Execution history for a migration run. A successful migration ends with Migration job completed successfully., and a failed one with Migration job failed after retries. after the Prisma error, as the log reference explains.
Related
- Terraform overview for the inputs every stack shares.
- Terraform provider to manage keys and models as code afterwards.
- Container images.