Back to Terraform

Kubernetes with Terraform: Cluster, CRDs and Workload Boundaries

November 6, 2026 Wasil Zafar 25 min read

Avoid planning-time and ownership traps when infrastructure providers meet Kubernetes APIs

Table of Contents

  1. The Cluster API Must Exist Before Some Plans Can Work
  2. Do Not Hide a Two-Stage System Inside Accidental Dependencies
  3. CRDs and Custom Resources Have Their Own Readiness Boundary
  4. Choose One Owner for Each Kubernetes Object
  5. Design an EKS Example with Explicit Cleanup Order

The Cluster API Must Exist Before Some Plans Can Work

Provider configuration is evaluated before the graph runs. Terraform resolves the Kubernetes provider block while it builds the plan, so no namespace, node group or module edge can postpone the connection. If the endpoint, certificate or credential is missing at that moment, the run stops before it can show a single change.

Three values form the contract. The host names the API server, the cluster certificate authority proves its identity, and the credential proves yours. EKS publishes the first two through the cluster resource; the third comes from an access entry, a mapped RBAC group or the legacy auth configuration, and it expires.

A static token is a timed dependency. The cluster auth data source returns a token with a lifetime measured in minutes, and Terraform stores that value in state. A long apply can outlive it, and a later plan can reuse a token that no longer authenticates.

Prefer an exec credential. The provider's exec block calls aws eks get-token for each client, so the token is short-lived and never enters state. It also uses the same AWS identity as the pipeline, which keeps one audit trail for the plan and the apply.

Base64 is not PEM. EKS returns the certificate authority as base64, while the provider expects PEM. Decode it once in the handoff output and pass the result; a pasted certificate silently mismatches after a cluster replacement.

A private endpoint moves the failure earlier. With public access disabled, the runner must sit in the VPC or reach it through a connection. The plan then fails on a timeout that looks like a provider bug but is a network design decision, and no credential will fix it.

Access entries are not always immediate. A new entry or policy association can take a moment to appear in the authorization path. Gate the second stage on one real API call rather than on the cluster resource reporting success.

Provider attributes cannot come from resources in the same run. A provider block cannot reference an attribute that is unknown until apply, and a module input does not change that rule. The only honest fix is to create the cluster in an earlier root or an earlier pipeline stage.

Schema discovery is a second, later gate. A manifest resource asks the cluster which kinds it serves and which fields they have. A CRD installed by the same apply is invisible to that question, because planning asked first.

Deferral changes the error, not the order. Terraform can mark a resource unknown when its schema is unavailable and keep planning the rest. The apply still needs a served kind, so deferral buys a cleaner plan rather than a bootstrap.

The handoff is data, not an edge. Publish the endpoint, the decoded certificate, the cluster name and the caller identity from the cluster root. The workload root consumes them as variables and never reads the cluster resource directly.

Pin both sides of the boundary. Terraform 1.17.1 and hashicorp/kubernetes 3.5.0 are the versions this article was checked against. A provider upgrade can change discovery behavior and defaults, so treat it as a change to the contract rather than a patch.

Figure 1 shows the two stages and the gates that sit between them.

The Cluster API Must Exist Before Some Plans Can Work
%%{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','signalColor':'#5a6e82','noteBkgColor':'#c4873b','noteTextColor':'#132440','fontFamily':'DM Sans, sans-serif'}}}%%
flowchart TD
    A["stage 1: cluster root
VPC, EKS control plane, access entry"] --> B["publish endpoint,
decoded CA, cluster name"] B --> C["stage 2: workload root
provider configuration"] C --> D{"Can the runner reach
the API now?"} D -->|"no route or wrong CA"| E["plan stops at
provider configuration"] D -->|"yes"| F["authenticate the caller"] F --> G{"Access entry or RBAC
allows the verb?"} G -->|"no"| H["401 or 403 before
any diff"] G -->|"yes"| I["discover kinds and
OpenAPI schema"] I --> J{"GVK served now?"} J -->|"no"| K["manifest plan fails,
or defers the object"] J -->|"yes"| L["diff against live objects"] L --> M["apply writes objects"] 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 A,B,D,G,J primary; class C,F,I,L secondary; class M ok; class E,H,K danger;

The left lane creates the contract; the right lane can only consume it.

A published cluster contract feeds the workload provider Stage one is the cluster root, which creates the EKS control plane and an access entry, then publishes the endpoint, decoded certificate authority and cluster name. A handoff panel with versioned outputs, a pipeline gate and a readiness check sits between the stages. Stage two is the workload root, which configures the provider, discovers schemas and only then plans a diff. A footer states that a graph edge cannot supply a provider block. One cluster contract, two plans The second plan cannot start until the first one publishes something it can reach. stage 1: cluster root EKS control plane endpoint and certificate authority access entry caller mapped to an RBAC group published outputs endpoint, decoded CA, cluster name the caller the second stage will use handoff versioned outputs pipeline gate readiness check stage 2: workload root provider configuration host, CA and exec credential schema discovery kinds and OpenAPI fields plan and apply a diff only after discovery one writer per object A graph edge cannot supply a provider block. The handoff is a published contract plus a pipeline gate.

Plan-time reads make the boundary visible. A data source that lists nodes or reads the cluster version uses the same credential at the same moment. If it targets a cluster being created in this run, it reads nothing and the plan records a value that is already stale.

A failed plan is the cheap failure. An unreachable endpoint, a mismatched certificate and an expired token all stop before anything is written. Treat those errors as design feedback: the stage boundary is in the wrong place, not the provider.

Do Not Hide a Two-Stage System Inside Accidental Dependencies

An accidental dependency is an edge that looks like ordering. A module call, a depends_on, a data source or a remote state read can make two stages appear connected while leaving the provider and the plan outside the order.

Three patterns, three contracts. Separate roots publish outputs and gate the second apply; one root with a managed product feature installs the second stage during apply; a pipeline orchestrates both roots as named jobs. Each has a different failure surface, and only the split-root patterns keep planning separate from creation.

A single root cannot plan its own CRDs. The definition is created during apply while the custom resource is planned before it. No graph edge crosses that line, because planning finishes before the first create.

Targeting is recovery, not architecture. Running terraform -target applies a subset and leaves the rest of the state unproven; the next full plan can propose changes the first run never evaluated. It also does not give you a second provider configuration.

Remote state is a read, not a wait. Reading another root's outputs gives you values, not a guarantee that its apply finished. Inside one pipeline the gate has to be a job dependency; across pipelines it has to be a published version or a readiness check.

Product capabilities can remove a stage. EKS managed add-ons, managed node groups and the cluster's own bootstrap remove some "install this after the cluster" work. They do not remove the CRD and workload stage, which is where the provider boundary actually bites.

Orchestration should name the artifact. A pipeline stage that applies the cluster root, waits for a specific output and then applies the workload root is a contract you can review. A chain of remembered targeting commands is not.

Active is not ready. An EKS cluster reports ACTIVE when the control plane exists, while nodes, CoreDNS and the CNI may still be converging. The workload plan can reach the API before any pod can be scheduled, so gate on the evidence the workload needs rather than cluster status alone.

Stale outputs survive a rebuild. A cluster replaced under the same name publishes a new endpoint and certificate, and a cached output can still point at the old one. Version the handoff or key it to the cluster's unique identifier so the second stage cannot silently use yesterday's contract.

Version the interface. Publish the cluster name, endpoint, certificate and required auth mode as a small output object with a documented shape. The workload root can then pin the contract it was tested against instead of guessing from a map.

Figure 2 separates the three patterns and keeps every failure attached to the pattern that causes it.

Do Not Hide a Two-Stage System Inside Accidental Dependencies
%%{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','signalColor':'#5a6e82','noteBkgColor':'#c4873b','noteTextColor':'#132440','fontFamily':'DM Sans, sans-serif'}}}%%
flowchart TD
    Q{"Does the workload plan
need a live API?"} Q -->|"no"| A["one root is honest"] Q -->|"yes"| B{"Can a managed feature
install it during apply?"} B -->|"yes"| C["managed add-on or
cluster bootstrap"] B -->|"no"| D["split into two roots"] D --> E["cluster root applies"] E --> F["publish outputs and
a readiness signal"] F --> G{"Pipeline gate passed
and outputs current?"} G -->|"no"| H["workload plan reaches
an API that is not ready"] G -->|"yes"| I["workload root plans
against a served API"] C --> I I --> J{"Full plan clean?"} J -->|"no"| K["drift, stale outputs or
a second writer"] J -->|"yes"| L["boundary proven for
this change"] H --> M["targeting hides the gap
until the next full plan"] K --> N["re-read state and managed
fields before editing"] 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 Q,B,G,J primary; class A,D,E,F,I secondary; class C,L ok; class H,M danger; class K,N warn;

The gate names evidence, not a duration. "Wait ten minutes" is a hope; "the workload identity can list the namespace" is a test. Choose the smallest API call that proves the second stage can do its job, and fail the pipeline when it does not.

CRDs and Custom Resources Have Their Own Readiness Boundary

A CRD is an API installation. It registers a group, a kind and one or more served versions, and the API server builds the endpoints and schema every client reads. Until that registration is served, a custom resource has no address to be planned against.

Established is the first condition, not the last. The Established condition says the definition was accepted and its names are registered. It does not prove that a conversion webhook is reachable, that the controller is running or that an instance will reconcile.

Discovery is a separate observation. The kind must appear in discovery for the version you intend to use. A CRD can be established while a new version is still not served, which is why the check happens after the apply rather than inside it.

The controller is a third dependency. A custom resource with a valid schema and no controller is stored with empty status. Terraform records the object; nothing turns it into a database, a certificate or a load balancer.

Defaults belong to the schema. A default in the CRD's OpenAPI schema is written by the API server when the field is omitted. Copying that value into HCL makes Terraform the owner of a decision the schema is supposed to make, and a later default change never reaches the object.

Finalizers turn deletion into a protocol. A controller adds a finalizer so it can clean up external state before the object disappears. If the controller is already gone, the object stays Terminating and the namespace cannot finish deleting.

A CRD deletion is cluster-wide. Deleting the definition garbage-collects every custom resource of that kind in every namespace. Keep the definition in a platform root with its own review, and never let an application destroy reach it.

Conversion adds a serving dependency. A CRD that converts between versions through a webhook needs that webhook healthy before the new version answers reads. An outage then looks like a failed plan or a missing object rather than a schema problem.

Upgrades follow the same two-stage rule. Adding a served version does not make it usable in the plan that introduces it. Apply the CRD change, confirm the new version answers discovery, then move the custom resources and only later switch the storage version.

Wait on a condition, not a sleep. A pipeline step can run kubectl wait --for condition=established and then confirm the kind in discovery. A fixed sleep either wastes time or fails on a slow cluster, and it never says which gate was missing.

Figure 3 separates the gates the API can prove from the gates only the controller can prove.

Five observations between a CRD and a reconciled custom resource Five boxes run left to right. The CRD applied box is navy, Established is blue, discovery is amber, the controller is blue and the custom resource status is teal. A bracket under the first three calls them API-side gates that Terraform can observe. A bracket under the last two calls them controller-side gates that only the operator can prove. A crimson pill marks where the apply returns and a teal pill marks where the workload is actually ready. The apply ends long before the workload begins A CRD install is one event in a chain of five observations. CRD applied definition accepted by the API server version registered Established names accepted condition is true no conversion test discovery version is served kind is listed OpenAPI is readable controller pods are available watch loop runs external work starts CR status conditions true external state exists workload can use it API-side gates: Terraform can observe these controller-side gates: only the operator can prove these CRD apply returns workload ready here A successful apply is evidence about the API, not about reconciliation. Read the Established condition, the served kind, the controller and the CR status separately.

Apply success is a schema event. The provider can report that the object was created while the controller has not seen it yet. Read the custom resource's status conditions and the controller's own logs as separate evidence, and keep both next to the plan that created the object.

Choose One Owner for Each Kubernetes Object

Ownership is per object, not per tool. A platform root, a Helm release, a GitOps application and an operator can all be legitimate writers, but each object needs exactly one lifecycle owner. The rest may own fields, never the object's existence.

Terraform is a slow writer with a good memory. It plans, applies and exits, and its state remembers what it created. That makes it a poor fit for objects that change continuously and a good fit for cluster-scoped bootstrap that changes on a reviewed schedule.

GitOps is a fast writer with a repository memory. A controller compares Git with the cluster on a loop and corrects drift. It can own hundreds of namespaced objects, but it cannot create the cluster or the CRDs it needs to parse its own configuration.

Helm is a release, not a loop. A release records what one operation rendered and wrote. Two releases, or a release and a GitOps application, that name the same object are two owners with different schedules and different rollback stories.

Controllers own fields, not lifecycles. A deployment controller, an autoscaler and an operator all write parts of objects they did not create. That is normal, as long as the field sets are disjoint and the lifecycle owner is not also writing the fields the controller needs.

The table assigns each object class to one owner and names the evidence that the handoff happened.

Object classNatural ownerTerraform's viewHandoff evidenceFailure when doubled
VPC, cluster, node groups, add-onscluster rootmanaged resourcesendpoint and certificate outputsthe workload root destroys infrastructure
CRDs and cluster-scoped policyplatform rootmanifest or CRD resourceEstablished and discovery checkan application destroy removes the schema
Namespaces, quotas, RBACplatform root or GitOpsnamespace resourcelabels and access entriestwo creators and one deleter
Deployments, Services, ConfigMapsGitOps controllernot in statetracking label or managed fieldsself-heal fights every plan
Helm releasesHelm provider or GitOpsrelease resourcerelease Secret and annotationsrollback fights the sync loop
Custom resources for an operatorapplication root or GitOpsmanifest resourcestatus conditionstwo controllers reconcile one spec
status and scale subresourcesin-cluster controllerscomputed or ignoredmanaged-field ownerthe autoscaler and Terraform trade replicas

The handoff is a delete-free removal. Terraform 1.7 and later can drop an address from state without destroying the object, using a removed block with destroy = false. The object keeps running while the new owner adopts it; deleting the resource block instead performs a destroy that nobody asked for.

Adoption needs the new owner's marks. Helm looks for its release annotations, Argo CD for its tracking label, and Flux for its inventory entry. A controller that does not recognize an object may create a second copy or refuse to prune the first.

Typed resources and manifests fail differently at the boundary. A typed resource validates against the provider schema and writes with an update, so a controller's value reappears as drift. A manifest uses server-side apply, so the same disagreement surfaces as a field conflict with a manager name.

Defaulted fields belong to the API. If the server or a CRD supplies a value you did not declare, leave it out of configuration and out of the ownership claim. Declaring the default makes every future schema change a Terraform change, and freezes the default in the plan.

Server-side apply records the field split. A controller can own status and the scale subresource while GitOps owns spec, because the API checks fields rather than objects. The object still has one lifecycle owner; the field managers only explain who writes which part.

A clean plan is the test, not the apply. Run the platform plan and the GitOps diff after the handoff. If Terraform still proposes the object, its state or configuration still claims it; if the controller reports drift, the repository does not match what was adopted.

Figure 4 contrasts a contested object with a split that has one lifecycle owner.

A contested Deployment compared with a single lifecycle owner The left panel shows Terraform apply and a GitOps sync both writing one Deployment, with a dashed loop showing the next plan reporting the other writer's change. The right panel shows GitOps owning the Deployment spec and a controller owning status and the scale subresource, while Terraform owns only the cluster. A footer says a handoff moves the lifecycle record without deleting the object, and a second plan proves one writer remains. One object, one lifecycle owner Field sharing is normal. Lifecycle sharing is the failure. two lifecycle owners Terraform apply writes the whole Deployment GitOps self-heal reverts it to the repository same Deployment the next plan shows a change the loop never settles one lifecycle owner GitOps owns spec tracking label or inventory controller owns status scale subresource and conditions same Deployment one writer per field the next plan is empty A handoff moves the lifecycle record without deleting the object. A second plan proves that only one writer remains.

A plan that keeps proposing the same object is telling you who writes next. Read state, labels and managed fields together before changing anything. Removing one of the two configurations is the fix; a lifecycle rule that hides the diff only postpones the question.

Design an EKS Example with Explicit Cleanup Order

The exercise is a review, not a deployment. Draw the ownership map for one EKS cluster and one application, then walk it in both directions: who creates each object, and who deletes it. The card records the split, the handoff and the evidence that would prove both.

Design

Review a cluster/workload split

Execution status: design-only. Written for Terraform 1.17.1 and hashicorp/kubernetes 3.5.0. No command output or identifier is recorded here, and nothing in this card was run against a live account.

Prerequisites. A sandbox account, a VPC with private subnets, permission to create EKS and IAM resources, a Git repository for the application, and a disposable cluster. No production data and no shared DNS zone.

  1. Inventory the objects by lifecycle. Write four groups: cloud infrastructure, cluster add-ons and CRDs, namespaced platform objects, and application objects. If an object appears in two groups, the split is not finished.
  2. Build the cluster root. Own the VPC attachments, the EKS cluster, an access entry for the workload identity, the OIDC provider, a managed node group and the add-ons.
  3. Publish a narrow contract. Emit the endpoint, the base64-decoded certificate, the cluster name and the principal the second stage will authenticate as. Do not export the whole cluster object.
  4. Configure the workload provider with an exec credential. Call aws eks get-token with the published cluster name, and keep the token out of state.
  5. Install the CRD in the platform stage. Wait for the Established condition, then confirm the kind appears in kubectl api-resources before planning anything that uses it.
  6. Choose the target owner. Deployments, Services and custom resources go to Git; namespaces, RBAC and CRDs stay in Terraform. If the application is already in Terraform, this step is a migration rather than a greenfield choice.
  7. Hand off without deleting. Remove the application addresses from Terraform state with a removed block and destroy = false, then let the controller adopt the live objects.
  8. Prove both plans. Run terraform plan -detailed-exitcode on each root and require a synced GitOps application. Both must be clean, and no object may appear in two states.
  9. Rehearse destroy in dependency order. Delete application objects and custom resources while the controller is alive, then the CRDs, the namespace, add-ons, node groups, access entries, the cluster, the OIDC provider and IAM roles, and finally the VPC.
OrderDeleteWait forResidue to check
1GitOps application and custom resourcescontroller running, finalizers clearedno Terminating CR and no orphan external resource
2CRDs and namespacesno custom resources remaindiscovery no longer lists the kind
3add-ons and node groupsload balancers and claims goneno ELB, ENI or EBS volume
4cluster, OIDC, IAM and VPCnode groups and access entries goneno orphan role, NAT gateway or address

Expected observation. A clean plan on both roots, a GitOps application that reports Synced, and a destroy rehearsal that removes objects in the order the dependencies were built. The evidence is a plan exit code, an ownership label or field manager, and an empty residue check.

Failure checks. A workload plan that still proposes an application object means the handoff did not complete. A namespace stuck Terminating means a finalizer outlived its controller. A load balancer or volume that survives the cluster means the teardown ran after the controller that could delete it.

A finalizer is not a cleanup button. Removing it by hand tells the API the external work is done, whether or not it is. Use that only after confirming the cloud resource is gone, and record who removed it and why.

Cost dimensions. The cluster, node group and any load balancer are the billable parts; the review itself is free. Destroy the node group and cluster on the same day, and confirm that the VPC and any elastic address were released.

Cleanup order is the design. If the order is hard to write down, the ownership split is not finished. The card is done when the destroy sequence and the clean plan can both be reviewed without running anything.