// Why this matters
Safe offboarding with a deliberate Terraform destroy order is one of the few places where the cost of a bad automation is permanent. Creating an environment wrongly costs a re-run; deleting one wrongly can orphan load balancers that keep billing, leave address space looking free while a VNet still holds it, or cancel a subscription with workloads still draining.
Offboarding also happens far less often than onboarding, which means it rots. Scripts that were right a year ago fail on a resource type that did not exist, or on a state that was half-destroyed last time. A teardown that cannot be safely re-run after a failure is a teardown people avoid, and avoided teardowns become permanent cost.
This post lays out the workflow shape that has worked: a strict order, a cached source of truth for the run, a guard on the irreversible steps, and enough logging that the run history explains itself. It is the mirror of From Form to Running Cluster: Self-Service Team Onboarding.
// The problem
Deleting a subscription or cluster out of order leaves debris. Remove the cluster while workloads still own load balancers and the cloud controller may leave them behind. Delete infrastructure before the autoscaler is detached and you get ghost registrations in the cost dashboard and a cluster delete that hangs on nodes the autoscaler keeps recreating. Cancel the subscription first and Terraform can no longer reach the resources to destroy them.
Network space has its own trap. Address blocks are a finite pool. If a block is returned to the pool while the VNet still exists (because a destroy failed halfway), the next onboarding receives a block that collides with a live network and cannot be peered.
Finally, partial failure is the normal case, not the edge case. A stuck node resource group, a peering that will not delete, or a vault with purge protection will fail one job. The workflow must be safe to run again and must not depend on state that the failed run already destroyed.
// The solution
The workflow has about ten numbered jobs in a single file. A prepare job resolves everything (subscription ids, cluster names, HA flag, feature flags) and writes it to an artifact retained for 90 days. Every later job reads that artifact, not Vault, so a re-run after Vault state was reset still has its inputs. The fallback chain is explicit: Vault first (fresh), then the cached artifact from a previous run, then derive from the naming convention, then fail with recovery instructions, because a subscription id cannot be derived.
The order is: remove the workloads by deleting the bootstrap kustomization through an auto-merged pull request and waiting for reconciliation (so the cluster deletes its own load balancers and volumes gracefully), destroy the GitOps bootstrap root, destroy the autoscaler root plus its API-side registration (non-blocking), destroy the infrastructure roots (lower and upper in parallel), and only then run the post-destroy cleanup. Subscriptions are destroyed last because cancelling them is asynchronous and final.
Safety is layered. The default action is Plan and Destroy; a destroy-only action skips the plan for emergencies. Each destroy job has a paired skip job that explains in the logs why it did not run, which turns a wall of grey boxes into a readable history. The network release job is guarded so that it runs only when the destroys did not fail and at least one succeeded. Concurrency is per team with cancel-in-progress off.
I rejected a single terraform destroy over one root: the roots have different lifecycles and different providers (Kubernetes and Flux providers cannot be destroyed after the cluster is gone), and one failed resource would block everything. I also rejected deleting the resource group as a shortcut; it skips Terraform state cleanup and leaves state pointing at nothing.
- Prepareread Vault, check the cluster exists, detect HA, cache everything as an artifact
- Workload cleanupremove the bootstrap kustomization via auto-merged PR; wait for reconciliation
- Destroy GitOpsTerraform destroy of the Flux bootstrap root
- Destroy autoscalerTerraform destroy plus API cleanup, non-blocking
- Destroy infrastructurelower and upper roots destroyed in parallel
- Gate: release network gateranges returned to the pool only if destroys succeeded
- Side jobsremove lock, archive chat channels (non-blocking)
- Network watcher cleanupdelete the group created by policy outside Terraform
- Destroy subscriptionscancelled asynchronously by the cloud provider
- Reset statelock cleared and team removed from the registry
- Prepareresolve and cache inputs as an artifact
- Drain workloadsdelete bootstrap kustomization via PR, wait
- Destroy GitOpsremove Flux bootstrap root
- Destroy autoscalerroot plus API cleanup, non-blocking
- Destroy infralower and upper roots in parallel
- Gate: destroys ok gateno failures and at least one success
- Release networkreturn CIDRs to the pool
- Destroy subscriptionsasynchronous cancel
- Reset stateclear lock, free the team name
// Before you start
- The onboarding pipeline from From Form to Running Cluster: Self-Service Team Onboarding, with one Terraform root per layer (GitOps bootstrap, autoscaler, infrastructure, subscriptions).
- GitHub Actions with protected environments and permission to upload artifacts; a token that can open and merge pull requests in the GitOps repository.
- Terraform 1.9+ and remote state per layer; a networking ledger as in Vault as the Control Plane: A Five-Tier Key Model with Locking or equivalent.
- Runner network access to the private cluster API, and cloud OIDC federation.
- Understanding of
if: always()andneeds.<job>.resultsemantics in GitHub Actions.
// Step-by-step implementation
01 Resolve inputs once and cache them as an artifact
The prepare job is the only job that talks to Vault. It reads the values every later job needs, falls back through the chain, and uploads a small JSON file. Later jobs download it. This single decision is what makes the workflow re-runnable: after a partial teardown, Vault keys may be gone, but the artifact is not.
Keep the data minimal and non-secret: ids, names, booleans. Never write tokens into the artifact, because artifacts are readable by anyone with read access to the repository.
02 Drain workloads before touching infrastructure
GitOps lets you drain the cluster in the cluster's own language. Remove the bootstrap kustomization that points at the application tree, open and auto-merge the pull request, then wait for reconciliation to finish pruning. Because the workloads are deleted by their controllers, cloud load balancers, disks and DNS records created by those workloads are deleted by the same controllers that created them.
Wait on an observable condition, not a sleep: poll until the application namespaces are empty or a timeout is hit. If the timeout hits, fail the job; continuing means the later destroy will leave orphans.
03 Destroy the control layers: GitOps, then autoscaler
Destroy the GitOps bootstrap root next. Its Kubernetes and Flux providers need a reachable cluster, so it must go before the infrastructure. Then destroy the autoscaler root, which removes its agent, node pools and Helm releases. The autoscaler also holds a registration in its SaaS API; if Terraform destroy leaves one behind, a small API cleanup step removes it. Mark that cleanup non-blocking so an API outage never blocks infrastructure removal.
Run both through the same reusable Terraform workflow used for onboarding with
TERRAFORM_DESTROY: trueand the-destroyplan flag, so reviewers see the same plan artifact format. See One Reusable Plan/Apply Workflow for Cost-Optimised Autoscaling for the shape of that workflow.04 Destroy infrastructure with a plan-destroy first and paired skip jobs
The infrastructure roots (lower and upper) can be destroyed in parallel. The default action runs
terraform plan -destroyfirst and the destroy only if that succeeds; a Destroy-only action exists for emergencies. Gate each job withalways()plus explicitresultchecks.always()is needed because a skipped upstream job would otherwise skip everything downstream; theresult != failurechecks stop you proceeding after a real failure.Pair every destroy job with a skip job that runs on the inverse condition and prints why. It costs ten lines and turns the run graph into documentation.
05 Guard network release so address space is only freed after a real destroy
The release job returns the team's blocks to the pool. It is guarded: it needs both destroy jobs, requires that neither failed, and requires that at least one succeeded (so an "everything skipped" run cannot release a block). If either destroy failed, a failure-handler job runs instead, prints that the ranges are still reserved and how to retry, and fails the workflow.
The release script mirrors allocation. It clears the assignment fields, sets
availableback to 1, and for HA also releases the secondary block. Commit it through the same auto-merged pull request path used for allocation.06 Clean up what Terraform does not own, then cancel subscriptions
Some resources are created outside Terraform by cloud policy, for example a network-watcher resource group that the platform creates automatically. Delete them explicitly after the infrastructure destroy or the subscription cancellation will be blocked or leave them dangling. Then destroy the subscription root: the provider cancels the subscription asynchronously, so a green job means "cancel requested", not "gone".
Do side jobs that do not matter for correctness (archive chat channels, remove the lock file) as
continue-on-errorjobs so a missing token never fails a teardown.07 Reset state last and keep concurrency strict
The final job clears the Vault lock and removes the team from the input registry (see Vault as the Control Plane: A Five-Tier Key Model with Locking) so the name can be reused. It runs only after everything else, because resetting early would remove the data the artifact fallback is protecting against.
Set the workflow concurrency group to the team name and
cancel-in-progress: false. A second trigger for the same team waits; a running teardown is never interrupted mid-destroy.
// How to verify it works
- Dispatch with
Plan & Destroyagainst a disposable team. Expected: plan-destroy artifacts appear, and nothing is destroyed until the environment reviewer approves. - After the drain job,
kubectl get nsshows only system namespaces, and the cloud console shows no leftover load balancers for the team. - Force a failure in one destroy job. Expected:
release-networkis skipped,handle-destroy-failureruns, and the ledger still shows the block as used. - Re-run the whole workflow after that failure. Expected: prepare resolves from the cached artifact even if Vault keys are gone, and the destroy continues from where it stopped.
- Confirm the ledger entry has
available: 1and noassigned_toafter a clean run, and that the team name can be onboarded again.
// Design decisions and trade-offs
- Artifact-based resilience: data is fetched once and cached for 90 days. Fallback chain: Vault, cached artifact, naming convention, then fail with recovery instructions.
- Plan-destroy first; a Destroy-only action skips the plan for emergencies.
- Every destroy job has a paired skip job that logs why it was skipped.
- The network release guard prevents range reuse while a VNet may still exist.
- Concurrency per team with cancel-in-progress off, so a running teardown is never interrupted.
- continue-on-error is used only for optional jobs. Documented failure modes include stuck node resource groups, peering delete failures and Key Vault purge protection.
// Pitfalls and lessons learned
- Using
always()without result checks. It runs the job even after an upstream failure and can release network space while a VNet still exists. - Destroying the cluster before the autoscaler is detached. Nodes keep being recreated and the delete hangs on the node resource group.
- Skipping the workload drain. Orphaned load balancers and disks keep billing and later block resource group deletion.
- Peering deletes that fail because the remote side still references the VNet. Retry after the other side is removed; do not force-delete state.
- Key vaults with purge protection. A destroyed vault is soft-deleted and its name stays reserved for the retention period, which breaks an immediate re-onboard with the same name.
- Treating a green subscription destroy as final. Cancellation is asynchronous; verify state afterwards.
- Putting secrets into the cached artifact. Artifacts are broadly readable; ids and names only.
// Frequently asked questions
What is the safe order for destroying a Kubernetes environment with Terraform?
Drain workloads through GitOps, destroy the GitOps bootstrap, detach the autoscaler, destroy infrastructure, release network space only if destroys succeeded, then cancel subscriptions and reset state.
How do I make a teardown workflow safe to re-run?
Resolve inputs once into an artifact with a fallback chain, so a re-run does not depend on state the previous run destroyed. Make every destroy idempotent and keep concurrency strict.
Why not just delete the resource group?
It bypasses Terraform, leaves state pointing at deleted objects, skips ordered cleanup like load balancers owned by workloads, and cannot be guarded by plan review.
Why pair each job with a skip job?
GitHub shows skipped jobs without explanation. A skip job that prints the reason makes the run history self-documenting for the next on-call.
When is it safe to return a CIDR block to the pool?
Only after the VNet is confirmed destroyed. Guard the release on destroy job results, requiring no failure and at least one success.
// The outcome
About ten numbered jobs, seven safety mechanisms and a pipeline that can be re-run after any failure.
// Where to take it next
- Compare with the customer chain in Subscription Factory: Customer Onboarding That Starts by Minting Subscriptions, whose offboarding mirrors its build.
- Add a scheduled job that diffs the network ledger against live VNets and reports leaks.
- Feed run results into Guardrails and Engineering Telemetry: Org Policy, Project Factory, Gatekeeper, Four Keys to track teardown success and duration.