← Full reference

Kubernetes: ServiceAccount, Role, RoleBinding

Kubernetes permissions — ServiceAccount, Role and ClusterRole, apiGroups/resources/verbs rules, bindings, pod token

RBAC (role-based access control) decides who can do what in the Kubernetes API. The scheme has three parts:

PartObjectsWhat it describes
WhoServiceAccount (for programs in pods), User and Group (people; these aren't Kubernetes objects — they come from a certificate or external authentication)the subject
What's allowedRole (in one namespace), ClusterRole (across the whole cluster or as a template)a set of "resources × actions" rules
The linkRoleBinding (in a namespace), ClusterRoleBinding (across the whole cluster)grants a role to subjects

Rules only allow: there are no deny rules, and everything is denied by default. A subject's permissions are the union of all roles bound to it.

Syntax

apiVersion: v1
kind: ServiceAccount
metadata:
  name: app
  namespace: dev
---
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
  name: pod-reader
  namespace: dev
rules:
  - apiGroups: [""]               # "" — the core group: pods, services, configmaps…
    resources: ["pods"]
    verbs: ["get", "list", "watch"]
---
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
  name: app-pod-reader
  namespace: dev
subjects:
  - kind: ServiceAccount
    name: app
    namespace: dev
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: Role
  name: pod-reader

Without a cluster you can generate ServiceAccount, RoleBinding and ClusterRoleBinding (kubectl create serviceaccount|rolebinding|clusterrolebinding … --dry-run=client -o yaml). kubectl create role and create clusterrole contact the server even with --dry-run=client — write roles by hand or build them with yq.

ServiceAccount

FieldMeaningDefault / notes
metadata.name, metadata.namespacename; a ServiceAccount always lives in a namespaceevery namespace has a default ServiceAccount
automountServiceAccountTokenwhether to mount the token into pods using this accounttrue
imagePullSecrets[{name: secret}] — added to all pods using this account

In a pod:

Pod spec fieldMeaningDefault
serviceAccountNamewhich ServiceAccount the pod uses to talk to the APIdefault
automountServiceAccountTokenwhether to mount the token; overrides the ServiceAccount settingas in the ServiceAccount

The token is mounted at /var/run/secrets/kubernetes.io/serviceaccount/: files token (JWT), ca.crt (the API server certificate), namespace. The token is short-lived; kubelet refreshes it itself. In the API a ServiceAccount appears as the user system:serviceaccount:<namespace>:<name> and belongs to the groups system:serviceaccounts and system:serviceaccounts:<namespace>.

Role and ClusterRole

RoleClusterRole
Where it appliesonly in its own namespace (metadata.namespace)across the whole cluster — or in one namespace via a RoleBinding
Resourcesnamespaced: pods, deployments, secrets…also cluster-scoped: nodes, namespaces, persistentvolumes, clusterroles
Non-resource URLsnononResourceURLs: ["/healthz", "/metrics"]

Fields of a rules[] element:

FieldMeaningExamples
apiGroupsAPI group — the part of apiVersion before /"" (v1: pods, services, configmaps, secrets, serviceaccounts), apps (deployments, statefulsets, daemonsets, replicasets), batch (jobs, cronjobs), networking.k8s.io (ingresses, networkpolicies), autoscaling, rbac.authorization.k8s.io, "*" — all
resourcesresources in plural, lowercasepods, deployments; subresources: pods/log, pods/exec, deployments/scale; "*" — all
verbsactionssee the table below; "*" — all
resourceNamesonly objects with these names["app-config"]; doesn't work with create and deletecollection
nonResourceURLsURLs outside resources (ClusterRole only)["/healthz", "/version"] with verbs: ["get"]

Actions (verbs) and what they correspond to:

VerbRequestExample command
getread one objectkubectl get pod web-1, describe
lista listkubectl get pods
watchwatch for changeskubectl get pods -w
createcreatekubectl create, apply of a new object; create on pods/exec — kubectl exec
updatereplace entirelykubectl replace
patchmodify partiallykubectl apply of an existing object, scale, label, edit
deletedelete onekubectl delete pod web-1
deletecollectiondelete manykubectl delete pods --all

kubectl apply needs get, create and patch all together.

A ClusterRole also has aggregationRule: {clusterRoleSelectors: [{matchLabels: …}]} — the role automatically collects the rules of other ClusterRoles with these labels. That's how the built-in admin, edit, view work.

RoleBinding and ClusterRoleBinding

FieldMeaningNotes
subjects[].kindServiceAccount / User / Group
subjects[].namesubject namefor ServiceAccount groups: system:serviceaccounts:dev
subjects[].namespacethe ServiceAccount's namespacerequired for ServiceAccount
subjects[].apiGrouprbac.authorization.k8s.io for User and Group; for ServiceAccount — omit it ("")
roleRef.kindRole or ClusterRole
roleRef.namerole name
roleRef.apiGroupalways rbac.authorization.k8s.io

Possible combinations:

BindingRoleResult
RoleBindingRole from the same namespacepermissions in that namespace
RoleBindingClusterRolethe ClusterRole's permissions, but only in the binding's namespace — handy for defining a role once and granting it per namespace
ClusterRoleBindingClusterRolepermissions in all namespaces and on cluster-scoped resources
ClusterRoleBindingRolenot possible

Built-in ClusterRoles: view (read-only without secrets), edit (modify most objects, without roles), admin (full access in a namespace, including roles), cluster-admin (everything).

Examples

# ServiceAccount and bindings — the generators work offline
kubectl create serviceaccount ci -n dev --dry-run=client -o yaml > sa.yaml
kubectl create rolebinding ci-edit -n dev --clusterrole=edit \
  --serviceaccount=dev:ci --dry-run=client -o yaml > rb.yaml
kubectl create rolebinding devs-view -n dev --clusterrole=view \
  --user=alice --group=developers --dry-run=client -o yaml
kubectl create clusterrolebinding ci-nodes --clusterrole=node-reader \
  --serviceaccount=dev:ci --dry-run=client -o yaml > crb.yaml

# Role: `kubectl create role` needs a cluster — build it with yq
yq -n '
  .apiVersion = "rbac.authorization.k8s.io/v1" |
  .kind = "Role" |
  .metadata = {"name": "deployer", "namespace": "dev"} |
  .rules = [
    {"apiGroups": ["apps"], "resources": ["deployments"], "verbs": ["get", "list", "create", "patch"]},
    {"apiGroups": [""], "resources": ["pods", "pods/log"], "verbs": ["get", "list"]}
  ]' > role.yaml

# bind it instead of the ClusterRole — edit roleRef the same way
yq '.roleRef.kind = "Role" | .roleRef.name = "deployer" | .metadata.name = "ci-deployer"' rb.yaml > rb-role.yaml

# disable token mounting for all pods using this account
yq -i '.automountServiceAccountToken = false' sa.yaml

kubeconform -strict -summary sa.yaml rb.yaml crb.yaml role.yaml rb-role.yaml

# in a cluster (won't work here):
# kubectl auth can-i create deployments -n dev --as=system:serviceaccount:dev:ci
# kubectl auth can-i --list -n dev --as=system:serviceaccount:dev:ci
# kubectl create token ci -n dev --duration=1h

A ClusterRole for reading nodes and namespaces, and a cluster-wide binding:

apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
  name: node-reader               # cluster-scoped objects have no namespace
rules:
  - apiGroups: [""]
    resources: ["nodes", "namespaces"]
    verbs: ["get", "list", "watch"]
  - nonResourceURLs: ["/healthz", "/version"]
    verbs: ["get"]
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
  name: monitoring-node-reader
subjects:
  - kind: ServiceAccount
    name: monitoring
    namespace: observability
  - kind: Group
    name: sre
    apiGroup: rbac.authorization.k8s.io
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: ClusterRole
  name: node-reader

Access to one specific ConfigMap, and a pod without a token:

apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
  name: read-app-config
  namespace: dev
rules:
  - apiGroups: [""]
    resources: ["configmaps"]
    resourceNames: ["app-config"]
    verbs: ["get", "watch"]
---
apiVersion: v1
kind: Pod
metadata:
  name: static-site
  namespace: dev
spec:
  serviceAccountName: default
  automountServiceAccountToken: false   # the app doesn't need the API — don't mount the token
  containers:
    - name: web
      image: nginx:1.27

Pitfalls

  • A wrong apiGroups is the most common mistake. Deployment lives in apps, not ""; Ingress in networking.k8s.io; CronJob in batch. The group is the part of apiVersion before /, and for apiVersion: v1 the group is empty: "".
  • The resource name is plural and lowercase. Pod, pod, Deployment in resources grant nothing: you need pods, deployments. The schema doesn't check this.
  • Subresources are separate. Permission on pods doesn't let you read logs or exec: you need pods/log (get) and pods/exec (create).
  • list exposes the contents. list on secrets returns the secrets in full, not just the names. Grant permissions on secrets as narrowly as possible.
  • roleRef can't be changed on an existing binding: only deleted and recreated. subjects can be changed.
  • namespace for a ServiceAccount in subjects is required, otherwise the API rejects the binding. The schema doesn't catch this.
  • --serviceaccount in kubectl create rolebinding takes the form namespace:name. Just --serviceaccount=ci is an error.
  • A RoleBinding won't find a Role from another namespace: roleRef looks for a Role only in its own namespace.
  • A ClusterRoleBinding to edit or admin grants permissions in all namespaces. If you need just one — a RoleBinding to the same ClusterRole.
  • You can't grant more than you have. The API won't let you create a Role or binding with permissions you don't have yourself (without the special escalate/bind verbs).
  • The token is mounted even if the program doesn't need the API. Anyone who gets a shell in the container can use its permissions. Where the API isn't needed — automountServiceAccountToken: false.
  • The default ServiceAccount is used by all pods without serviceAccountName. Grant permissions to default and every such pod in the namespace gets them. Create a dedicated ServiceAccount for the app.
  • Access errors are visible only in a cluster: Forbidden: User "system:serviceaccount:dev:ci" cannot list resource "pods" … in the namespace "dev". The message shows right away which verb, resource and namespace is missing.

See also

kubectl · kubeconform · yq · k8s-workloads · k8s-config · sudo · chmod