How does Kubernetes Role-Based Access Control (RBAC) restrict API access?
❓ Interview Prompt: Explain RBAC Roles, ClusterRoles, RoleBindings, ServiceAccounts, and least-privilege API access patterns in Kubernetes.
Kubernetes RBAC controls who (subject) can do what (verbs) on which resources (API objects).
RBAC Components:
ServiceAccounts for Pods:
Every Pod runs with a ServiceAccount — its token is auto-mounted at /var/run/secrets/kubernetes.io/serviceaccount/token and used to authenticate to the Kubernetes API.
Best Practice: Create dedicated ServiceAccounts per application with minimum required permissions. Never use the default ServiceAccount with broad permissions.
Common Verbs:
get, list, watch, create, update, patch, delete, deletecollection.
Code Implementation Example
# Step 1: Create a dedicated ServiceAccount for the API pod
apiVersion: v1
kind: ServiceAccount
metadata:
name: api-sa
namespace: app
automountServiceAccountToken: false # opt-in, not auto-mount
---
# Step 2: Define a Role — read-only access to ConfigMaps and Secrets
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
name: api-config-reader
namespace: app
rules:
- apiGroups: [""]
resources: ["configmaps", "secrets"]
verbs: ["get", "list"] # read-only — no create/delete
- apiGroups: [""]
resources: ["pods"]
verbs: ["get", "list", "watch"]
---
# Step 3: Bind the Role to the ServiceAccount
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
name: api-config-reader-binding
namespace: app
subjects:
- kind: ServiceAccount
name: api-sa
namespace: app
roleRef:
kind: Role
name: api-config-reader
apiGroup: rbac.authorization.k8s.ioRBAC = Role (what) + RoleBinding (who). Create per-app ServiceAccounts with minimum verbs. Never grant wildcard (*) permissions or bind to the default ServiceAccount.