Overview and What You Will Learn
Role-Based Access Control (RBAC) decides who can do what in a Kubernetes cluster, using rules that list allowed verbs on resources. RBAC is enabled by default on modern clusters, so the real risk is not a missing RBAC, it is overly broad grants such as cluster-admin given to a pipeline or a whole team. In this lab, you will build least-privilege access for a CI pipeline, a team of developers, and an SRE group, and then verify and audit it.
By the end of this guide you will be able to:
- Explain the four RBAC objects and how they combine into a policy
- Create namespace-scoped Roles and cluster-scoped ClusterRoles for different team personas
- Bind them to users, groups, and service accounts with RoleBindings and ClusterRoleBindings
- Verify permissions with
kubectl auth can-i, and test them with a real short-lived token - Find dangerous bindings, such as
cluster-admingrants, in an existing cluster
Why This Matters in Production
A service account with cluster-admin is a skeleton key. Imagine a CI/CD pipeline that only needs to deploy pods, but was given cluster-admin for convenience. If its token leaks, an attacker can read every Secret in every namespace and delete any workload. A Role limited to Deployments in one namespace would contain the same leak to a single team's services.
On a multi-team cluster at a company like Razorpay, Hotstar, or Zerodha, RBAC is what stops one squad's runaway script from deleting another squad's production workloads. It is a security and an operational control, and it is also what auditors ask to see.
Core Principles
RBAC has four objects, and one idea: permissions are only ever added, never subtracted. There are no deny rules, so a subject's access is the union of every rule bound to it.
- Role defines allowed verbs on resources inside one namespace.
- ClusterRole defines allowed verbs cluster-wide, or on cluster-scoped resources such as nodes.
- RoleBinding grants a Role or ClusterRole to subjects inside one namespace.
- ClusterRoleBinding grants a ClusterRole to subjects across the whole cluster.
The subjects that receive permissions are users, groups, and ServiceAccounts. Kubernetes has no user objects, so users and groups come from your identity provider or, on EKS, from IAM mappings.
User, Group, ServiceAccount] --> B[RoleBinding or
ClusterRoleBinding] B --> R[Role or ClusterRole
verbs on resources] R --> A([Allowed actions]) classDef subj fill:#8B5CF6,color:#FFFFFF classDef bind fill:#F97316,color:#FFFFFF classDef role fill:#326CE5,color:#FFFFFF classDef out fill:#10B981,color:#FFFFFF class S subj class B bind class R role class A out
The scope of a grant depends on which pair you combine:
| Combination | Scope | Typical use |
|---|---|---|
| Role + RoleBinding | One namespace | A team's access to its own namespace |
| ClusterRole + RoleBinding | One namespace | Reusing built-in view or edit in many namespaces |
| ClusterRole + ClusterRoleBinding | Whole cluster | SRE read access, nodes, and other cluster-wide resources |
RememberKubernetes ships four ready-made ClusterRoles:
viewfor read-only access,editfor read and write,adminfor full control of a namespace, andcluster-adminfor everything. Bind the smallest one that does the job.
Detailed Step-by-Step Practical Lab
Run this on any cluster where you are an administrator, such as kind, minikube, or a sandbox EKS cluster. Impersonation with --as needs administrator rights, and kubectl create token needs Kubernetes 1.24 or later.
How to Create Namespaces for Two Teams
kubectl create namespace paymentskubectl create namespace inventoryHow to Create a ServiceAccount for a CI Pipeline
Each workload gets its own identity. Do not reuse the default ServiceAccount, because every pod in the namespace shares it.
kubectl create serviceaccount ci-deployer -n paymentsHow to Write a Namespace-Scoped Role
This Role lets the pipeline manage Deployments, and read the objects it needs to watch a rollout. It cannot delete anything and cannot read Secrets.
apiVersion: rbac.authorization.k8s.io/v1kind: Rolemetadata: name: deployer namespace: paymentsrules: - apiGroups: ["apps"] resources: ["deployments"] verbs: ["get", "list", "watch", "create", "update", "patch"] - apiGroups: ["apps"] resources: ["replicasets"] verbs: ["get", "list", "watch"] - apiGroups: [""] # The empty string means the core API group resources: ["pods", "pods/log", "services"] verbs: ["get", "list", "watch"]kubectl apply -f deployer-role.yamlHow to Bind a Role to a ServiceAccount
A Role does nothing until a RoleBinding attaches it to a subject.
# deployer-binding.yamlapiVersion: rbac.authorization.k8s.io/v1kind: RoleBindingmetadata: name: ci-deployer-binding namespace: paymentssubjects: - kind: ServiceAccount name: ci-deployer namespace: paymentsroleRef: kind: Role name: deployer apiGroup: rbac.authorization.k8s.iokubectl apply -f deployer-binding.yamlTipA binding's
roleRefcannot be edited after creation. To change which role a binding points to, delete the binding and create it again.
How to Verify Permissions with kubectl auth can-i
Impersonate the ServiceAccount and ask Kubernetes what it may do. Each command prints yes or no.
SA="system:serviceaccount:payments:ci-deployer" kubectl auth can-i create deployments -n payments --as=$SA # yeskubectl auth can-i delete deployments -n payments --as=$SA # nokubectl auth can-i get secrets -n payments --as=$SA # nokubectl auth can-i create deployments -n inventory --as=$SA # no # The full list of what this identity can do in the namespacekubectl auth can-i --list -n payments --as=$SAHow to Test With a Real Short-Lived Token
Impersonation tests the rules, and a real token tests the whole path. Modern clusters no longer create long-lived token Secrets for ServiceAccounts, so request a token that expires in ten minutes.
TOKEN=$(kubectl create token ci-deployer -n payments --duration=10m) kubectl get pods -n payments --token="$TOKEN"# Allowed: No resources found in payments namespace. kubectl get secrets -n payments --token="$TOKEN"# Error from server (Forbidden): secrets is forbidden: User# "system:serviceaccount:payments:ci-deployer" cannot list resource "secrets"# in API group "" in the namespace "payments"How to Give a Team Read-Only Access by Reusing a ClusterRole
Developers in the payments-devs group should see everything in their own namespace and nothing elsewhere. Bind the built-in view ClusterRole with a RoleBinding, which limits it to one namespace.
# payments-devs-binding.yamlapiVersion: rbac.authorization.k8s.io/v1kind: RoleBindingmetadata: name: payments-devs-view namespace: paymentssubjects: - kind: Group name: payments-devs apiGroup: rbac.authorization.k8s.ioroleRef: kind: ClusterRole name: view apiGroup: rbac.authorization.k8s.iokubectl apply -f payments-devs-binding.yaml kubectl auth can-i list pods -n payments --as=priya@devops.in --as-group=payments-devs # yeskubectl auth can-i list pods -n inventory --as=priya@devops.in --as-group=payments-devs # nokubectl auth can-i delete pods -n payments --as=priya@devops.in --as-group=payments-devs # noHow to Grant Cluster-Wide Read Access to an SRE Group
Nodes are cluster-scoped, so a RoleBinding cannot grant access to them. Use a ClusterRole with a ClusterRoleBinding.
# sre-node-reader.yamlapiVersion: rbac.authorization.k8s.io/v1kind: ClusterRolemetadata: name: node-readerrules: - apiGroups: [""] resources: ["nodes", "namespaces"] verbs: ["get", "list", "watch"]# sre-node-reader-binding.yamlapiVersion: rbac.authorization.k8s.io/v1kind: ClusterRoleBindingmetadata: name: sre-node-readersubjects: - kind: Group name: sre-team apiGroup: rbac.authorization.k8s.ioroleRef: kind: ClusterRole name: node-reader apiGroup: rbac.authorization.k8s.iokubectl apply -f sre-node-reader.yaml -f sre-node-reader-binding.yaml kubectl auth can-i list nodes --as=rahul@devops.in --as-group=sre-team # yeskubectl auth can-i delete nodes --as=rahul@devops.in --as-group=sre-team # noHow to Stop Pods From Mounting API Credentials They Do Not Need
Most application pods never call the Kubernetes API. Turning off token mounting on the default ServiceAccount removes a credential an attacker could steal from a compromised container.
kubectl patch serviceaccount default -n payments \ -p '{"automountServiceAccountToken": false}'How to Audit a Cluster for Dangerous Bindings
List every ClusterRoleBinding that grants cluster-admin, and who receives it.
kubectl get clusterrolebindings -o json | jq -r ' .items[] | select(.roleRef.name == "cluster-admin") | .metadata.name + " -> " + ([.subjects[]? | .kind + "/" + .name] | join(", "))'Expect system:masters and a few system entries. Anything else, especially a ServiceAccount or a broad group, needs a justification. The kubectl who-can plugin, installed with kubectl krew install who-can, answers the reverse question, for example kubectl who-can get secrets -n payments.
How to Clean Up
kubectl delete namespace payments inventorykubectl delete clusterrolebinding sre-node-readerkubectl delete clusterrole node-readerProduction Best Practices & Common Pitfalls
Common MistakeGiving a pipeline or a team
cluster-adminbecause it is the quickest way to stop permission errors. Write a Role for what it really does, find the gaps withkubectl auth can-i, and add only the missing verbs.
SecuritySome permissions are more powerful than they look. Reading Secrets, using
pods/exec, creating pods in a namespace that holds Secrets, and theescalate,bind, andimpersonateverbs can all lead to wider access. Treat each as a sensitive grant.
TipKeep Roles, ClusterRoles, and bindings in Git and apply them through your normal review process. Every access change then has an author, a reviewer, and a history, which is exactly what an audit asks for.
- Bind groups, not individuals. Map teams from your identity provider, or from IAM roles on EKS through access entries, to Kubernetes groups, so joining or leaving a team needs no cluster change.
- Avoid wildcards. A rule with
verbs: ["*"]orresources: ["*"]quietly grants access to resource types that are added later. - Prefer namespace scope. Reach for a ClusterRoleBinding only for resources that are genuinely cluster-wide, and use a RoleBinding to a ClusterRole for the rest.
- Use one ServiceAccount per workload. A leaked token then exposes one app's permissions instead of everything sharing the default account.
- Never bind to broad system groups. Granting anything to
system:authenticatedorsystem:unauthenticatedgives it to every logged-in user or, worse, to everyone. - Review access on a schedule. Run the
cluster-adminaudit regularly, and remove bindings for people and pipelines that no longer exist.
Quick Reference & Troubleshooting Commands
| Command | Description |
|---|---|
kubectl auth can-i VERB RESOURCE -n NS --as=USER |
Test one permission for a user |
kubectl auth can-i --list -n NS --as=USER |
List everything a user can do in a namespace |
kubectl create token SA -n NS --duration=10m |
Get a short-lived ServiceAccount token |
kubectl get rolebindings,clusterrolebindings -A |
List every binding in the cluster |
kubectl describe clusterrole NAME |
Show the rules inside a ClusterRole |
kubectl who-can VERB RESOURCE -n NS |
Find who is allowed an action (krew plugin) |