Back to Terraform

Kubernetes Provider: API Access, Authentication and Cluster Boundaries

November 6, 2026 Wasil Zafar 20 min read

Connect to an existing reachable API with explicit context and credentials that survive planning and apply

Table of Contents

  1. A Kubernetes Provider Does Not Provision the Cloud Cluster
  2. Choose Context and Credentials Explicitly
  3. Check API Reachability During Both Plan and Apply
  4. Pass Cluster Aliases Through Modules Transparently
  5. Prove the Target Cluster and Narrow Permission Set

A Kubernetes Provider Does Not Provision the Cloud Cluster

The cluster is someone else's object. A managed service or a bootstrap module you own creates the control plane, the endpoint, the certificate authority and the node pools. The Kubernetes provider never creates any of that; it opens an HTTPS session to an endpoint it was handed.

Four gates sit behind that endpoint. Authentication answers who is calling, authorization answers which verbs are allowed on which resources, and admission answers whether the object is acceptable. Only then does anything reach etcd, and each gate fails with its own status and its own message.

The provider is configured before the graph exists. Provider configuration is read as planning begins, so no depends_on can make it wait for a cluster that the same run is still building. That ordering problem is why the provider documentation tells you to split cluster creation from object management.

LayerWhat it ownsWho creates itFailure when mixed
Control planeendpoint, CA, etcd, API servercloud cluster rootprovider points at an API that does not exist yet
Nodes and add-onskubelet, CNI, CoreDNScloud cluster rootobjects apply, pods stay Pending
Objectsnamespaces, RBAC, workloadsworkload rootdestroy leaves cloud resources behind
Controllerspods, endpoints, load balancersin-cluster controllersstate cannot see or delete them

A plan already talks to the API. Refresh reads every object this root manages, a data source queries live state, and kubernetes_manifest fetches the cluster's schema before it can produce a diff. A root that cannot reach the endpoint fails before it shows you a single change.

Objects and what controllers make are different things. Terraform records the namespace, the Deployment and the Service. Pods, ReplicaSets, endpoints and cloud load balancers appear afterwards, created by controllers that Terraform never asked and cannot delete.

Destroy carries the same boundary in reverse. Delete the cluster first and its objects disappear with it while the workload root still lists them. The next destroy fails on missing objects, and rebuilding a cluster under the same name does not bring them back.

Keep one root per lifecycle. The cluster root owns the endpoint, the CA and the add-ons; the workload root owns the provider block and the objects. The hand-off is a published output plus a pipeline gate, not an edge in the graph.

A Kubernetes Provider Does Not Provision the Cloud Cluster
%%{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
    CLUSTER["Cloud cluster root
endpoint, CA, node pools"] --> API["API server
HTTPS on 443"] RUNNER["Terraform runner
workload root"] -->|"kubeconfig, exec token
or service account"| API API --> AUTHN{"Authentication
who is calling?"} AUTHN -->|"unknown or expired"| E401["Authentication rejected
no diff produced"] AUTHN -->|"identity"| AUTHZ{"Authorization
RBAC allows the verb?"} AUTHZ -->|"no binding"| E403["Forbidden
verb and resource named"] AUTHZ -->|"allowed"| ADM{"Admission
mutate, validate, quota"} ADM -->|"rejected"| EDENY["Admission denied
webhook or quota"] ADM -->|"accepted"| STORE[("etcd
object persisted")] STORE --> CTRL["Controller manager
pods, endpoints, balancers"] CTRL -.->|"never in state"| DRIFT["Objects change
outside the plan"] 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 CLUSTER,RUNNER primary; class API,CTRL secondary; class STORE ok; class AUTHN,AUTHZ,ADM warn; class E401,E403,EDENY,DRIFT danger;
The cluster root creates the API that the workload root then talks to The top band is the cloud cluster root, which owns the control plane, the endpoint with its certificate authority, and the node pools. Below it, the Terraform runner sends an authenticated HTTPS request through authentication, authorization and admission before the object is stored in etcd and reconciled by controllers. A crimson note records that the provider cannot create the endpoint it depends on. Two lifecycles, one API boundary The cluster root builds the endpoint; the workload root authenticates to it. Cloud cluster root — cloud API only control plane and etcd endpoint and certificate authority node pools and add-ons kubeconfig or exec token Terraform runner workload root, one alias plans and applies objects Authenticate who is calling bearer token Authorize which verbs RoleBinding scope Admission quota, policy webhook decision Stored etcd object then reconciled A provider cannot create the endpoint it plans against Provider configuration is read before the graph runs, so one root cannot build the cluster and also talk to it. Split the two roots and put a readiness gate between them.

Choose Context and Credentials Explicitly

Ambient context is the default failure. A kubeconfig on a workstation can hold a dozen contexts, and the one left selected after an incident is rarely the sandbox. A provider that reads that file without naming a context inherits the mistake without printing a warning.

The provider does not read the kubectl variable. Its own are KUBE_CONFIG_PATH and KUBE_CONFIG_PATHS, and the shell variable kubectl honours is not one of them. Set the provider's path explicitly, or pass the path in the root, instead of assuming the shell already pointed it somewhere.

Pin the context, not only the file. A file with many contexts resolves to the default context when no name is given, and the default is a property of the file rather than of your intent. Name the context in the provider block and let the file hold everything else.

Explicit attributes are a complete alternative. A host, a CA bundle and a token are enough to connect, and they take the file out of the trust path. The cost is rotation: the token is now the root's problem, and it is written wherever that value is written.

Exec is the durable option for expiring tokens. The provider runs a command, decodes the credential it returns, and runs it again when a fresh one is needed. The cloud CLIs already implement this, so an EKS or GKE token helper becomes the credential source instead of a copied secret.

Never mix exec with a static credential. The provider documents that combining exec with a token or a client certificate has undefined behaviour, so there is no guaranteed winner. Pick one mechanism per provider block and delete the other.

In-cluster is implicit and strictly local. When the pod environment carries the service host and port variables, the provider connects to that cluster with the mounted service account and needs no attributes. That is convenient for an in-cluster controller and useless for reaching a second cluster.

A token that outlives the run is a bug. Static tokens expire on the issuer's schedule, not yours, and a plan followed by a long apply can cross that boundary between two requests. The failure arrives as a 401 in the middle of a change set that had already planned cleanly.

Pin the provider with the Terraform version. This article is written against Terraform 1.17.1 and hashicorp/kubernetes 3.5.0, and both belong in version constraints rather than in a comment. A provider upgrade can change which credential source wins, so treat it as a planned change with the same proof steps as a cluster change.

SourceSecret lives inRotationFailure shape
kubeconfig filea file on the runnerreissued by the cluster ownerwrong context, silently
explicit attributesvariables and the plan filemanualexpired token mid-apply
exec pluginnowhere, minted per callautomatichelper missing from the runner
in-clustermounted service accountrotated by the kubeletworks only for the local cluster
Choose Context and Credentials Explicitly
%%{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
    CFG["provider kubernetes"] --> SRC{"Where does the
credential come from?"} SRC -->|"file"| FILE["config_path or config_paths
plus config_context"] SRC -->|"attributes"| EXPL["host and CA
plus a static token"] SRC -->|"exec"| EXEC["exec block
command mints a token"] SRC -->|"pod environment"| INCL["service host and port
detected in the pod"] FILE --> CTX{"Context pinned
by name?"} CTX -->|"no"| AMB["Default context wins
which cluster is that?"] CTX -->|"yes"| MIX EXPL --> MIX{"Mixed with
exec?"} EXEC --> MIX INCL --> MIX MIX -->|"yes"| UNDEF["Undefined credential
no guaranteed winner"] MIX -->|"no"| TOKEN{"Still valid
at apply time?"} TOKEN -->|"static, long run"| EXP["401 mid-apply
state partly written"] TOKEN -->|"minted per call"| WHO{"Identity matches
the intended account?"} WHO -->|"no"| WRONG["403 on the first write
or a write to the wrong cluster"] WHO -->|"yes"| OK["Objects applied
under a known identity"] 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 CFG primary; class FILE,EXPL,EXEC,INCL secondary; class OK ok; class SRC,CTX,MIX,TOKEN,WHO warn; class AMB,UNDEF,EXP,WRONG danger;

Check API Reachability During Both Plan and Apply

A plan is a network operation for this provider. Refresh, data sources and manifest schema lookups all leave the runner. A plan is not a local computation that happens to contact the API later.

Four conditions must hold at once. The host name must resolve, a route must exist to that address, the port must be open, and the certificate must chain to the CA in the provider block. Each one fails differently, and only one of them is a credential problem.

Runner location decides which conditions are achievable. A laptop plans over VPN or not at all, a CI runner in a private subnet needs a route and an endpoint policy, and an in-cluster runner inherits both. Choose the runner before the endpoint, because the endpoint is a create-time property of the cluster.

TLS trust fails before authentication does. A certificate error means the runner reached something, but not the cluster you think it reached. Setting insecure disables the check and hides exactly the mistake that produced it.

A proxy is part of the path, not an escape from it. When egress leaves through a proxy, the provider needs proxy_url, and the name it validates is still the cluster's. A tls_server_name override belongs only where the endpoint is fronted by a name that differs from the certificate.

The endpoint is part of the cluster's identity. Recreate the cluster and the host and CA change together even when the name is identical. Publish both from the cluster root and consume both, so a stale value fails loudly instead of reaching the old API.

A long apply is many authenticated requests. An exec credential refreshes between calls, so the run survives a token lifetime; a static credential must stay valid for the whole apply. Budget for the slowest resource, not the fastest.

Destroy needs the API more than apply does. Terraform removes an object by calling the API, so a cluster deleted out of band turns teardown into a sequence of missing-object errors. The state has to be repaired deliberately, either by removing the addresses or by re-importing what still exists.

A pull-request plan needs the same reachability as an apply. A plan job on a hosted runner that cannot reach the endpoint will fail every pull request, and the usual workaround is to disable the job rather than fix the network. Either run that job inside the network, or plan against a cluster it can actually reach and record that choice in the pipeline.

Message or symptomLayerFirst check
no such hostDNSprivate zone or resolver used by the runner
dial tcp timeoutnetworkroute, firewall, authorized networks
x509 unknown authorityTLSCA published by the cluster root
401 Unauthorizedauthenticationtoken issuer, expiry, exec helper output
403 ForbiddenauthorizationRoleBinding in the target namespace
404 on destroyobjectcluster still exists and is the same one

Pass Cluster Aliases Through Modules Transparently

One alias per cluster, one root per alias. An alias is a second provider configuration with its own endpoint and its own credential. Two clusters in one root mean one plan that can write to both and one refresh failure that stops both.

Provider blocks belong in the root. A child module cannot declare a configuration for a different cluster, and it should not try. The root declares the provider, the module receives it, and the mapping is readable in one place.

configuration_aliases is the contract for a module that needs two. A module that manages two clusters in a single call declares both names and the caller supplies both. A module called once per cluster under the default name needs no alias at all.

Aliases cannot be created in a loop. for_each repeats resources and module instances, not provider configurations. Ten clusters are ten module calls with ten explicit mappings, or ten roots, never one block with a computed name.

Pass the provider, not the token. Handing a module a host and a bearer token puts the credential in variables, in the plan file and in every log line that prints inputs. Handing it the configured provider keeps the secret in one place and keeps the module reusable.

Publish the endpoint, not the whole kubeconfig. A module that returns a rendered kubeconfig file hands every caller a credential; a module that returns the host and CA lets the root keep the credential source. Return the two non-secret values and let the provider block own the rest.

A shared state merges failure domains. One state that spans two clusters makes a staging error block a production plan and turns a lock on one into a lock on both. State is a blast radius, and clusters have different ones.

State per cluster keeps destroy honest. A destroy in the production root cannot reach the staging cluster because it has no address for it. That separation is worth more than the convenience of a single apply.

Name the cluster in the module call. A label or a variable that names the cluster is not decoration; it is the only thing a reviewer can check when two aliases look alike in a diff.

One root with two aliases shares a failure domain, while one root per cluster does not The left panel shows a single root module holding both a production and a staging provider alias, wired into two clusters from one state, with a refresh failure aborting both plans and a swapped alias writing to the wrong cluster. The right panel shows two roots, each with one unaliased provider, one cluster and one state, so a forbidden call in staging stops only staging. The alias is the failure boundary Two credentials in one state cannot fail independently. One root, two aliases both clusters from one plan root module one state, one lock alias prod endpoint A alias staging endpoint B cluster A cluster B One failure stops both plans A swapped alias writes prod objects to staging One root per cluster no alias to mix up root prod provider kubernetes cluster A, state A root staging provider kubernetes cluster B, state B A 403 in staging stops staging Production plans and applies on its own schedule A swapped alias is a silent write to the wrong cluster

Prove the Target Cluster and Narrow Permission Set

Prove identity before permissions. The first question is which account the runner is, not what it may do. A self-subject review or the equivalent CLI call answers it, and the answer should match the identity you intended to deploy as.

The endpoint URL is the cluster's real name. Two clusters can share a name across accounts, projects or regions, and the host plus CA is what actually distinguishes them. Compare the endpoint against the published output before reading a single line of diff.

Scope the proof to a disposable namespace. A Role and a RoleBinding in one namespace prove the binding works without granting anything cluster-wide. A ClusterRoleBinding proves the opposite of what you want to know.

The denied call is the evidence. An allowed create shows that the path works; a denied cluster-scoped call shows that the permission stops where you designed it to stop. Run both and keep both results.

A data source read is the cheapest Terraform probe. Reading one existing namespace through the provider exercises endpoint, TLS, identity and authorization in a single plan, without proposing a change. If that read succeeds the configuration is proven; if it fails, nothing else in the root will work.

Record the proof with the change. The endpoint, the identity, the allowed verb and the denied verb belong in the pull request, because they are the facts a reviewer cannot reconstruct from a diff.

Clean up in the order you created. Delete the namespace and the objects inside it disappear with it, including the Role and RoleBinding. Nothing cluster-scoped is left for the next person to find.

Lab

Prove the Target Cluster and Narrow Permission Set

Execution status: design-only. These steps are a lab plan; no live cluster output is recorded here, and every identifier is written as a token rather than a real value.

Prerequisites. Terraform 1.17.1 with hashicorp/kubernetes 3.5.0, kubectl, one sandbox cluster you are allowed to break, and a credential that can create a namespace in it. The provider block pins the endpoint, the CA and one credential source; it does not read a second context from the environment.

CheckCommandExpected
endpointkubectl config view --minifythe host published by the cluster root
identitykubectl auth whoamithe account you intended to deploy as
allowed verbkubectl auth can-i create configmaps -n labyes
denied verbkubectl auth can-i delete nodesno, with the resource named
objectskubectl get all -n labone deployment and its pods
  1. Read the endpoint and CA from the cluster root's outputs and compare them with the provider block. A mismatch is a stop, not a warning.
  2. Confirm the identity with a self-subject review where the cluster supports it, otherwise list the permitted verbs in the namespace and read the account name from the output.
  3. Apply only a namespace-scoped Role and RoleBinding for the deploy identity, and grant the verbs the workload root actually uses: create, update and delete on the object kinds it owns.
  4. Plan a data source read of the existing lab namespace. Confirm the plan reports a read, not a create, and that it completes from the same runner that will apply.
  5. Apply one ConfigMap through the provider, then read it back with kubectl. The object name and the namespace in the output must match the resource address.
  6. Point the root at a second cluster and plan again. The read should fail on a missing namespace or a denied verb, and no object should appear in either cluster.
  7. Delete the ConfigMap through Terraform, then delete the namespace out of band and plan again. The provider should report the objects as missing and propose to create them, which is the drift signal that something moved without the root.

Expected observation. Step 4 proves reachability, TLS, identity and authorization without changing anything. Step 6 shows that the failure is loud and local: a wrong endpoint produces a missing object or a forbidden error, never a successful apply somewhere else.

Failure checks. The lab fails if a plan succeeds against an endpoint the root did not publish, if a denied cluster-scoped verb is allowed, if the deploy identity can read secrets it does not own, or if the wrong-cluster plan proposes creating objects.

Cleanup. If the namespace still exists, delete it and confirm the Role, RoleBinding and ConfigMap disappear with it. Then remove the lab block from the root so the next plan stops proposing to recreate what you deleted. Keep the cluster: destroying it is the cluster root's decision, not the workload root's.

Evidence to keep. The endpoint and CA values read from the outputs, the identity output, one allowed and one denied authorization result, and the plan that reported a read rather than a change.

Next in the Series

In Namespaces, RBAC and Service Accounts as Explicit Contracts, we'll explore Separate Kubernetes authorization from cloud IAM and model least-privilege workload identities.