CKAD — RBAC for ServiceAccounts

less than 1 minute read

ServiceAccount with RBAC

ServiceAccounts by themselves have no permissions. You need Role and RoleBinding (or ClusterRole/ClusterRoleBinding) to grant permissions.

# Create a Role that allows reading Pods
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
  name: pod-reader
  namespace: default
rules:
- apiGroups: [""]
  resources: ["pods"]
  verbs: ["get", "list", "watch"]
---
# Bind the Role to the ServiceAccount
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
  name: read-pods-binding
  namespace: default
subjects:
- kind: ServiceAccount
  name: app-sa
  namespace: default
roleRef:
  kind: Role
  name: pod-reader
  apiGroup: rbac.authorization.k8s.io
# Or using imperative commands
kubectl create role pod-reader --verb=get,list,watch --resource=pods
kubectl create rolebinding read-pods-binding --role=pod-reader --serviceaccount=default:app-sa

Test ServiceAccount Permissions

# Check what a ServiceAccount can do
kubectl auth can-i get pods --as=system:serviceaccount:default:app-sa
# Expected: yes

kubectl auth can-i delete pods --as=system:serviceaccount:default:app-sa
# Expected: no

kubectl auth can-i list secrets --as=system:serviceaccount:default:app-sa
# Expected: no

Next: Production Security →

Updated: