Lesson 81 · Section 7: Security
Lesson 81: Role-based access control: Roles and RoleBindings
How RBAC decides what an authenticated user may do in a namespace: the rules inside a Role, the RoleBinding that hands it to users, groups and service accounts, how the API server evaluates a request, and how to create and test permissions quickly with kubectl. · 18 min read · 3 min video
Official competency this lesson covers
Narrated by the local narrator voice. Keys: Space plays and pauses, J and L step, C captions, F full screen.
Why RBAC exists
A cluster is shared. A developer needs to read logs and restart Pods in one namespace. A CI pipeline needs to update Deployments. An on-call engineer needs to look at everything and change little. If all of them used the administrator's kubeconfig, any typo or stolen laptop could delete the whole cluster.
The Authentication lesson showed how the API server learns who is making a request. The Authorization lesson
showed that a chain of authorizers then decides whether the request may proceed, and that almost every cluster
runs with --authorization-mode=Node,RBAC. This lesson is about that second word: role-based access control,
the authorizer you will configure yourself.
What it is
RBAC is configured with ordinary API objects in the group rbac.authorization.k8s.io/v1. There are four kinds:
| Kind | Scope | Purpose |
|---|---|---|
| Role | One namespace | A list of permissions on namespaced resources |
| RoleBinding | One namespace | Grants a Role (or a ClusterRole) to subjects, inside that namespace |
| ClusterRole | Whole cluster | Permissions on cluster-scoped resources, or a reusable set for any namespace |
| ClusterRoleBinding | Whole cluster | Grants a ClusterRole everywhere |
This lesson covers the first two. The cluster-wide pair works the same way and is the subject of the next lesson.
Parts:
- User jane (from her certificate)
- Group dev-team (everyone in it)
- ServiceAccount ci (a program's identity)
- RoleBinding (subjects + roleRef), in Namespace dev
- Role developer (rules: what is allowed), in Namespace dev
Connections:
- User jane to RoleBinding: subject
- Group dev-team to RoleBinding: subject
- ServiceAccount ci to RoleBinding: subject
- RoleBinding to Role developer: roleRef
The design separates three things that change at different speeds:
- Subjects (who): users, groups and service accounts. People join and leave.
- Roles (what): a job description such as "can manage Pods and read Deployments". These rarely change.
- Bindings (the link): which subject holds which role, in which namespace. This is what you edit day to day.
Because a Role names nobody, one Role can be bound to many subjects, and one subject can hold many Roles. Their permissions simply add up.
The rules inside a Role
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
name: developer
namespace: dev # the only namespace these rules apply to
rules:
- apiGroups: [""] # "" is the core group: pods, services, configmaps, secrets ...
resources: ["pods"]
verbs: ["get", "list", "watch", "create", "delete"]
- apiGroups: ["apps"]
resources: ["deployments"]
verbs: ["get", "list", "watch"]
Each rule is a small sentence: on these resources, in these API groups, these verbs are allowed.
| Field | What goes in it | Watch out for |
|---|---|---|
apiGroups | The group of the resource, without the version: "" for core, apps, batch, networking.k8s.io | Deployments under "" match nothing. The group is the part of apiVersion before the slash |
resources | Plural, lowercase resource names: pods, deployments, configmaps | Not the kind (Pod) and not a short name (deploy) |
verbs | get, list, watch, create, update, patch, delete, deletecollection | kubectl edit and kubectl apply need get plus patch or update |
resourceNames | Optional. Limits the rule to objects with these names | Cannot limit create or deletecollection, and does not help list |
"*" is a wildcard in any of the three main fields. A rule with "*" everywhere is full control of the namespace,
including resource types that are installed later, so use it sparingly.
Subresources are written with a slash. Reading logs, opening a shell and scaling are separate permissions from reading the Pod or Deployment itself:
rules:
- apiGroups: [""]
resources: ["pods", "pods/log"] # kubectl get pods, kubectl logs
verbs: ["get", "list"]
- apiGroups: [""]
resources: ["pods/exec"] # kubectl exec
verbs: ["create"]
The RoleBinding
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
name: developer-jane
namespace: dev # where the permissions are granted
subjects:
- kind: User
name: jane # case sensitive
apiGroup: rbac.authorization.k8s.io
roleRef:
kind: Role
name: developer
apiGroup: rbac.authorization.k8s.io
subjects is a list, so one binding can serve a whole team. There are three kinds of subject:
| Kind | Where the name comes from | Written as |
|---|---|---|
User | The authenticator, for example the certificate's Common Name (CN=jane) | kind: User, name: jane, apiGroup: rbac.authorization.k8s.io |
Group | The authenticator, for example the certificate's Organization (O=dev-team) | kind: Group, name: dev-team, apiGroup: rbac.authorization.k8s.io |
ServiceAccount | A real object in a namespace | kind: ServiceAccount, name: ci, namespace: dev (no apiGroup) |
Users and groups are not objects in the cluster. Kubernetes never checks that jane exists: the binding is just a
string that will match if someone authenticates with that name. A typo in the name is therefore silent.
roleRef points at exactly one role and is immutable. Try to change it and the API server answers:
The RoleBinding "developer-jane" is invalid: roleRef: Invalid value: ...: cannot change roleRef
Delete the binding and create it again. This is deliberate: whoever may edit the subject list of a binding should not be able to quietly swap the role behind it for a more powerful one.
How it works
One request, step by step
Parts:
- Request (list pods in dev)
- Authentication (user jane, her groups)
- RBAC authorizer (inside kube-apiserver)
- Bindings in dev (any that name jane?)
- Rules of the role (group, resource, verb)
- Allowed (request continues)
- 403 Forbidden (nothing matched)
Connections:
- Request to Authentication: HTTPS
- Authentication to RBAC authorizer: jane
- RBAC authorizer to Bindings in dev: looks up
- Bindings in dev to Rules of the role: roleRef
- Rules of the role to Allowed: match
- Rules of the role to 403 Forbidden: no rule matches
Every API request carries the same facts: the user and their groups (from authentication), a verb, an API
group, a resource (possibly with a subresource and a name) and a namespace. kubectl get pods -n dev by
jane becomes "jane, list, group "", resource pods, namespace dev".
The RBAC authorizer then does something simple:
- Collect every RoleBinding in the namespace
dev, and every ClusterRoleBinding, whose subjects includejaneor one of her groups. - For each, read the rules of the role it references.
- If any rule matches the verb, group, resource and (if set) name, the request is allowed.
- If none does, RBAC has no opinion, no other authorizer says yes, and the API server returns
403 Forbidden.
There is no ordering between rules and no "most specific wins", because there is nothing to conflict: rules can only allow. That is also why you cannot write "everything except Secrets" as one exception. You list what is allowed and leave Secrets out.
The refusal tells you exactly which facts did not match:
Error from server (Forbidden): deployments.apps is forbidden: User "jane" cannot delete resource "deployments"
in API group "apps" in the namespace "dev"
Read it as a ready-made rule: verb delete, resource deployments, group apps, namespace dev.
Changes take effect immediately. The API server watches RBAC objects, so there is nothing to restart and the user does not need to log in again.
Verbs are HTTP methods with better names
| kubectl command | Verb checked | Resource checked |
|---|---|---|
kubectl get pod web | get | pods |
kubectl get pods | list | pods |
kubectl get pods -w | list, then watch | pods |
kubectl create -f, kubectl run | create | pods |
kubectl apply -f on an existing object | get, then patch | the resource |
kubectl edit | get, then patch | the resource |
kubectl delete pod web | delete | pods |
kubectl logs web | get | pods/log |
kubectl exec web -- sh | create | pods/exec |
kubectl scale deploy web | patch (or update) | deployments/scale |
Two consequences surprise people:
getandlistare different verbs. A user with onlygetcan read a Pod whose name they know, butkubectl get podsis refused.listandwatchreturn complete objects. Anyone who maylistSecrets can read every Secret's contents with-o yaml, so "list only" is not a safe way to hide values.
Where a Role stops
Parts:
- User jane (kubectl get ...)
- RoleBinding in dev (jane → developer)
- No binding in prod (nothing names jane)
- Not namespaced (a Role cannot reach)
- Pods in dev (allowed)
- Pods in prod (Forbidden)
- Nodes (Forbidden)
Connections:
- User jane to RoleBinding in dev: pods -n dev
- User jane to No binding in prod: -n prod
- User jane to Not namespaced: get nodes
- RoleBinding in dev to Pods in dev: yes
- No binding in prod to Pods in prod: no
- Not namespaced to Nodes: no
A Role and a RoleBinding both carry a namespace, and the permissions exist only there. Three things follow:
- The same subject can be an editor in
devand have nothing inprod. You bind per namespace. - A Role cannot grant cluster-scoped resources such as Nodes, PersistentVolumes, Namespaces or StorageClasses,
because they are in no namespace.
kubectl api-resources --namespaced=falselists them. They need a ClusterRole and a ClusterRoleBinding. - The subject does not have to live in the binding's namespace. A RoleBinding in
devcan name a ServiceAccount fromci-system: what counts is where the binding is, not where the subject is.
You cannot grant what you do not have
RBAC protects itself against privilege escalation. A user who is allowed to create Roles and RoleBindings still cannot use that to become more powerful:
- You can create or update a Role only if you already hold every permission it contains (in the same scope),
or you have the special verb
escalateonroles. - You can create a RoleBinding only if you already hold every permission of the role it references, or you
have the special verb
bindon that role.
Error from server (Forbidden): roles.rbac.authorization.k8s.io "secret-reader" is forbidden: user "jane"
(groups=["dev-team" "system:authenticated"]) is attempting to grant RBAC permissions not currently held:
{APIGroups:[""], Resources:["secrets"], Verbs:["get" "list"]}
In the exam you work as a cluster administrator, so you will not hit this. On a real cluster it is the reason a namespace admin cannot hand out access to Secrets they cannot read themselves.
Under the hood · Why the administrator can do everything
Your own access is RBAC too. kubeadm writes /etc/kubernetes/admin.conf with a certificate for the user
kubernetes-admin in the group kubeadm:cluster-admins, and creates a ClusterRoleBinding from that group to the
built-in ClusterRole cluster-admin, which has "*" on everything. Look at it:
kubectl auth whoami
kubectl get clusterrolebinding kubeadm:cluster-admins -o wide
The group system:masters is different: the API server lets it through before RBAC is even asked, so its access
cannot be removed by deleting a binding. kubeadm keeps that power in a separate break-glass file,
super-admin.conf. Never put real people in system:masters.
Service accounts, covered two lessons from now, authenticate as the user
system:serviceaccount:<namespace>:<name> and belong to the groups system:serviceaccounts and
system:serviceaccounts:<namespace>. A new service account has no permissions beyond API discovery, which every
authenticated identity gets.
Using it
Example · Give a user read and write access to Pods in one namespace
The task: user jane must be able to list, create and delete Pods in the namespace dev, and nothing else.
kubectl -n dev create role pod-manager --verb=get,list,watch,create,delete --resource=pods
kubectl -n dev create rolebinding pod-manager-jane --role=pod-manager --user=jane
Check what you built, then test it as jane:
kubectl -n dev describe role pod-manager
kubectl -n dev get rolebinding pod-manager-jane -o wide
PolicyRule:
Resources Non-Resource URLs Resource Names Verbs
--------- ----------------- -------------- -----
pods [] [] [get list watch create delete]
NAME ROLE AGE USERS GROUPS SERVICEACCOUNTS
pod-manager-jane Role/pod-manager 5s jane
kubectl auth can-i create pods -n dev --as jane # yes
kubectl auth can-i create pods -n prod --as jane # no: the Role stops at dev
kubectl auth can-i delete deployments -n dev --as jane # no: not in the rules
Example · One Role with resources from two API groups
The imperative command writes a single rule, but it can hold several resources, and it looks up each resource's API group for you. Write the group after a dot when you want to be explicit:
kubectl -n dev create role app-reader \
--verb=get,list,watch --resource=pods,services,deployments.apps,jobs.batch \
--dry-run=client -o yaml
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
name: app-reader
namespace: dev
rules:
- apiGroups: [""]
resources: ["pods", "services"]
verbs: ["get", "list", "watch"]
- apiGroups: ["apps"]
resources: ["deployments"]
verbs: ["get", "list", "watch"]
- apiGroups: ["batch"]
resources: ["jobs"]
verbs: ["get", "list", "watch"]
That is the output, shortened. kubectl split the resources by group into separate rules. When a task needs different verbs for different resources, save this output to a file, edit the verbs per rule, and apply it.
Example · Let a service account read logs and open a shell
A debugging tool runs as the ServiceAccount debugger in dev. It must read Pods and their logs and run
kubectl exec. Subresources go after a slash:
kubectl -n dev create serviceaccount debugger
kubectl -n dev create role pod-debugger --verb=get,list --resource=pods,pods/log
kubectl -n dev create rolebinding pod-debugger --role=pod-debugger --serviceaccount=dev:debugger
The --serviceaccount flag always takes namespace:name. exec needs a different verb, so add a second rule:
kubectl -n dev edit role pod-debugger
rules:
- apiGroups: [""]
resources: ["pods", "pods/log"]
verbs: ["get", "list"]
- apiGroups: [""]
resources: ["pods/exec"]
verbs: ["create"]
Test as the service account, using its full user name:
kubectl auth can-i get pods --subresource=log -n dev --as system:serviceaccount:dev:debugger # yes
kubectl auth can-i create pods --subresource=exec -n dev --as system:serviceaccount:dev:debugger # yes
kubectl auth can-i delete pods -n dev --as system:serviceaccount:dev:debugger # no
Example · Allow changes to one named object only
The group dev-team may read every ConfigMap in dev but update only the one called app-settings:
kubectl -n dev create role cm-reader --verb=get,list,watch --resource=configmaps
kubectl -n dev create role settings-editor --verb=update,patch --resource=configmaps --resource-name=app-settings
kubectl -n dev create rolebinding cm-reader --role=cm-reader --group=dev-team
kubectl -n dev create rolebinding settings-editor --role=settings-editor --group=dev-team
Two Roles and two bindings, and the permissions add up. To test a group, impersonate any user name together with the group:
kubectl auth can-i update configmap/app-settings -n dev --as x --as-group dev-team # yes
kubectl auth can-i update configmap/other -n dev --as x --as-group dev-team # no
resourceNames cannot restrict create: when the request is authorized, the name of the new object is not yet
part of the URL. Nor does it make kubectl get configmaps work, because listing asks for all of them.
Example · Find out why a user is Forbidden
Jane reports that kubectl -n dev get deployments is refused. Work from the question to the objects:
kubectl auth can-i list deployments -n dev --as jane # no
kubectl auth can-i --list -n dev --as jane # everything jane may do in dev
kubectl -n dev get rolebindings -o wide # which bindings name jane or her groups?
kubectl -n dev describe role developer # what do the rules really say?
PolicyRule:
Resources Non-Resource URLs Resource Names Verbs
--------- ----------------- -------------- -----
deployments [] [] [get list watch]
pods [] [] [get list watch create delete]
The Resources column says deployments, not deployments.apps: the rule was written with apiGroups: [""], a
group in which no Deployments exist. Fix the group with kubectl -n dev edit role developer and ask again.
Tricks
Common mistakes
- Wrong or missing namespace. A Role and RoleBinding created without
-nland indefaultand grant nothing indev. Check both objects withkubectl -n dev get role,rolebinding. - Wrong API group.
apiGroups: [""]withresources: ["deployments"]is accepted and matches nothing. The Forbidden message andkubectl api-resourcesboth name the right group. - A Role without a binding. Creating the Role is half the task. Nobody holds it until a RoleBinding names them.
- Kind names or short names in
resources. Writepods, notPodorpo, when you write the YAML yourself. - Forgetting subresources.
getonpodsdoes not includekubectl logs(pods/log) orkubectl exec(pods/exec, verbcreate). - Giving
getand expectingkubectl get podsto work. Listing needslist. Giveget,listandwatchtogether for read access. --serviceaccount=namewithout the namespace. The flag needsnamespace:name; in YAML, a ServiceAccount subject needsnamespaceand must not have the RBACapiGroup.- Trying to grant Nodes or PersistentVolumes with a Role. They are cluster-scoped. Use a ClusterRole and a ClusterRoleBinding.
- Testing
can-iwithout--as. You tested the administrator.
Recap
- RBAC denies by default and its rules only add. There is no deny rule; leave out what should not be allowed.
- A Role lists
apiGroups,resources(with subresources such aspods/log) andverbs, in one namespace. - A RoleBinding grants one role to users, groups and service accounts in its namespace.
roleRefis immutable: delete and recreate to change it. - A Role cannot reach other namespaces or cluster-scoped resources. That is the job of ClusterRoles.
- Create with
kubectl create roleandkubectl create rolebinding; prove it withkubectl auth can-i <verb> <resource> -n <namespace> --as <user>.
Official docs
Quiz: check what you learned
5 questions on this lesson · about 3 min · instant feedback. Missed questions come back in your review queue.
Sign in to take the quiz and keep your score.
Practise: try it on a real cluster
2 hands-on labs for this lesson. You get goals, not steps: any solution that reaches them passes.
Give a service account just enough access to roll out Deployments in one namespace, and nothing more.
Build · Level 2 · standard · target 15 min
A developer's access to her own namespace is broken in more than one place. Find each fault from the Forbidden messages and repair it without handing out more than she needs.
Fix · Level 2 · standard · target 15 min
Discussion
Learners ask and answer questions here. Sign in to read and join the discussion.