Platform · Customer onboarding

Subscription Factory: Customer Onboarding That Starts by Minting Subscriptions

The customer chain provisions isolated lower and upper environments, creating cloud subscriptions first because every other resource needs their ids.

  • Terraform
  • Azure
  • AKS
  • Istio
  • Vault
  • Apps Script
  • GitHub Actions
  • Python

// Why this matters

A Terraform Azure subscription factory is the right foundation when customers must be isolated from each other at the billing, policy and blast-radius level. A subscription is the strongest isolation boundary the cloud offers short of a separate tenant: its own quotas, its own role assignments, its own cost view, and a clean unit to delete at offboarding.

The engineering reason to automate it is ordering. Every other resource (network, cluster, identities, storage) needs a subscription id, and subscriptions are slow, tenant-global objects that cannot be rolled back with a normal terraform destroy without cancelling real billing entities. Get this stage wrong and everything built on top of it is wrong.

This is the customer variant of the pipeline in From Form to Running Cluster: Self-Service Team Onboarding. It differs mainly in that it starts by minting the subscriptions, in how it treats existing ones, and in its stricter handling of HA regions.

// The problem

Each customer needs isolated lower and upper environments, plus consistent networking and Kubernetes inside them. If subscription creation is a manual portal step, the id has to be copied into configuration by hand, naming is inconsistent, and the management-group placement (which applies policy and cost rules) is forgotten for the one customer that matters.

Terraform makes subscription lifecycle sharp-edged. Destroying a subscription resource cancels the subscription, which is irreversible in practice and deletes the ids downstream roots rely on. A run that targets only one environment of a customer who has both sees the other environment as removed from configuration and plans exactly that cancellation. This is a normal operator mistake, not an exotic one.

Migration adds a third wrinkle. Some customers already have a subscription that Terraform did not create, or whose alias in state points at a different (empty) subscription. You cannot recreate them, and you cannot manage them without bringing them under state with the management-group association intact. There is also an ownership caveat: whoever deploys a subscription first becomes its Owner, and a subscription created manually cannot be cleaned up by the pipeline identity.

// The solution

The factory is a Terraform root, subscriptions-creation, that wraps a small module. The module declares an azurerm_subscription per environment (count-gated by an environment input), a management-group association per subscription, and outputs for id and name. The root writes subscription_id, subscription_name and management_group_id for each environment into Vault, so downstream roots get everything through the same Vault read they use for all other configuration (see Vault as the Control Plane: A Five-Tier Key Model with Locking).

Safety comes from two decisions. One state holds both environments for a customer, keyed by customer name. And both subscription resources carry lifecycle { prevent_destroy = true }. Together they mean a lower-only dispatch for a customer with both environments fails at plan time with a prevent_destroy error instead of cancelling the upper subscription. The runbook says to dispatch both for any customer that has both.

Adoption is an explicit map. A local existing_subscriptions keyed by customer name and environment holds subscription ids that already exist. When set, the module passes the id to the alias, which makes Terraform adopt it instead of creating one under the billing scope, and an imports.tf import block pulls in the existing management-group association. The adopted alias is distinct (suffixed -adopted) because alias names are tenant-unique and the plain name may still point at another subscription. Before the first run the old resources are removed from state with terraform state rm.

After subscriptions, the workflow triggers onboarding natively. A prepare job reads the ids; lower and upper deploy in parallel; each builds a VNet peered to a hub (hub-and-spoke), subnets, a cluster with mesh, and managed identities; a post-apply job configures the mesh gateway and internal load balancer per cluster. HA customers add a second region, a second cluster and cross-region peering. I rejected one-subscription-for-both-environments (weak isolation and cost separation) and creating subscriptions inside each environment root (circular: the root needs the subscription it is creating).

How it flows flow1. Form and Apps Script → 2. Populate Vault → 3. Create subscriptions → 4. Trigger onboarding → 5. Prepare → 6. Deploy lower and upper → 7. Branch: HA → 8. Configure cluster01Form and Apps Script02Populate Vault03Create subscriptions04Trigger onboarding05Prepare06Deploy lower and upper07 · GATEBranch: HA08Configure cluster
How it flows. End-to-end flow. Dashed pink nodes are gates: points where a human or a check must pass before the next stage runs.
  1. Form and Apps Scriptresponses transposed and pushed as a CSV
  2. Populate Vaultstandard defaults then CSV overwrite; CSV archived with a timestamp
  3. Create subscriptionsone Terraform state for both environments; ids stored in Vault
  4. Trigger onboardingcalled natively with customer and environment
  5. Prepareresolve environments and fetch subscription ids
  6. Deploy lower and uppernetwork with hub peering, subnets, cluster with mesh, managed identity (parallel)
  7. Branch: HA gateHA customers get two regions, two clusters and cross-region peering
  8. Configure clusterper-cluster gateway and internal load balancer
Parent workflowSubscription rootVaultOnboardingstandard defaults, then CSV overwrite, archive CSVapply for lower, upper or bothwrite subscription id, name, management groupnative call with customer and environmentprepare: read ids, resolve environmentswrite back cluster and identity outputs
Customer chain, stage by stage. Subscriptions are created and published to Vault before any environment root runs.
TenantManagement group lowerManagement group upperSubscriptionscustomer-lowercustomer-upperEnvironmentVNet peered to hubCluster with meshManaged identitiesHA (optional)Second regionSecond clusterCross-region peering
Per-customer isolation layers. Each environment is its own subscription, joined to the platform only through the hub.

// Before you start

  • An Azure tenant with a billing account that permits programmatic subscription creation (a Microsoft Customer Agreement billing scope), and management groups for lower and upper.
  • A CI identity with rights to create subscriptions under the invoice section and to associate them with management groups.
  • Terraform 1.9+, azurerm 4.x, and a state bucket; Vault for storing ids and for configuration.
  • The populate-Vault stage from From Form to Running Cluster: Self-Service Team Onboarding (standard defaults, then customer CSV overwrite, then archive).
  • A hub VNet and firewall that each customer VNet will peer to.

// Step-by-step implementation

  1. 01 Create the subscription module with count gates and prevent_destroy

    The module is intentionally tiny. One resource per environment, gated by create_lower and create_upper booleans, each with prevent_destroy. The subscription takes either a billing scope (to create) or an existing id (to adopt), controlled by a single ternary pair so the two modes cannot both be set.

    Associate each subscription with its management group in the same module, so policy and cost rules apply from the first minute. The association needs the subscription id in the /subscriptions/<id> form.

  2. 02 Wrap the module in a root that publishes ids to Vault

    The root maps the environment input (lower, upper, both) onto the booleans and writes three keys per environment to Vault: id, name and management group. Downstream roots never see the module; they read Vault, which keeps them decoupled and lets the same read pattern work everywhere.

    Key the state by customer name, for example subscriptions-management/<customer>. Both environments live in this one state, which is what makes the prevent_destroy guard effective.

  3. 03 Adopt an existing subscription without recreating it

    For a subscription that already exists, add the customer to existing_subscriptions with the id. The module then adopts it under a distinct alias, because alias names are unique per tenant and the plain alias may still be held by another (often empty) subscription. An imports.tf import block brings in the management-group association that already exists, so the plan shows an import and not a create.

    Do the state surgery before the first run. Remove the previous subscription and association from state with terraform state rm; otherwise Terraform plans to replace the old alias, which prevent_destroy rejects. Take a state backup first.

  4. 04 Orchestrate with a three-job parent workflow

    The parent workflow has three jobs. Populate Vault applies the standard defaults, then overwrites with the customer CSV, then archives the CSV with a timestamp so the input is auditable. The subscription job calls the reusable Terraform workflow against the subscriptions root with the customer name and environment. The trigger job calls the onboarding workflow natively, passing the customer and environment.

    Pass environment through unchanged. A customer-chain run does not special-case it and defaults to both, which is the safe default given the single shared state.

  5. 05 Deploy lower and upper in parallel, each peered to the hub

    The onboarding workflow starts with a prepare job that resolves the environments and reads the subscription ids from Vault, then runs deploy-lower and deploy-upper concurrently as separate calls to the reusable Terraform workflow. Each root uses a provider alias bound to its own subscription id, so the same module code deploys into different subscriptions.

    The network is hub-and-spoke: every customer VNet is peered to a shared hub (peering is created in both directions, because a one-sided peering shows as Initiated and carries no traffic). Subnets and the service and pod ranges come from the allocation ledger described in From Form to Running Cluster: Self-Service Team Onboarding.

  6. 06 Branch for HA: two regions, two clusters, cross-region peering

    HA is a flag in Vault, not a separate pipeline. When it is true the root instantiates a second VNet and cluster in the secondary region with its own suffixed keys, and peers the two VNets across regions. Everything that is singular in the non-HA case becomes keyed, which is the same discipline described in Adding a Region Without Destroying Anything: if you key by region from the start, adding a region is additive.

    Gate with count or for_each on a computed ha_enabled boolean so the non-HA plan has no secondary resources at all, and make the secondary state separate (suffix) so a primary apply can never plan to destroy it.

  7. 07 Configure each cluster after apply: mesh gateway and internal load balancer

    Some configuration needs the cluster to exist and cannot sensibly live in Terraform state: annotating the mesh ingress service with a reserved internal address and creating the gateway resources. Do it in a post-apply job per cluster, using credentials fetched from the cluster directly. Make the job idempotent (kubectl apply, annotate with --overwrite) because it will run on every onboarding dispatch.

    Derive the reserved internal address by convention (the second-to-last host of the cluster subnet) so it never has to be typed and is stable across re-runs.

// How to verify it works

  • terraform plan -var environment=lower for a customer that has both environments fails with a prevent_destroy error, proving the guard works.
  • vault kv get -field=value PLATFORM/Lower/Customers/<customer>-lower/subscription_id returns a GUID and az account show --subscription <guid> resolves it under the lower management group.
  • After onboarding, az network vnet peering list on both the spoke and the hub shows state Connected.
  • For an HA customer, both clusters are Succeeded, and the cross-region peerings are Connected in both directions.
  • kubectl -n istio-ingress get svc istio-ingressgateway shows the reserved internal address and the gateway resource is accepted.

// Design decisions and trade-offs

  • The subscription module can adopt an existing subscription under a distinct alias and import its management-group association.
  • Docs call out that dropping an environment already in state plans a destroy of that subscription.
  • Documented caveat: whoever deploys a subscription first becomes its Owner.
  • Hub-and-spoke: every VNet is peered to a hub.
  • Offboarding mirrors the build: destroy, cancel subscriptions, release network, archive Vault config last.

// Pitfalls and lessons learned

  • Dispatching only one environment for a customer that has both. Without the single shared state and prevent_destroy, this cancels the other subscription.
  • Letting someone create the subscription manually. Whoever deploys it first becomes Owner and the pipeline identity may be unable to clean it up.
  • Using the plain alias when adopting. Aliases are tenant-unique; adopt under a distinct alias or the plan errors because the name is held elsewhere.
  • Skipping terraform state rm before adoption. The old alias is then planned for replacement, which prevent_destroy blocks.
  • One-sided peering. It sits at Initiated and passes nothing; create both directions.
  • Reading subscription ids from CSV. Ids come from Vault only, written by the factory, so they cannot be mistyped.
  • Treating a destroyed subscription as deleted. Cancellation is asynchronous and the name can stay reserved for a while.

// Frequently asked questions

How do I create Azure subscriptions with Terraform?

Use azurerm_subscription with an alias and a billing scope from azurerm_billing_mca_account_scope, then associate it with a management group. Your CI identity needs subscription creation rights on the invoice section.

How do I stop Terraform from cancelling a subscription by accident?

Set prevent_destroy on the subscription resource and keep both environments of a customer in one state, so a run that omits an environment fails at plan time instead of destroying it.

Can I bring an existing subscription under Terraform?

Yes: pass its id to azurerm_subscription under a distinct alias, import its management-group association, and terraform state rm the old alias resources first.

Why create subscriptions before the rest of the infrastructure?

Every other resource needs the subscription id, and subscription creation is slow and tenant-global, so it is a separate stage whose outputs go to Vault.

How should a customer VNet connect to shared services?

Hub-and-spoke: peer each customer VNet to a hub in both directions, with forwarded traffic allowed, so shared firewalls and DNS apply.

// The outcome

Isolated customer environments in minutes of pipeline time instead of days of tickets; 3 jobs for populate, 5 for onboarding.

// Where to take it next

// Keep reading