Namespaces Organize Resources but Do Not Guarantee Isolation
A namespace is a scope for names and policy attachment, not a wall. It gives namespaced objects a unique name space, a default target for RoleBindings, ResourceQuotas and NetworkPolicies, and a cascade unit for deletion. It does not create a separate network, scheduler, kernel or cloud account.
Four different contracts hang off the same object. Authorization, capacity, admission labels and traffic policy are all attached at namespace scope, but each is enforced by a different component at a different moment. Treating "the namespace" as one security control hides which of the four is actually missing.
Labels are selectors, so editing one is a security change. The pod-security.kubernetes.io/enforce label gates admission, and NetworkPolicy peers select namespaces by label. A relabeling commit can therefore weaken admission or widen traffic without touching a single rule.
Quota answers a different question from authorization. RBAC decides whether this identity may send this request; quota decides whether the namespace has room for the resulting object. A fully authorized request can still be rejected, and a quota never narrows who may act.
NetworkPolicy is declared intent, not enforcement. The object is stored by the API server and enforced, if at all, by the CNI plugin. A cluster whose plugin ignores the policy will show a green manifest and pass every configuration test while pods talk freely.
Deletion is the sharpest namespace operation. Removing a namespace deletes every namespaced object inside it: Secrets, ConfigMaps, RoleBindings, service accounts and disruption budgets. Persistent volume reclaim is decided by the PV, not by the namespace, so data can outlive the delete and still be orphaned.
Figure 1 shows where each contract attaches, and the one path none of them closes.
%%{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
NS["Namespace payments
names, labels, deletion"] --> L["labels
PSA and namespaceSelector"]
NS --> Q["ResourceQuota and LimitRange
admission-time capacity"]
NS --> RB["RoleBinding
who may send which request"]
NS --> NP["NetworkPolicy
traffic intent"]
NP --> ENF{"Does the CNI
enforce NetworkPolicy?"}
ENF -->|"no"| OPEN["pod-to-pod traffic allowed
the object has no effect"]
ENF -->|"yes"| BLOCK["selected flows denied
and logged"]
L --> GAP["a label edit changes
admission and selection"]
Q --> CAP["an authorized request
can still be rejected"]
RB --> AUTH["a granted verb
is not granted traffic"]
OPEN --> CONC["the namespace alone is not
a network or tenant boundary"]
BLOCK --> PROOF["a boundary exists only
when a test proves it"]
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 NS,RB,AUTH primary;
class L,Q,CAP,NP secondary;
class ENF,BLOCK ok;
class OPEN,CONC danger;
class GAP,PROOF warn;
Read the traffic edge as the exception. Every other control is evaluated at admission or at request time by the API server. Pod-to-pod packets never ask the API server, which is why the namespace box has no wall around it until a CNI enforces one.
A namespace name is an API, not a filing choice. Other teams write it into cloud IAM conditions, network policies, dashboards and cost reports. It cannot be renamed either, so a move means creating the new scope, recreating every object in it and deleting the old one.
A namespace is still worth having. It gives ownership, a deletion boundary and a place to attach the other controls. It is simply not a tenant boundary on its own, and a review that stops at the namespace name has not reviewed anything.
Model Roles and Bindings Without Broad Administrative Grants
A Role is a list of rules; a binding is the sentence that names who gets them. Roles carry verbs, resources and API groups. Bindings carry subjects. Reviewing one without the other answers half the question.
RBAC is purely additive. The authorizer unions every rule from every binding that matches the subject, and there are no deny rules. You cannot carve an exception out of a broad grant; the only fix is to remove or replace the grant.
The binding decides the scope, not the role. A Role only has meaning inside a namespace. A ClusterRole is a reusable rule set with no scope of its own: bound with a RoleBinding it applies in that one namespace, bound with a ClusterRoleBinding it applies everywhere and to cluster-scoped resources. Figure 2 is the whole decision.
The bottom-right cell is the one to justify. A ClusterRoleBinding is not the cluster-wide edition of a role; it is a different grant that reaches namespaces created after the binding, including ones nobody has reviewed yet.
RoleBinding plus ClusterRole is the usual answer. Define the verbs once, bind them per namespace, and let the platform team own the ClusterRole while each application root owns only its binding. Cluster-scoped rules inside that ClusterRole are inert in a namespaced binding, which is a feature: one rule set can be reused without exporting its cluster reach.
Split ownership along the three objects. The platform team owns ClusterRoles and the small set of ClusterRoleBindings; the namespace owner owns Roles and RoleBindings inside it; the service account belongs to the workload that runs as it. When two roots claim the same binding name, the second apply takes the object over instead of merging with it.
A ServiceAccount subject needs its namespace spelled out. The provider defaults the subject namespace to default, and a RoleBinding only matches service accounts in its own namespace. Omit the field in a namespace called payments and the binding is accepted, applies to nothing, and looks correct in a diff.
Wildcards turn a namespace role into namespace admin. A rule that uses the wildcard for both verbs and resources covers Secrets, RoleBindings and Pods. Creating a Pod is enough to run as any service account in the namespace, unless an admission policy says otherwise. The bind and escalate verbs exist for the same reason: a subject holding either can manufacture a wider grant than it was given.
Bind groups, not people, and know when the group is resolved. A binding to a group survives staff changes without a Terraform edit, which is usually the right contract. Membership is resolved by the authenticator, though, so a removal takes effect when the identity next authenticates rather than when the binding changes.
Aggregated ClusterRoles belong to their controller. A ClusterRole can collect rules from other ClusterRoles through a label selector, which is how many add-ons extend the default roles. Editing the aggregated role by hand creates a rule that disappears the next time the controller reconciles, so manage the contributing role instead.
The built-in roles are coarse. The view role reads most objects but not Secrets. The edit role adds Secrets and workload writes, and admin adds role and binding management inside the namespace. A deployer that only rolls a Deployment does not need edit.
role_ref is immutable, so a repoint is a replacement. The provider replaces the binding when role_ref changes, which leaves a window with no grant at all. For load-bearing access, apply the new binding first, move the subject, then delete the old one.
Figure 3 follows the decision and keeps each failure attached to the choice that causes it.
%%{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
S["Subject: User, Group
or ServiceAccount plus namespace"] --> Q1{"Does the grant need
cluster-scoped objects?"}
Q1 -->|"yes: nodes, PVs,
CRDs, /metrics"| C1["ClusterRole plus
ClusterRoleBinding"]
Q1 -->|"no"| Q2{"Same rules needed in
several namespaces?"}
Q2 -->|"yes"| C2["ClusterRole plus one
RoleBinding per namespace"]
Q2 -->|"no"| C3["Role plus RoleBinding
in that namespace"]
C1 --> W{"Wildcard verbs
or resources?"}
C2 --> W
C3 --> W
W -->|"yes"| E1["namespace admin by another name
Secrets, bindings, pods"]
W -->|"no"| OK["smallest reviewable grant"]
C3 --> E2["SA subject in another namespace
matches no pod"]
E1 --> R["enumerate verbs and resources"]
R --> OK
E2 --> F["set the subject namespace
explicitly"]
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 S,Q1,Q2,W primary;
class C1,C2,C3 secondary;
class OK,F ok;
class E1,E2 danger;
class R warn;
The flow ends where the review begins. Every branch converges on "enumerate", because the only durable contract is a named subject, a named namespace and a short list of verbs and resources.
Keep Runner and Workload Service Accounts Separate
Two credentials, two jobs. The Terraform runner authenticates to the API with a kubeconfig or an exec plugin, as the previous part established. A workload authenticates with a projected token. Reusing one service account for both merges an operator credential and an application identity into one auditable object.
Sharing the account breaks three things at once. Audit logs can no longer separate an apply from a compromised pod, rotating the workload's cloud annotation breaks the runner, and the workload inherits every permission the runner needed.
The runner may not be a service account at all. Managed clusters commonly authenticate the pipeline's cloud identity and map it to a Kubernetes user or group, as EKS access entries, AKS groups and GKE IAM bindings do. In that case the runner's RBAC subject is a User or Group, and the only service account in the picture is the one workloads use. That separation is the point.
Give the runner an enumerated, namespace-scoped grant. The verbs it needs are the ordinary create, read, update and delete set on the resource types it owns, plus bind on the specific ClusterRoles it may hand out. Cluster-admin for a pipeline converts one leaked token into the whole cluster.
The ability to create bindings is itself an escalation path. A subject that can create RoleBindings in a namespace can grant any role it is allowed to bind, including to a service account it controls. Keep role creation in a platform root when a team should not self-grant, and scope bind to a short list.
Tokens are short-lived and audience-bound by default. Since Kubernetes 1.22 the kubelet requests a projected token through the TokenRequest API, with a default lifetime of one hour and automatic rotation. There is nothing to store, and nothing for Terraform to rotate.
Legacy token Secrets are the exception, and a bad one. Automatic creation of non-expiring token Secrets stopped in 1.24, but the API still allows one to be created by hand. Declaring it in Terraform writes a credential that never expires into state and every saved plan.
Automount is a default, not a guarantee. Setting automount_service_account_token = false stops the automatic mount for pods that use the account, and a pod can still request a token through a projected volume. Set it false on the namespace's default account and make each workload opt in with its own.
The default account is a real object you can adopt. A dedicated resource manages the controller-created account, once per namespace, which is the clean way to turn automount off without deleting the account every pod falls back to.
Image pull credentials belong to the same contract. The service account can carry pull secrets and pods inherit them, but the referenced secret must live in the same namespace. Prefer a node-level credential provider tied to the node identity, so the cluster holds no long-lived registry password at all.
A dedicated account per workload is what makes the cloud bridge possible. Cloud integrations match a namespace and an account name, so a single shared account collapses every workload onto one cloud role and erases the per-workload audit trail the bridge is supposed to provide.
Bridge to Cloud IAM Only Through the Selected Integration
Kubernetes RBAC never grants a cloud permission. A pod's projected token is addressed to the API server. Calling an object store, a queue or a managed database requires a token from the cloud's token service, issued only because a trust relationship accepted the pod's identity.
The bridge is a trust policy with a literal subject. The common shape has three parts: an issuer the cluster publishes, a subject string naming the namespace and account, and an audience the cloud expects. The cloud role trusts that issuer for that subject.
Terraform spans two providers and one ordering constraint. The Kubernetes provider creates the namespace, account and annotation; the cloud provider creates the role and the trust or federation object. The cluster issuer must exist before the trust policy can name it, so the two roots are staged rather than merged.
Stage the issuer before the trust. The trust object always references an issuer the cluster must already publish. Create or enable the issuer in the cluster root, expose its URL as an output, and let the identity root consume it. Merging the two roots invites a plan against an issuer that does not exist yet, and the error arrives as a provider failure rather than a review finding.
The table is the comparison worth keeping; the last column is where the diagnosis starts.
| Platform | Kubernetes-side contract | Cloud-side object | Breaks when |
|---|---|---|---|
| EKS, IRSA | annotation eks.amazonaws.com/role-arn on the account | IAM role trust policy naming the cluster OIDC provider and a sub condition | the sub string names a different namespace or account |
| EKS, Pod Identity | no annotation; an association names cluster, namespace and account | IAM role trusting pods.eks.amazonaws.com | the association is missing or the agent DaemonSet is absent |
| AKS | annotation azure.workload.identity/client-id, plus the pod label azure.workload.identity/use | federated identity credential on the managed identity | the pod lacks the label, so the webhook injects nothing |
| GKE | annotation iam.gke.io/gcp-service-account on the account | roles/iam.workloadIdentityUser for the NS/KSA member in the project pool | the member string or the pool name is wrong |
| ACK | annotation ack.alibabacloud.com/role-arn on the account | RAM role trust policy naming the cluster OIDC provider | the provider ARN or the sub condition is wrong |
| OKE | no annotation; identity is the cluster, namespace and account triple | OCI policy conditions on request.principal | the cluster is not enhanced, or a condition names another account |
Every row fails in the same place. The Kubernetes object is created successfully, the cluster stays healthy, and the workload fails when it asks for a cloud token. Terraform will report a clean apply, because neither provider validates the other side's subject string.
Figure 4 draws that chain and the two places it breaks.
The break is never in the Kubernetes object. The service account exists, the annotation is stored, and the token is issued. What fails is the exchange, because the trust policy compared a string the workload never controlled and a string Terraform cannot read back.
An annotation change is not retroactive. The webhook or credential plugin reads the annotation when a pod is admitted, so running pods keep the old environment until they are recreated. A rollout is part of the identity change, not a follow-up task.
Read the error as a layer, not a verdict. A 401 means no valid credential reached the API server. A 403 means a valid identity lacked the verb. A cloud error naming a trust, audience or subject means the exchange failed before any role was consulted. Only the middle case is an RBAC problem.
The token audience is part of the contract. A workload's projected token is addressed to the Kubernetes API, so a cloud token service will not accept it as-is. The integration requests its own audience, and a mismatch there fails the exchange even when the subject string is perfect.
Never widen the cloud role to make the bridge work. A wildcard action hides the same problem one layer down. Enumerate actions against the calls the workload actually makes, and treat the first access-denied error as evidence about the trust chain rather than a reason to add permissions.
Prove a Workload Can Perform Only Its Intended Operations
The lab proves what a plan cannot. A no-change baseline shows the configuration matches the cluster, and a pair of server-side authorization checks shows that one verb is allowed and its neighbour is denied. Run it in a disposable namespace with Terraform 1.17.1 and hashicorp/kubernetes 3.5.0.
Prove a Workload Can Perform Only Its Intended Operations
Execution status: design-only. These steps were not run against a live cluster for this article. The sequence is written to be executed and recorded, not quoted as a transcript.
Prerequisites. A disposable namespace on a cluster you can afford to break, Terraform 1.17.1 with hashicorp/kubernetes 3.5.0, and kubectl with permission to impersonate service accounts or to create pods. No cloud identity integration is required for the core proof.
- Record the baseline. Create the namespace with a label that pins Pod Security to the baseline level, then run a plan. Expect no changes after the first apply; anything else is drift you did not create.
- Write the role once. Declare a Role in the lab namespace with get, list and watch on configmaps only. No wildcards, no Secrets, no pod creation.
- Bind the account explicitly. Add a RoleBinding whose subject is a ServiceAccount named config-reader, and set the subject namespace even though it matches. The provider would otherwise default it to
default. - Ask the server, not the file. Run
kubectl auth can-i get configmaps --as=system:serviceaccount:rbac-lab:config-reader -n rbac-laband expect yes. This is a SubjectAccessReview, so the answer comes from the authorizer. - Ask for the neighbour verb. Repeat with
deleteand then with get on secrets. Expect no for both, and record the exact verb and resource rather than a screenshot. - Ask from another namespace. Repeat the allowed check with
-n default. Expect no, because a RoleBinding grants only where it lives. - Run the real workload. Deploy a pod with
serviceAccountNameset to the account, exec into it, and call the API with the mounted token. Expect the ConfigMap list to succeed and the Secret read to return 403. - Prove the token is optional. Deploy a second pod with an account whose automount is off, and confirm there is no projected token to read. Expect the same call to fail as unauthenticated rather than forbidden.
- Add the cloud bridge last. If the cluster has an identity integration, add the annotation, recreate the pod, and confirm the cloud SDK receives credentials. Remove the annotation, recreate, and confirm the failure is a trust error rather than a Kubernetes 403.
- Destroy without collateral. Delete the namespace and confirm the Role, binding and accounts are gone. Confirm the lab created no cluster-scoped object that survives the namespace.
| Check | Evidence | Pass looks like |
|---|---|---|
| Baseline | plan after the first apply | no changes, no replacement |
| Allowed verb | SubjectAccessReview in the lab namespace | yes for get on configmaps |
| Denied verb | the same review for delete | no, with the verb named |
| Denied resource | the same review for secrets | no, even though both are in the same namespace |
| Scope | the allowed check in another namespace | no, because the binding is local |
| Runtime | a request from inside the pod | list succeeds, secret read returns 403 |
| Tokenless pod | a second account with automount off | no token mounted, request unauthenticated |
| Cleanup | plan and object listing after delete | only the namespace's objects disappear |
Expected observation. The RoleBinding produces a yes for the allowed verb and a no for every neighbour, and the same subject fails in a namespace where it has no binding. The tokenless pod fails authentication rather than authorization, which is the difference between a missing credential and a missing grant.
Failure checks. If the allowed check returns no, the subject namespace is probably wrong or the binding references a different role name. If the denied check returns yes, a broader binding already matches the subject, so review the union rather than the file you just wrote. If the in-pod call returns 401, the token is absent or expired; a 403 means the token is valid and the rule is missing.
Cost dimensions. The lab is close to free: one namespace, one pod, one Role and one binding. Leaving a load balancer or a persistent volume behind is the only realistic charge, and this lab creates neither.
Cleanup. Delete the namespace, then confirm the RoleBinding and accounts are gone with it. Run a final plan to prove the root manages nothing else, and check that no cluster-scoped object was created for a namespaced experiment.
The record is the deliverable. Keep the baseline plan, the two review answers and the cleanup listing together. A reviewer can then see who was allowed, where, and what proved it, without rerunning the lab.
Next in the Series
In Workloads and Rollouts: Deployments, Probes, Jobs and Scaling, we'll explore Configure desired workloads while treating controller convergence and application health as separate evidence.