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:
| Part | Objects | What it describes |
|---|---|---|
| Who | ServiceAccount (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 allowed | Role (in one namespace), ClusterRole (across the whole cluster or as a template) | a set of "resources × actions" rules |
| The link | RoleBinding (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
| Field | Meaning | Default / notes |
|---|---|---|
metadata.name, metadata.namespace | name; a ServiceAccount always lives in a namespace | every namespace has a default ServiceAccount |
automountServiceAccountToken | whether to mount the token into pods using this account | true |
imagePullSecrets | [{name: secret}] — added to all pods using this account |
In a pod:
Pod spec field | Meaning | Default |
|---|---|---|
serviceAccountName | which ServiceAccount the pod uses to talk to the API | default |
automountServiceAccountToken | whether to mount the token; overrides the ServiceAccount setting | as 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
| Role | ClusterRole | |
|---|---|---|
| Where it applies | only in its own namespace (metadata.namespace) | across the whole cluster — or in one namespace via a RoleBinding |
| Resources | namespaced: pods, deployments, secrets… | also cluster-scoped: nodes, namespaces, persistentvolumes, clusterroles |
| Non-resource URLs | no | nonResourceURLs: ["/healthz", "/metrics"] |
Fields of a rules[] element:
| Field | Meaning | Examples |
|---|---|---|
apiGroups | API 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 |
resources | resources in plural, lowercase | pods, deployments; subresources: pods/log, pods/exec, deployments/scale; "*" — all |
verbs | actions | see the table below; "*" — all |
resourceNames | only objects with these names | ["app-config"]; doesn't work with create and deletecollection |
nonResourceURLs | URLs outside resources (ClusterRole only) | ["/healthz", "/version"] with verbs: ["get"] |
Actions (verbs) and what they correspond to:
| Verb | Request | Example command |
|---|---|---|
get | read one object | kubectl get pod web-1, describe |
list | a list | kubectl get pods |
watch | watch for changes | kubectl get pods -w |
create | create | kubectl create, apply of a new object; create on pods/exec — kubectl exec |
update | replace entirely | kubectl replace |
patch | modify partially | kubectl apply of an existing object, scale, label, edit |
delete | delete one | kubectl delete pod web-1 |
deletecollection | delete many | kubectl 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
| Field | Meaning | Notes |
|---|---|---|
subjects[].kind | ServiceAccount / User / Group | |
subjects[].name | subject name | for ServiceAccount groups: system:serviceaccounts:dev |
subjects[].namespace | the ServiceAccount's namespace | required for ServiceAccount |
subjects[].apiGroup | rbac.authorization.k8s.io for User and Group; for ServiceAccount — omit it ("") | |
roleRef.kind | Role or ClusterRole | |
roleRef.name | role name | |
roleRef.apiGroup | always rbac.authorization.k8s.io |
Possible combinations:
| Binding | Role | Result |
|---|---|---|
| RoleBinding | Role from the same namespace | permissions in that namespace |
| RoleBinding | ClusterRole | the ClusterRole's permissions, but only in the binding's namespace — handy for defining a role once and granting it per namespace |
| ClusterRoleBinding | ClusterRole | permissions in all namespaces and on cluster-scoped resources |
| ClusterRoleBinding | Role | not 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
apiGroupsis the most common mistake. Deployment lives inapps, not""; Ingress innetworking.k8s.io; CronJob inbatch. The group is the part ofapiVersionbefore/, and forapiVersion: v1the group is empty:"". - The resource name is plural and lowercase.
Pod,pod,Deploymentinresourcesgrant nothing: you needpods,deployments. The schema doesn't check this. - Subresources are separate. Permission on
podsdoesn't let you read logs or exec: you needpods/log(get) andpods/exec(create). listexposes the contents.listonsecretsreturns the secrets in full, not just the names. Grant permissions on secrets as narrowly as possible.roleRefcan't be changed on an existing binding: only deleted and recreated.subjectscan be changed.namespacefor a ServiceAccount insubjectsis required, otherwise the API rejects the binding. The schema doesn't catch this.--serviceaccountinkubectl create rolebindingtakes the formnamespace:name. Just--serviceaccount=ciis an error.- A RoleBinding won't find a Role from another namespace:
roleReflooks for a Role only in its own namespace. - A ClusterRoleBinding to
editoradmingrants 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/bindverbs). - 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
defaultServiceAccount is used by all pods withoutserviceAccountName. Grant permissions todefaultand 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