Skip to main content

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​

  1. Authenticate the az CLI on the machine that runs Terraform, since the stack runs the migration through it.

  2. Run terraform init and terraform apply with your inputs, as in the commands above.

  3. Read the URL and check the gateway.

    curl "$(terraform output -raw lb_url)/health/readiness"
  4. Open the URL followed by /ui and sign in as admin with 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​

InputDefaultWhat it does
locationeastus
tenant, envrequiredResource name prefix
tags{}
vnet_cidr10.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_days30Log Analytics retention

Images and sizing​

InputDefaultWhat it does
image_registry, image_tagregistry.spanway.ai, a pinned release tagCompose 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_memory2, 4GivCPU count and memory string
backend_cpu, backend_memory1, 2Gi
ui_cpu, ui_memory0.25, 0.5Gi
gateway_min_replicas, gateway_max_replicas, gateway_concurrent_requests1, 10, 80Container Apps scaling. Lower the concurrency for long LLM streams
backend_min_replicas, backend_max_replicas, backend_concurrent_requests1, 4, 80
ui_min_replicas, ui_max_replicas, ui_concurrent_requests1, 3, 200
gateway_num_workers1
gateway_connection_pool_enabled, gateway_pool_max_db_connections, gateway_pool_max_client_connfalse, 20, 1000

Database and Redis​

InputDefaultWhat it does
db_sku_nameGP_Standard_D2ds_v5Flexible Server SKU
db_version16
db_storage_mb32768
db_high_availability_modeZoneRedundantSameZone, or empty for a single instance
db_name, db_usernamespanway, spanway_appThe application user is the server administrator login
redis_sku_name, redis_family, redis_capacityStandard, C, 1

Secrets, observability and metering​

InputDefaultWhat 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_contentotel_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_secondsfalse, 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​

InputDefaultWhat it does
workflow_worker_enabledfalseAdds 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_target2, 10, 70Replica bounds and the CPU scale rule. The minimum is at least 1 because nothing wakes a worker
workflow_worker_cpu, workflow_worker_memory1, 2GiA Consumption pair
workflow_worker_drain_seconds90How 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.

  1. Grant the runtime identity (azurerm_user_assigned_identity.runtime) the AcrPull role on your Azure Container Registry.
  2. Add registry { server = "<name>.azurecr.io", identity = azurerm_user_assigned_identity.runtime.id } to the gateway and backend apps and the migrations job in container_apps.tf, and to the workflow_worker app in workflow_worker.tf when you run workers. The ui app has no identity, so give it the username and password form from the next step, or add the runtime identity to it first.
  3. For a registry that takes a username and password instead, add the password as a secret block on each app and use registry { server = "<server>", username = "<user>", password_secret_name = "<secret name>" }.
  4. Set image_registry to the registry address and run terraform 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​

OutputWhat it is
front_door_hostname, lb_urlThe default endpoint and the proxy URL, which switches to the first custom domain once set
custom_domain_validation_tokensPer-domain TXT record values
gateway_fqdn, backend_fqdn, ui_fqdnDirect Container Apps hostnames
resource_groupThe stack's resource group
postgres_writer_fqdn, postgres_reader_fqdn, db_username, db_nameDatabase connection details
redis_host, redis_port, redis_endpointPrivate endpoint details
storage_account, storage_containerExposed as AZURE_STORAGE_ACCOUNT_NAME and AZURE_STORAGE_FILE_SYSTEM
key_vault_id, master_key_secret_id, db_password_secret_idWhere 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_idThe managed identity, exported to the containers as AZURE_CLIENT_ID
migration_run_commandThe az containerapp job start command that re-runs the migration

Errors​

What you seeWhat it meansFix
local-exec fails with a missing commandThe 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 errorThe images are in a private registry and the apps have no registry block.Follow Pull from a private registry.
The services never become healthyThe migration did not run, so the schema is missing.Run terraform output migration_run_command and execute it.
The load balancer answers 502 or 503The 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.