Skip to main content

Implementing Kubernetes RBAC for Least Privilege

Implement Kubernetes RBAC with Roles, ClusterRoles, and ServiceAccounts to enforce least-privilege access across multi-team production clusters.

52 Terms

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-admin grants, 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.

  1. Role defines allowed verbs on resources inside one namespace.
  2. ClusterRole defines allowed verbs cluster-wide, or on cluster-scoped resources such as nodes.
  3. RoleBinding grants a Role or ClusterRole to subjects inside one namespace.
  4. 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.

flowchart TD S[Subject
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
Remember

Kubernetes ships four ready-made ClusterRoles: view for read-only access, edit for read and write, admin for full control of a namespace, and cluster-admin for 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
Bash
kubectl create namespace payments
kubectl create namespace inventory
How 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.

Bash
kubectl create serviceaccount ci-deployer -n payments
How 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.

YAML
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
name: deployer
namespace: payments
rules:
- 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"]
Bash
kubectl apply -f deployer-role.yaml
How to Bind a Role to a ServiceAccount

A Role does nothing until a RoleBinding attaches it to a subject.

YAML
# deployer-binding.yaml
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
name: ci-deployer-binding
namespace: payments
subjects:
- kind: ServiceAccount
name: ci-deployer
namespace: payments
roleRef:
kind: Role
name: deployer
apiGroup: rbac.authorization.k8s.io
Bash
kubectl apply -f deployer-binding.yaml
Tip

A binding's roleRef cannot 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.

Bash
SA="system:serviceaccount:payments:ci-deployer"
kubectl auth can-i create deployments -n payments --as=$SA # yes
kubectl auth can-i delete deployments -n payments --as=$SA # no
kubectl auth can-i get secrets -n payments --as=$SA # no
kubectl auth can-i create deployments -n inventory --as=$SA # no
# The full list of what this identity can do in the namespace
kubectl auth can-i --list -n payments --as=$SA
How 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.

Bash
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.

YAML
# payments-devs-binding.yaml
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
name: payments-devs-view
namespace: payments
subjects:
- kind: Group
name: payments-devs
apiGroup: rbac.authorization.k8s.io
roleRef:
kind: ClusterRole
name: view
apiGroup: rbac.authorization.k8s.io
Bash
kubectl apply -f payments-devs-binding.yaml
kubectl auth can-i list pods -n payments --as=priya@devops.in --as-group=payments-devs # yes
kubectl auth can-i list pods -n inventory --as=priya@devops.in --as-group=payments-devs # no
kubectl auth can-i delete pods -n payments --as=priya@devops.in --as-group=payments-devs # no
How 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.

YAML
# sre-node-reader.yaml
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
name: node-reader
rules:
- apiGroups: [""]
resources: ["nodes", "namespaces"]
verbs: ["get", "list", "watch"]
YAML
# sre-node-reader-binding.yaml
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
name: sre-node-reader
subjects:
- kind: Group
name: sre-team
apiGroup: rbac.authorization.k8s.io
roleRef:
kind: ClusterRole
name: node-reader
apiGroup: rbac.authorization.k8s.io
Bash
kubectl 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 # yes
kubectl auth can-i delete nodes --as=rahul@devops.in --as-group=sre-team # no
How 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.

Bash
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.

Bash
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
Bash
kubectl delete namespace payments inventory
kubectl delete clusterrolebinding sre-node-reader
kubectl delete clusterrole node-reader

Production Best Practices & Common Pitfalls

Common Mistake

Giving a pipeline or a team cluster-admin because it is the quickest way to stop permission errors. Write a Role for what it really does, find the gaps with kubectl auth can-i, and add only the missing verbs.

Security

Some permissions are more powerful than they look. Reading Secrets, using pods/exec, creating pods in a namespace that holds Secrets, and the escalate, bind, and impersonate verbs can all lead to wider access. Treat each as a sensitive grant.

Tip

Keep 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: ["*"] or resources: ["*"] 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:authenticated or system:unauthenticated gives it to every logged-in user or, worse, to everyone.
  • Review access on a schedule. Run the cluster-admin audit 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)

Resources

Velero vs etcd Snapshot: Which Do You Need?

Velero vs etcd Snapshot: Which Do You Need?

Velero and etcd snapshots protect different layers of a Kubernetes cluster. See what each backs up, what each misses, and why most DR needs both.

11 min read•Aug 2026
Istio Ambient vs Linkerd in 2026: Which Mesh?

Istio Ambient vs Linkerd in 2026: Which Mesh?

Istio Ambient cuts the sidecar tax at L4, but L7 adds waypoint hops, and Linkerd stable builds now come from Buoyant. Choose with tests.

11 min read•Aug 2026
Nginx Ingress vs Traefik vs Gateway API in 2026

Nginx Ingress vs Traefik vs Gateway API in 2026

Ingress-NGINX is retired. Compare Traefik and Gateway API controllers as replacements, plus a safe migration plan that avoids outages.

10 min read•Aug 2026
OPA Gatekeeper vs Kyverno: Policy Engine in 2026

OPA Gatekeeper vs Kyverno: Policy Engine in 2026

OPA Gatekeeper vs Kyverno compared for 2026: Rego vs YAML, mutation, reporting, and operations, plus how to pick a Kubernetes policy engine.

10 min read•Aug 2026
Helm vs Kustomize in 2026: Templating vs Patching

Helm vs Kustomize in 2026: Templating vs Patching

Helm vs Kustomize compared for 2026 - templating vs patching, Helm 4's new features, and why most production teams end up running both.

5 min read•Aug 2026
Prometheus vs Datadog vs New Relic: Real Costs

Prometheus vs Datadog vs New Relic: Real Costs

Prometheus, Datadog, and New Relic compared for 2026 - real pricing at scale, hidden cost drivers, and which fits a Kubernetes-heavy stack.

5 min read•Aug 2026
Cluster Autoscaler vs Karpenter for EKS in 2026

Cluster Autoscaler vs Karpenter for EKS in 2026

Cluster Autoscaler vs Karpenter on EKS: scale-up speed, bin-packing, Spot handling, Auto Mode limits and a safe migration path, with v1 NodePool YAML.

11 min read•Aug 2026
GKE vs EKS vs AKS in 2026: Which Fits Your Team?

GKE vs EKS vs AKS in 2026: Which Fits Your Team?

GKE, EKS, and AKS compared for 2026 - control plane pricing, Autopilot vs Karpenter vs Node Auto Provisioning, and which platform actually fits your team.

5 min read•Aug 2026
K3s vs K8s vs MicroK8s: Which Distro in 2026?

K3s vs K8s vs MicroK8s: Which Distro in 2026?

Compare K3s, upstream Kubernetes and MicroK8s on footprint, datastores, HA and updates, and pick the right fit for edge, dev or production.

10 min read•Aug 2026
Canary Deployments with Argo Rollouts & Flagger

Canary Deployments with Argo Rollouts & Flagger

Ship to 5% of users first and auto-rollback on bad metrics: canary deployments on Kubernetes with Argo Rollouts, Flagger, and Gateway API.

11 min read•Jun 2026
OpenTelemetry Explained: Metrics, Logs, Traces

OpenTelemetry Explained: Metrics, Logs, Traces

OpenTelemetry in practice: instrument a Node.js service, run a production Collector, sample traces and link metrics, logs and traces in Grafana.

11 min read•Jun 2026
Kubernetes Cost Optimization Without SLO Risk

Kubernetes Cost Optimization Without SLO Risk

Kubernetes clusters average about 8% CPU use. Cut waste safely with request rightsizing, autoscaling, spot, and OpenCost, keeping SLOs.

11 min read•Jun 2026
ArgoCD vs FluxCD: GitOps for Kubernetes in 2026

ArgoCD vs FluxCD: GitOps for Kubernetes in 2026

ArgoCD vs FluxCD compared for 2026: UI, multi-tenancy, Helm, image automation and pruning risks, with a clear guide to picking your GitOps engine.

10 min read•Jun 2026

Explore More in Kubernetes Security and Access Control

All 3 Topics

Frequently Asked Questions

Is Implementing Kubernetes RBAC for Least Privilege free to learn on DevOps Network?

Yes - this topic, like everything on DevOps Network, is 100% free with no paywall or sign-up gate.

What does the Implementing Kubernetes RBAC for Least Privilege topic cover?

Implement Kubernetes RBAC with Roles, ClusterRoles, and ServiceAccounts to enforce least-privilege access across multi-team production clusters.

Found a mistake, an outdated step or a broken link?