Partition State by Cluster and Operational Owner
A cluster is an API endpoint with a blast radius. Production and staging accept the same resource kinds and answer to the same provider, but a mistake in one must not be able to reach the other. The partition that matters is therefore not the resource type; it is the credential, the state file and the operator who can write.
The provider alias names a connection, not a cluster. An alias such as prod is a label on a provider configuration; the config_context inside that configuration chooses the endpoint. Pair the two deliberately, and treat a mismatch as a production incident rather than a typo.
An alias is a label, not an endpoint
The alias names a provider configuration; the config context chooses the API server. A prod alias pointed at staging produces plausible plans for the wrong cluster, so record the context, server URL and git version beside every plan.
Keep the alias and the context identical. If the alias says prod and the context resolves to staging, every plan is plausible and wrong. Record the context name, the server URL and the server's gitVersion beside the plan, and reject a run whose recorded identity differs from the approved one.
State is the real boundary. A root module with two aliases shares one lock, one rollback and one set of approvals. Separate state per cluster gives each failure domain its own lock and its own recovery path; a shared state gives one bad apply two victims.
Split cluster-scoped objects into a platform root. CRDs, ClusterRoles, StorageClasses and admission configurations are not namespaced, so they cannot belong to a team namespace root. Put them in a platform root with its own approval, and let application roots reference them without owning them.
Namespace ownership needs a label, not a naming convention. Mark each namespace with the root that owns it and the team that answers for it. A prefix in the name is a hint; a label on the object is evidence that survives a rename.
Credentials belong to the root. Use a short-lived exec plugin or a job-scoped kubeconfig, not a long-lived token in a CI variable. Give the planning identity read access and the applying identity write access, so a stolen plan credential cannot delete a namespace.
Aliases are inherited silently. A module that omits a provider meta-argument receives the caller's default provider. Declare configuration_aliases in the child module and pass each alias explicitly in the providers map; a missing pass is not a type error, it is a wrong-cluster apply.
Do not create a cluster and its objects in one apply. Provider configuration is evaluated before the resources that would supply its credentials. A cluster module and a Kubernetes module belong to separate applies, with data sources carrying the endpoint and certificate between them.
Renaming an alias is state surgery. Terraform records the provider configuration address with each resource. A cosmetic rename can leave the state pointing at a configuration that no longer exists, so re-import or plan the move as a change with a freeze window.
Three checks make the partition visible. Compare the plan's provider configuration, the kubeconfig context and server URL, and the server version before apply. A check block can assert the expected version, but it reports a warning rather than blocking the apply; the CI gate must do that.
A default provider is not a neutral fallback. If KUBE_CONFIG_PATH is set in the environment, an alias without an explicit path can inherit it, and CI images often carry one. Unset inherited kubeconfig variables at job start and set one path per alias.
Cross-cluster references are a plan-time trap. A resource in one cluster cannot supply the provider for another cluster in the same apply, because the provider is configured before the graph runs. Pass values through variables or remote state, then apply in order.
Plan approval is per root. One approval for a root that spans two clusters is one approval for two blast radii. Separate pipelines, and separate approvers where the environments differ.
The state backend is part of the boundary. Access to the backend is access to every object in the root, including Secret data. Scope bucket or workspace permissions by environment, not by team convenience.
The alias set should be small and boring. One alias per cluster, named for the environment, with no per-team aliases pointing at the same endpoint. A large alias matrix multiplies the number of ways to pass the wrong one.
Workspaces are not a credential boundary. Workspaces give separate state for the same configuration, but they share the backend and often the same execution identity. Use them for ephemeral environments, not as the only separation between production and staging.
Name the root after the endpoint and the owner. A root named for the provider rather than the cluster hides what it writes; a name that carries environment, cluster and owner does not. The name appears in plan output, state keys and incident channels, so make it carry the boundary.
Break-glass access is still a writer. A human with cluster-admin can change an object Terraform owns, and the next plan will call it drift. Record break-glass changes in the same ownership list so the reconciliation is intentional.
Figure 1 shows the two roots and the inheritance path that bypasses both.
%%{init: {'theme':'base','themeCSS':'.edgeLabel .label text, .edgeLabel text, .edgeLabel span { fill:#132440 !important; color:#132440 !important; }','themeVariables': {'primaryColor':'#16476A','primaryTextColor':'#ffffff','primaryBorderColor':'#132440','secondaryColor':'#3B9797','secondaryTextColor':'#ffffff','secondaryBorderColor':'#132440','tertiaryColor':'#c4873b','tertiaryTextColor':'#132440','tertiaryBorderColor':'#132440','lineColor':'#5a6e82','textColor':'#132440','titleColor':'#132440','mainBkg':'#16476A','nodeBorder':'#132440','clusterBkg':'#eef3f7','clusterBorder':'#132440','edgeLabelBackground':'#ffffff','actorBkg':'#16476A','actorTextColor':'#ffffff','actorBorder':'#132440','activationBkgColor':'#3B9797','activationBorderColor':'#132440','signalColor':'#5a6e82','signalTextColor':'#132440','noteBkgColor':'#c4873b','noteTextColor':'#132440','noteBorderColor':'#132440','labelBoxBkgColor':'#a8dede','labelBoxBorderColor':'#132440','labelTextColor':'#132440','loopTextColor':'#132440','altBackground':'#f8f9fa','fontFamily':'DM Sans, sans-serif'}}}%%
flowchart TD
ID["Operator identity
OIDC or exec plugin"] --> SEL{"Which root
is running?"}
SEL -->|"prod job"| PA["kubernetes.prod
config_context = prod"]
SEL -->|"staging job"| SA["kubernetes.staging
config_context = staging"]
PA --> PS[("prod state
own lock and backend")]
SA --> SS[("staging state
own lock and backend")]
PS --> PC["Prod API server
cluster-scoped objects"]
SS --> SC["Staging API server
cluster-scoped objects"]
PC --> PN["Namespaced app objects
team-owned roots"]
SC --> SN["Namespaced app objects
team-owned roots"]
R["Resource with no provider
meta-argument"] -.->|"inherits default"| DF["Default alias
often the wrong cluster"]
DF -.->|"plan looks valid"| X1["Writes to the wrong API server"]
SEL -.->|"one root, two aliases"| SR["Single root
both clusters"]
SR --> X2["Shared lock and blast radius"]
classDef primary fill:#132440,color:#ffffff,stroke:#0b172b;
classDef secondary fill:#16476A,color:#ffffff,stroke:#0f314a;
classDef ok fill:#3B9797,color:#ffffff,stroke:#2a6f6f;
classDef danger fill:#BF092F,color:#ffffff,stroke:#7a0420;
classDef warn fill:#c4873b,color:#132440,stroke:#8a5a1f;
class ID,SEL primary;
class PA,SA secondary;
class PS,SS ok;
class PC,SC secondary;
class PN,SN ok;
class R,DF,SR warn;
class X1,X2 danger;
Figure 2 separates the boundary from the objects inside it. The credential and state decide who may write; the API scope decides which root should own the object. A namespaced Deployment and a cluster-scoped CRD can sit in the same cluster and still belong to different owners.
Partition by owner first, then by cluster. Two teams sharing one cluster still need separate roots when their namespaces, credentials and review paths differ. The cluster is the endpoint; ownership is the reason the state was split.
Import Supported Resources and Review Server Defaults
Import changes ownership, not existence. An import block tells Terraform to read an object that is already in the cluster and record it at a resource address. The object is not recreated; the next plan is the first honest comparison between the object and your configuration.
Find the identifier before writing the block. Use API discovery to confirm the group, the served version and whether the kind is namespaced. Then confirm the namespace and name on the live object; a plausible name in the wrong namespace imports nothing.
Typed resources use a short identifier. Most namespaced types take namespace/name; a namespace takes its name alone; a cluster-scoped role takes its name. The resource type pins the API group and version, so the identifier does not repeat them.
Use the versioned resource names. Provider 3.x deprecates the unversioned types; a new configuration should use the versioned name, and an existing one can move with a moved block or a state remove-and-import. The API group and version stay pinned by the type.
The kubernetes_manifest resource uses a longer identifier. It carries the API version, the kind, an optional namespace and the name, separated by commas, in the form apiVersion=<value>,kind=<value>,namespace=<value>,name=<value>. That form is explicit about the version, which is useful for custom resources and dangerous when the version is not served.
The identifier is not a global object ID. Two clusters can hold the same namespace and name; the provider configuration decides which API server is read. Importing with the wrong alias writes correct-looking state for the wrong cluster.
The identifier is not global
Namespace and name identify an object only within one API server. Confirm the context before importing, or the state will look correct while describing a different cluster entirely.
Generated configuration is a draft. The -generate-config-out option writes a starting point from the imported object, often including server-side values and defaults. Review it, remove values you do not intend to own, and never apply it unread.
Server defaults arrive with the object. A Deployment may carry a default replica count, strategy and progress deadline; a Service may carry a default type and session affinity; a Secret has a type; a PVC has a volume mode. These are real fields, not Terraform inventions.
A clean first plan is the acceptance test. After import, plan should show no changes, or only changes you can explain field by field. An unexplained replacement means the identifier, the API version or an immutable field is wrong.
Import does not adopt children. A namespace import does not import its Deployments, a Deployment import does not import its ReplicaSets, and a CRD import does not import its custom resources. Each object needs its own address or an explicit decision to leave it unmanaged.
Import into the right address and alias. An import block names the destination address and inherits the provider from that resource. With for_each, the destination includes the key; there is no dynamic provider selection inside the block.
API versions need a served-version check. A version can be served, deprecated or removed; conversion webhooks can change the shape between versions. Import under a version the cluster still serves, and record which version the provider schema uses.
Secrets are a special case. Importing a Secret copies its data into state, where it remains readable to anyone with backend access. If that is unacceptable, leave the Secret with its controller or manage only its metadata.
Three failures are common and look different. A missing object returns not found; an object already in another state returns an already-managed error; a custom resource without its CRD fails during planning because the schema is unavailable. Each points at a different fix.
Use a plan, not a shell import, when the change is reviewed. An import block is visible in the diff and can be approved with the rest of the change. A command-line import is invisible to review and easy to run against the wrong context.
The first plan may legitimately update. Import records the object as it is; your configuration may intentionally differ. Separate intentional updates from defaults before applying, and do not use ignore rules to hide the intentional ones.
Imports are state writes, so back up the state. A failed import can leave a partial state entry; a backend version or snapshot makes recovery boring. The backup is also the evidence that the object existed before adoption.
Generated names cannot be imported by a name you do not know. An object created with a name prefix receives a suffix from the API server; the configuration must use the actual name before adoption, or the import has no stable address. Prefer explicit names for anything Terraform will own.
Import the parent before the children, or leave the parent unmanaged. A namespace import followed by child imports is a valid order; importing children first leaves them parentless in state but still valid in the cluster. The order affects review, not the API.
Remove the import block after adoption. The block is a one-time instruction; keeping it makes a later plan try to import an object already in state, which fails the plan. Remove it in the same change that proves the clean plan, and keep the evidence in the pull request.
Review the normalized object, not the YAML you remember. The API server may have added labels, annotations, defaults and a managed-fields record since the object was created. The imported state reflects the server's answer, which is the only one the next plan can compare against.
Figure 3 follows the import path and stops at each branch.
%%{init: {'theme':'base','themeCSS':'.edgeLabel .label text, .edgeLabel text, .edgeLabel span { fill:#132440 !important; color:#132440 !important; }','themeVariables': {'primaryColor':'#16476A','primaryTextColor':'#ffffff','primaryBorderColor':'#132440','secondaryColor':'#3B9797','secondaryTextColor':'#ffffff','secondaryBorderColor':'#132440','tertiaryColor':'#c4873b','tertiaryTextColor':'#132440','tertiaryBorderColor':'#132440','lineColor':'#5a6e82','textColor':'#132440','titleColor':'#132440','mainBkg':'#16476A','nodeBorder':'#132440','clusterBkg':'#eef3f7','clusterBorder':'#132440','edgeLabelBackground':'#ffffff','actorBkg':'#16476A','actorTextColor':'#ffffff','actorBorder':'#132440','activationBkgColor':'#3B9797','activationBorderColor':'#132440','signalColor':'#5a6e82','signalTextColor':'#132440','noteBkgColor':'#c4873b','noteTextColor':'#132440','noteBorderColor':'#132440','labelBoxBkgColor':'#a8dede','labelBoxBorderColor':'#132440','labelTextColor':'#132440','loopTextColor':'#132440','altBackground':'#f8f9fa','fontFamily':'DM Sans, sans-serif'}}}%%
flowchart TD
O["Object already in the cluster"] --> DISC["kubectl api-resources
group, version, namespaced"]
DISC --> ID{"Import identifier
format?"}
ID -->|"typed resource"| T["namespace/name"]
ID -->|"namespace"| N["name only"]
ID -->|"manifest"| M["apiVersion, kind,
namespace, name"]
T --> B["import block
to = resource address"]
N --> B
M --> B
B --> P["terraform plan
provider reads the object"]
P --> S{"Schema available
at plan time?"}
S -->|"no CRD"| X1["Plan fails
unknown type"]
S -->|"yes"| G["Review generated
or hand-written config"]
G --> D{"Server defaults
or immutable fields?"}
D -->|"defaults only"| OK["Adopt with a clean plan"]
D -->|"replacement"| X2["Stop
immutable field conflict"]
P -->|"not found"| X3["Wrong namespace
or name"]
P -->|"already managed"| X4["Object in another
state or address"]
OK --> A["Apply adopts
state records the object"]
classDef primary fill:#132440,color:#ffffff,stroke:#0b172b;
classDef secondary fill:#16476A,color:#ffffff,stroke:#0f314a;
classDef ok fill:#3B9797,color:#ffffff,stroke:#2a6f6f;
classDef danger fill:#BF092F,color:#ffffff,stroke:#7a0420;
classDef warn fill:#c4873b,color:#132440,stroke:#8a5a1f;
class O,DISC,ID primary;
class T,N,M,B secondary;
class S,D,G warn;
class A,OK ok;
class X1,X2,X3,X4 danger;
Adoption ends when the plan is explainable. If every field in the diff has a named owner and a reason, the import is complete. If the diff contains fields nobody recognizes, the import is only a state entry.
Differentiate Controller Drift from Terraform Ownership Mistakes
Drift is a difference; ownership is a decision. Terraform reports both the same way: a proposed update. The question is not whether the object changed, but whether your configuration is the authority for the field that changed.
Controllers mutate spec, not only status. A horizontal autoscaler writes the replica count, a vertical autoscaler writes resource requests, a certificate controller writes Secret data, and a service mesh injects sidecars and annotations. Status changes are expected; spec changes are where ownership fights start.
Defaulted fields are not drift. The API server fills in defaults because the object would otherwise be incomplete. Copying every default into configuration makes the diff quiet, but it also claims ownership of fields you did not choose.
Defaults are not drift
The API server fills defaults to complete the object; copying them into configuration silences the diff and takes ownership of values you never chose. Leave them unmanaged unless your design actually depends on them.
Blanket ignore is a blindfold. Ignoring all of metadata and spec hides a wrong image, a dropped label, a missing ConfigMap reference and an admission change. The plan stays green while the workload diverges.
Ignore one field and name its owner. For an autoscaled Deployment, remove the replica count from configuration and ignore only that field, with a comment that names the autoscaler. If the autoscaler is removed, remove the ignore in the same change.
Resource requests need one writer. A vertical autoscaler and a Terraform resource block both writing requests will alternate. Choose the autoscaler or the configuration, and make the other read-only in the review.
Two roots can own one object. State locking is per state, so a lock in one root does not stop another root from writing the same object. The last writer wins, and a typed provider's read-modify-write can revert fields the other root just set.
A lock protects one state
State locking is per state file, so two roots can still write the same object with both plans green. Give each object one address and one root, and treat a second owner as an incident.
Server-side apply makes the conflict visible, not harmless. A manifest resource records a field manager and reports conflicts; force_conflicts converts that report into last-writer-wins. Forcing is a decision to overwrite another owner, not a way to make the plan pass.
A repeating diff is an ownership bug. If every plan proposes the same change and every apply is reverted by a controller, the configuration is claiming a field it does not own. Fix the claim; do not schedule more applies.
A clean plan can also be wrong. If configuration omits a field that nobody writes, the plan is clean and the object is unowned. Ownership is a matrix of fields, not a property of the whole resource.
Managed fields are evidence. Server-side apply records which manager owns which field; read that record before assigning blame. It shows whether Terraform, a controller or a human last wrote the value.
Admission webhooks are a third writer. A mutating webhook can add a sidecar, a label or a security context on every write. Terraform sees the result and may propose to remove it; the fix is to let the webhook own the field or to stop managing it.
Labels and annotations are maps, not single values. Ignoring the whole map hides key-level drift. For typed resources, avoid managing maps that other controllers write; for manifest resources, computed_fields can exclude a map, but it excludes every key in it.
Imports expose defaulted fields immediately. The first plan after adoption often shows defaults rather than real drift; classify them before changing anything. A default that appears only after import is not evidence that a controller moved.
Immutable fields turn drift into replacement. A Service cluster IP, a PVC storage class or a Deployment selector cannot be updated in place; a diff there is a design change, not a reconcile. Stop and review before accepting a replacement.
Drift detection should not change the cluster. A plan refreshes state, and a manifest diff compares a desired file with the server; neither should be the moment you discover an owner. Record the owner before the diff appears.
A controller upgrade can change defaults. A new admission controller or operator version may add fields; re-review the ownership list after the upgrade rather than adding a new ignore. Otherwise the next upgrade will be diagnosed as drift again.
A deleted and recreated object can look unchanged. If the replacement has the same name and fields, the refresh may not flag the new UID, and the plan can be clean while the old object's data is gone. Check the UID when continuity matters, especially for PVCs and Secrets.
Ownership labels help humans, not the provider. A label such as app.kubernetes.io/managed-by records intent, but Terraform does not enforce it. Use it in audits and in the ownership list; do not treat it as a lock.
Status is not a field you manage. The provider reads status, but a configuration that writes it is fighting the controller. Keep status out of configuration and read it as evidence of convergence.
Figure 4 places each observed change in one of four ownership states.
The useful artifact is a short ownership list. For each resource, record which fields Terraform owns, which fields a controller owns, and which fields nobody owns. The list is shorter than a pile of ignore rules and it survives a controller upgrade.
Protect Plans While Credentials and APIs Change
A saved plan is a promise about four things. It is bound to a configuration, a state serial, a provider version and the API schema the provider read. If any of them changes, the plan describes a world that no longer exists.
State serial protects state, not the cluster. Terraform refuses to apply a plan whose state serial has moved, which prevents overwriting a concurrent state write. It does not notice a controller change, a cluster upgrade or a deleted CRD.
Credentials are not in the reviewed diff, and that is the trap. A plan file records provider configuration, but credentials supplied by the environment or an exec plugin are not part of the change a reviewer approves. If the configuration resolves a path or an environment variable at apply time, the same plan can reach an endpoint the reviewer never saw.
The plan does not contain the endpoint
Credentials from the environment or an exec plugin are outside the reviewed diff, so the same saved plan can apply somewhere else. Record the resolved context and server URL as approval evidence.
Record versions with the plan. Capture the Terraform version, the provider version 3.5.0, the server's gitVersion, the served CRD versions, and the kubeconfig context and server URL. Store them as CI metadata beside the plan, not in a comment someone can edit.
Cluster upgrades change defaulting and remove APIs. A control-plane upgrade can change admission defaults, deprecate a served version or remove a beta API. A plan created before the upgrade may fail, or worse, apply a shape the new server normalizes differently.
CRD changes are API changes. A new served version, a changed validation schema or a new conversion webhook changes what the provider reads during planning. Re-plan after any CRD change, even when the CRD is managed by another root.
Expiring credentials fail in the middle. An exec plugin refreshes short-lived tokens, but a long rollout can outlive one. When the token expires, the apply stops with some objects written and some not; the recovery path is the partial-apply path, not a retry loop.
Kubeconfig environment variables are a global fallback. If an alias omits config_path, the provider can inherit KUBE_CONFIG_PATH from the job. Unset inherited variables and set an explicit path per alias, or one stale variable will point every root at one cluster.
Plan files are sensitive artifacts. They can contain Secret values, generated passwords and the full desired state. Encrypt the backend, restrict plan access and delete the file after a successful apply.
Apply the reviewed plan, not a fresh one. A saved plan applies exactly the change that was reviewed and ignores later configuration edits. That is the point; it is also why a failed gate must discard the file rather than edit around it.
Separate plans per cluster. A single plan spanning production and staging has one approval and two blast radii. Run separate jobs, with separate credentials and separate approvers where the environments differ.
A stale plan is a change request. When a gate fails, re-plan and review the new diff. Treating re-plan as an exception encourages applying a plan whose assumptions have already expired.
Provider upgrades change normalization. A new provider version can read a field differently or add a computed attribute; a plan created under 3.4.0 is not evidence for 3.5.0. Pin the version and re-plan when it moves.
The cluster can change without a version bump. A CRD installed by another team, a new admission webhook or a changed default StorageClass can alter the next plan. Record those dependencies with the plan, not only the server version.
Long-lived plans are a rollback hazard. An old plan can reintroduce a value that was deliberately changed; the older the plan, the more it looks like a revert. Set an expiry and discard on breach.
The apply should run in the same job as the plan. A saved artifact passed to a different runner inherits a different environment and identity. If separation is required, make the handoff explicit and reviewed, not an accident of whichever job picked up the file.
Review the plan's action, not only its diff. An in-place update, a replacement and a create-after-destroy are different risks. Mark every replacement in the approval, especially for PVCs, Services and CRDs.
Deprecated APIs fail at different times. A removed API fails the plan or the apply; a deprecated but served API succeeds with a warning and becomes a deadline. Record the served versions and the removal timeline beside the root.
State encryption does not protect a running plan. Backend encryption protects the stored state; a plan file on a CI workspace is a separate copy. Apply the same access control to both.
A no-op plan is still worth recording. It proves the cluster matched the configuration at that moment, which is exactly the evidence an incident review needs.
Figure 5 shows the gates between a saved plan and an apply, and the partial-apply branch when a gate fails late.
Protect the decision, not just the file. A plan is safe only while its assumptions hold; the gates exist to prove that they still do.
Recover Timeouts and Teardown in Dependency Order
A timeout is a state question, not a delete signal. When a create or update times out, the object may exist and be partially ready, and Terraform may already have recorded it. Deleting first destroys the evidence and can destroy data.
Read three inventories after a failed apply. List what state believes it manages, what the API server actually holds, and what the controller reports as ready. The gaps between the three lists are the recovery plan.
A tainted resource is not always replaceable. A create timeout taints the resource, and the next apply proposes replacement. For a Deployment that is cheap; for a PVC, a PV or a CRD it can mean data loss or a cluster-wide delete.
Taint is not a licence to replace
A timeout taints the resource and the next apply offers replacement. That is routine for a Deployment and potentially destructive for a PVC, PV or CRD, so read state before accepting the replacement.
State can hold an object the cluster no longer has. A manual delete leaves state behind, and the next plan proposes creation. A refresh-only plan reconciles the read, but if the deletion was intentional, remove the resource from state without destroying anything.
The cluster can hold an object state never recorded. A provider crash or an interrupted write can leave an object without a state entry. Import it at the address the configuration expects; do not let apply create a duplicate or fail with an already-exists error.
A removed block is the declarative way to forget. With destroy = false, Terraform drops the object from state and leaves it running. Use that for ownership transfer, not a shell state deletion.
A targeted apply is a recovery tool, not a workflow. Targeting one broken resource can restore service, but it leaves the rest of the graph unverified. Follow it with a full plan and a full apply before calling the incident closed.
Readiness settings move the failure; they do not remove it. A Deployment waits for rollout by default; disabling that wait makes apply succeed before the workload is ready. Timeouts should be raised after diagnosis, not to make a red apply green.
Teardown starts with a destroy plan and an inventory. Terraform knows the objects in its state and the dependencies between them. It does not know controller-created objects, custom resources in another root, retained volumes or cloud load balancers.
Namespace deletion is a cascade. Deleting a namespace deletes every namespaced object inside it, including objects Terraform never managed. A namespace stuck in termination usually has a resource with a finalizer, not a namespace controller bug.
CRDs are cluster-scoped and destructive. Deleting a CRD deletes every custom resource of that type, and a CR finalizer can block the deletion. Delete custom resources first, resolve their finalizers, then delete the CRD from the platform root.
Finalizers are contracts with a controller. A finalizer says an external resource still needs cleanup. Remove it only after the external resource is gone or the controller is permanently retired; a blanket removal orphans cloud disks, load balancers and DNS records.
Persistent volumes outlive claims. A Retain reclaim policy leaves the PV and its cloud disk after the claim is deleted, and StatefulSet claims are not always removed with the workload. Inventory PVs and cloud volumes before declaring teardown complete.
Load balancers and DNS records are controller-owned. Deleting a Service asks the cloud controller to delete its address, and external-dns removes the record. If the controller was removed first, both can survive the destroy with no Terraform object to explain them.
Ownership transfer needs a freeze, not a lock. Stop both writers, remove the object from the old root without destroying it, import it into the new root, and verify a clean plan before unfreezing. Two roots managing one object is an outage waiting for the next apply.
Cross-root dependencies are not in the graph. If a CRD lives in a platform root and a custom resource in an app root, Terraform sees two graphs. Destroy the app root first, then the platform root; reversing the order deletes the CRD and every custom resource under it.
PVC expansion is not a rollback. A storage class that allows expansion accepts a larger request but not a smaller one; a plan that tries to shrink is rejected or replaced. Treat size as a one-way decision.
A namespace finalizer is not the same as a resource finalizer. The namespace controller removes its own finalizer after the namespace is empty; a stuck resource keeps the namespace alive. Find the resource, not the namespace finalizer, unless the namespace itself is being force-deleted.
Deletion protection has a cost. A prevent-destroy lifecycle blocks the destroy plan, which is useful for production but can also block an incident teardown. Name the person who may remove it and record the review.
Record the teardown in the same inventory. The post-destroy list is evidence: namespaces, CRDs, PVs, load-balancer addresses and DNS records. A blank list is the only clean result; a surviving item needs an owner, not a retry.
The lab below exercises the recovery and teardown path in a disposable namespace.
Recover Timeouts and Teardown in Dependency Order
Execution status: design-only. The procedure is written for Terraform CLI 1.17.1 with hashicorp/kubernetes 3.5.0, but this article does not claim the commands were run. Use a disposable cluster and a namespace you are allowed to delete.
Prerequisites. A cluster where you may create a namespace, a CRD and a PersistentVolumeClaim; a default StorageClass with a reclaim policy you know; and a second root or state backend if you want to rehearse ownership transfer.
- Snapshot before the lab. Record namespaces, PVs, PVCs, CRDs and the state list. Expect an inventory you can compare after teardown.
- Create the namespace and a PVC with an explicit StorageClass. Apply and confirm the claim is Bound. Note the PV name and its reclaim policy.
- Install the CRD in a separate apply from the custom resource. This is the plan-time dependency: the provider reads the CRD schema before it can plan the custom resource.
- Deploy a workload with an image that never becomes ready, with rollout waiting left on. Expect the apply to time out with the Deployment in state and the rollout incomplete.
- Recover without deleting. Compare state, the live Deployment and the rollout status. Fix the image or the probe, then run a full plan. Untaint only after the object is healthy.
- Rehearse a missing state entry. Remove the Deployment from state without destroying it, then import it back at the same address. Expect a clean plan, not a replacement.
- Rehearse a finalizer. Add a finalizer to a disposable custom resource, delete it, and observe the object remain in termination. Identify the controller, confirm no external resource remains, then remove the finalizer and let deletion finish.
- Tear down in order. Run a destroy plan and review its order before applying. Destroy the app root first so custom resources and namespaced objects go, then the platform root's CRD, then the namespace if a separate root owns it. Inspect PVs and load-balancer addresses afterwards, and expect retained volumes to remain.
| Evidence | Source | Expected | What it rules out |
|---|---|---|---|
| State list after timeout | Terraform | workload recorded, rollout incomplete | a silently lost object |
| Live rollout status | Kubernetes | condition not available | a false ready signal |
| PV after namespace delete | Kubernetes | Retain leaves the volume | complete storage cleanup |
| CRD after custom resource delete | Kubernetes | CRD remains until deleted | an accidental cluster-wide delete |
| Finalizer before removal | Kubernetes | controller name in the list | an unexplained hang |
| Post-destroy addresses | cluster and cloud | no Service addresses left | a leaked load balancer |
Expected observation. The timeout leaves a recoverable object rather than a reason to delete the namespace. The retained PV survives the namespace, the CRD survives the custom resource, and the finalizer hangs until its owner is identified. A clean final inventory is the only evidence that teardown is complete.