Lesson 82 · Section 7: Security
Lesson 82: Cluster Roles: permissions for the whole cluster
What a ClusterRole can grant that a Role cannot, how ClusterRoleBindings and RoleBindings decide where its rules apply, the built-in roles and aggregation, and the exam routine for granting and checking cluster-wide access. · 20 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.
What a ClusterRole is
In the previous lesson you gave a user access with a Role and a RoleBinding. Both live in a namespace, and that is their limit: a Role can only talk about things inside its own namespace.
Many things in a cluster have no namespace. Nodes, PersistentVolumes, StorageClasses and namespaces themselves
belong to the cluster. No Role in any namespace can grant kubectl get nodes.
A ClusterRole is the same list of rules as a Role, stored at cluster level instead of in a namespace. A ClusterRoleBinding gives those rules to a user, a group or a ServiceAccount for the whole cluster.
Parts:
- User jane (the subject)
- ClusterRoleBinding (no namespace)
- ClusterRole (no namespace)
- Nodes, PVs (cluster-scoped)
- /healthz, /metrics (non-resource URLs)
- Pods (in all namespaces)
Connections:
- User jane to ClusterRoleBinding: subject
- ClusterRoleBinding to ClusterRole: roleRef
- ClusterRole to Nodes, PVs: rules
- ClusterRole to /healthz, /metrics: rules
- ClusterRole to Pods: rules
A ClusterRole is the only way to grant three things:
- Cluster-scoped resources: nodes, PersistentVolumes, namespaces, StorageClasses, CertificateSigningRequests, CustomResourceDefinitions, and ClusterRoles and ClusterRoleBindings themselves.
- Non-resource URLs: paths of the API server that are not objects, such as
/healthz,/versionor/metrics. - Namespaced resources in all namespaces at once: what
kubectl get pods --all-namespacesneeds.
It also has a fourth use that is easy to miss: a ClusterRole can serve as a reusable template that you bind in single namespaces. More on that below.
How it works
Namespaced or cluster-scoped: ask the cluster
Whether a resource is namespaced is a fixed property of the resource type. You do not have to memorise the list:
kubectl api-resources --namespaced=false # cluster-scoped: needs a ClusterRole
kubectl api-resources --namespaced=true # namespaced: a Role is enough for one namespace
NAME SHORTNAMES APIVERSION NAMESPACED KIND
namespaces ns v1 false Namespace
nodes no v1 false Node
persistentvolumes pv v1 false PersistentVolume
certificatesigningrequests csr certificates.k8s.io/v1 false CertificateSigningRequest
clusterrolebindings rbac.authorization.k8s.io/v1 false ClusterRoleBinding
clusterroles rbac.authorization.k8s.io/v1 false ClusterRole
storageclasses sc storage.k8s.io/v1 false StorageClass
The APIVERSION column also tells you the API group to write in a rule: everything before the slash, or the empty
string "" when there is no slash (the core group).
The ClusterRole object
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
name: node-reader # no namespace: the object is cluster-scoped
rules:
- apiGroups: [""] # core group
resources: ["nodes"]
verbs: ["get", "list", "watch"]
Compared with a Role, only two things change: kind is ClusterRole, and metadata has no namespace. If you
write a namespace there, it is ignored. The rules follow the same grammar as in a Role, with one extra field that
only makes sense here:
| Field | Meaning | Example |
|---|---|---|
apiGroups | The API group of the resources | [""], ["apps"], ["storage.k8s.io"] |
resources | Plural resource names, optionally with a subresource | ["nodes"], ["pods", "pods/log"] |
verbs | The allowed actions | ["get", "list", "watch", "create", "update", "patch", "delete"] |
resourceNames | Optional: only these named objects | ["node01"] |
nonResourceURLs | Paths instead of resources. Cannot be mixed with resources in one rule | ["/healthz", "/metrics"] |
RBAC rules are additive. There is no "deny" rule. A subject's permissions are the union of every role bound to it, so you take access away by deleting a binding, never by adding a rule.
The ClusterRoleBinding object
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
name: node-reader-jane # no namespace
subjects:
- kind: User
name: jane # case sensitive
apiGroup: rbac.authorization.k8s.io
roleRef:
kind: ClusterRole # a ClusterRoleBinding can only point at a ClusterRole
name: node-reader
apiGroup: rbac.authorization.k8s.io
A binding has two halves. subjects is a list of who receives the permissions, and roleRef names the one role
that is given to them. Three kinds of subject exist:
| Subject kind | apiGroup | Namespace needed | kubectl flag |
|---|---|---|---|
User | rbac.authorization.k8s.io | No | --user=jane |
Group | rbac.authorization.k8s.io | No | --group=ops |
ServiceAccount | none (core) | Yes | --serviceaccount=monitoring:prometheus |
A ServiceAccount is itself a namespaced object, so even in a ClusterRoleBinding its subject entry carries the namespace it lives in.
The binding decides where the rules apply
Roles and bindings can be combined in three ways, and one combination is not allowed.
Parts:
- Role (in namespace dev)
- RoleBinding (in namespace dev)
- Pods in dev (one namespace)
- ClusterRole (written once)
- RoleBinding (in namespace dev)
- Pods in dev (still one namespace)
- ClusterRole (the same role)
- ClusterRoleBinding (no namespace)
- Pods everywhere (all namespaces)
Connections:
- RoleBinding to Role: roleRef
- RoleBinding to Pods in dev: grants
- RoleBinding to ClusterRole: roleRef
- RoleBinding to Pods in dev: grants
- ClusterRoleBinding to ClusterRole: roleRef
- ClusterRoleBinding to Pods everywhere: grants
| Role kind | Binding kind | Result |
|---|---|---|
| Role | RoleBinding | The rules apply in that one namespace |
| ClusterRole | RoleBinding | The rules apply only in the RoleBinding's namespace |
| ClusterRole | ClusterRoleBinding | The rules apply in every namespace and to cluster-scoped resources |
| Role | ClusterRoleBinding | Not possible. The API server rejects it |
The second row is the template pattern. You write pod-reader once as a ClusterRole, then create a RoleBinding to
it in dev, another in test, and so on. Each team gets the same rules in its own namespace and nowhere else, and
you maintain one role instead of one per namespace.
There is a limit to that pattern: a RoleBinding can only hand out namespaced permissions. If the ClusterRole contains rules for nodes or for non-resource URLs, a RoleBinding to it simply does not grant those rules. They take effect only through a ClusterRoleBinding.
roleRef cannot be changed
After a binding is created, its roleRef is fixed. You may add and remove subjects, but an attempt to point the
binding at another role is refused:
The ClusterRoleBinding "node-reader-jane" is invalid: roleRef: Invalid value: ...: cannot change roleRef
Delete the binding and create it again. The rule exists so that someone who is only allowed to manage the subjects of a binding cannot quietly swap in a more powerful role.
What the API server says when access is missing
The error message tells you exactly which rule is missing. Read it as a recipe for the ClusterRole:
Error from server (Forbidden): nodes is forbidden: User "jane" cannot list resource "nodes"
in API group "" at the cluster scope
Verb list, resource nodes, API group "", and "at the cluster scope" means a namespaced binding will not help.
For a namespaced request the message ends with in the namespace "dev" instead.
The roles every cluster already has
Kubernetes ships with a set of ClusterRoles. Four of them are meant for people:
| ClusterRole | What it allows | Bind it with |
|---|---|---|
cluster-admin | Every verb on every resource and every non-resource URL | A ClusterRoleBinding for full control of the cluster. In a RoleBinding it gives full control of one namespace |
admin | Read and write most namespaced objects, plus Roles and RoleBindings. No write access to ResourceQuotas or the namespace itself | A RoleBinding |
edit | Read and write most namespaced objects, including Secrets. Cannot see or change Roles and RoleBindings | A RoleBinding |
view | Read most namespaced objects. Cannot read Secrets, Roles or RoleBindings | A RoleBinding |
view leaves out Secrets on purpose: a Secret can hold a ServiceAccount token, and reading it would let the
viewer act as that ServiceAccount.
The default ClusterRoleBinding named cluster-admin gives the role of the same name to the group
system:masters. On a kubeadm cluster, the everyday administrator file /etc/kubernetes/admin.conf belongs to the
group kubeadm:cluster-admins instead, which a second ClusterRoleBinding also connects to cluster-admin. That
binding is why the file is allowed to do everything, and it is an ordinary binding that you can inspect:
kubectl get clusterrolebindings cluster-admin kubeadm:cluster-admins -o wide
The roles whose names start with system: belong to the cluster's own components, for example
system:kube-scheduler, system:node and system:coredns. Look at them to learn, but do not edit them: the API
server restores the defaults at every start, and a broken system role can stop a component from working.
kubectl get clusterroles | grep -v '^system:' # the short, human list
kubectl describe clusterrole view | head -n 20
Aggregated ClusterRoles
admin, edit and view are not written by hand. Each one is an aggregated ClusterRole: it has an
aggregationRule with a label selector, and a controller in kube-controller-manager fills its rules with the
rules of every ClusterRole that carries a matching label.
Parts:
- ClusterRole (label aggregate-to-view)
- Controller (watches the labels)
- ClusterRole view (rules filled in)
- User jane (can read CronTabs)
- RoleBinding (in namespace dev)
Connections:
- ClusterRole to Controller: matched
- Controller to ClusterRole view: copies
- RoleBinding to ClusterRole view: roleRef
- RoleBinding to User jane: subject
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
name: crontab-viewer
labels:
rbac.authorization.k8s.io/aggregate-to-view: "true"
rules:
- apiGroups: ["stable.example.com"]
resources: ["crontabs"]
verbs: ["get", "list", "watch"]
Create this object and, a moment later, everyone bound to view can read CronTabs. This is how an operator that
installs a custom resource makes it visible to existing users. The labels for the other two roles are
rbac.authorization.k8s.io/aggregate-to-edit and rbac.authorization.k8s.io/aggregate-to-admin. edit also
aggregates into admin, and view into edit.
Two consequences are worth remembering. Rules that you write directly into an aggregated role are overwritten by the controller, so add a labelled ClusterRole instead. And you can build your own aggregated role:
kubectl create clusterrole monitoring --aggregation-rule="rbac.example.com/aggregate-to-monitoring=true"
Under the hood · Why you cannot grant yourself more than you have
RBAC protects itself against privilege escalation in two places.
- Creating or updating a role. You may only write rules that you already hold yourself at the same scope, unless
you have the
escalateverb onrolesorclusterroles. - Creating a binding. You may only bind a role whose permissions you already hold, unless you have the
bindverb on that role.
So a user who is allowed to create ClusterRoleBindings, and nothing else, still cannot bind cluster-admin to
their own name. The request fails with user "jane" ... is attempting to grant RBAC permissions not currently held.
The built-in admin role uses this deliberately: it may create Roles and RoleBindings in its namespace, but only up
to the level of access that an admin of the namespace already has.
Members of system:masters are a special case. The API server lets that group through before RBAC is consulted,
so their access cannot be removed by deleting a binding. On a kubeadm cluster only the break-glass file
/etc/kubernetes/super-admin.conf is in that group. Keep it for emergencies and give people their own, narrower
bindings.
Using it
Example · Let a user read nodes and PersistentVolumes
The task: "User jane must be able to list nodes and PersistentVolumes." Both are cluster-scoped, so you need a
ClusterRole and a ClusterRoleBinding.
kubectl create clusterrole infra-reader \
--verb=get,list,watch --resource=nodes,persistentvolumes
kubectl create clusterrolebinding infra-reader-jane \
--clusterrole=infra-reader --user=jane
Check the result as that user, without logging in as her:
kubectl auth can-i list nodes --as jane # yes
kubectl auth can-i list persistentvolumes --as jane # yes
kubectl auth can-i delete nodes --as jane # no
kubectl get nodes --as jane # the real request
Add --dry-run=client -o yaml to either create command to see the manifest it would send.
Example · One ClusterRole, bound in a single namespace
The task: "ServiceAccount deployer in namespace ci must be able to manage Deployments in namespace staging
only. Use the ClusterRole deployment-manager."
kubectl create clusterrole deployment-manager \
--verb=get,list,watch,create,update,patch,delete --resource=deployments.apps
kubectl create rolebinding deployer-staging -n staging \
--clusterrole=deployment-manager --serviceaccount=ci:deployer
The binding is a RoleBinding, and it lives in staging: that namespace is where the permissions apply. The
ServiceAccount stays in ci. Verify both sides of the boundary:
kubectl auth can-i create deployments -n staging --as system:serviceaccount:ci:deployer # yes
kubectl auth can-i create deployments -n default --as system:serviceaccount:ci:deployer # no
With --as, a ServiceAccount is written as system:serviceaccount:<namespace>:<name>.
Example · Read-only access to everything, for a group
The task: "Members of the group auditors must be able to read objects in all namespaces." The built-in view
role already contains the right rules, so only a binding is needed:
kubectl create clusterrolebinding auditors-view --clusterrole=view --group=auditors
kubectl auth can-i list pods -A --as someone --as-group auditors # yes
kubectl auth can-i get secrets -n default --as someone --as-group auditors # no: view excludes Secrets
--as-group can only be used together with --as; the user name can be anything.
Example · Allow a monitoring agent to call /metrics
Paths such as /metrics are not resources, so the rule uses nonResourceURLs. Only a ClusterRoleBinding can grant
it:
kubectl create clusterrole metrics-reader --verb=get --non-resource-url=/metrics
kubectl create clusterrolebinding metrics-reader-prom \
--clusterrole=metrics-reader --serviceaccount=monitoring:prometheus
kubectl auth can-i get /metrics --as system:serviceaccount:monitoring:prometheus # yes
rules:
- nonResourceURLs: ["/metrics"]
verbs: ["get"]
Example · Find out why someone has access
There is no command that lists "everything bound to jane", but the wide output of the bindings gets you there:
kubectl get clusterrolebindings -o wide | grep -w jane
kubectl get rolebindings -A -o wide | grep -w jane
NAME ROLE AGE USERS GROUPS SERVICEACCOUNTS
infra-reader-jane ClusterRole/infra-reader 4m jane
Then read the role, and list what the user ends up with:
kubectl describe clusterrole infra-reader
kubectl auth can-i --list --as jane
Tricks
Common mistakes
- Using a Role for a cluster-scoped resource.
kubectl create role ... --resource=nodessucceeds, but the Role never grants anything, because nodes are not in any namespace. - Using a ClusterRoleBinding when the task names one namespace. The user receives the permission everywhere. Bind the ClusterRole with a RoleBinding in that namespace instead.
- Forgetting the namespace of a ServiceAccount. It is
--serviceaccount=<namespace>:<name>. With only the name, kubectl reports an error; in YAML the subject needs itsnamespacefield. - Putting
-non the wrong object. A ClusterRole and a ClusterRoleBinding have no namespace. A RoleBinding does, and its namespace is where the permissions apply, not where the subject lives. - Expecting a RoleBinding to grant node access. Cluster-scoped rules and non-resource URLs in a ClusterRole only take effect through a ClusterRoleBinding.
- Binding
cluster-adminto make a task pass. It works, and it is wrong. Grant the verbs and resources that were asked for, nothing more. - Writing the wrong API group.
apiGroups: ["apps"]withresources: ["nodes"]matches nothing and gives no error. The Forbidden message names the group the API server expected. - Editing the rules of
view,editoradmindirectly. The aggregation controller overwrites them. Add a ClusterRole with the matchingaggregate-to-...label.
Recap
- A ClusterRole is a Role without a namespace. Its rules use the same
apiGroups,resourcesandverbs, plusnonResourceURLs. - Only a ClusterRole can grant access to cluster-scoped resources (nodes, PersistentVolumes, namespaces, StorageClasses), to non-resource URLs, and to namespaced resources across all namespaces.
- The binding sets the reach: ClusterRoleBinding means everywhere, RoleBinding to a ClusterRole means that one namespace. A ClusterRoleBinding cannot point at a Role.
roleRefis fixed after creation, and RBAC has no deny rules: permissions only add up.cluster-admin,admin,editandviewexist in every cluster; the last three grow through aggregation labels.- Exam routine:
kubectl create clusterrole,kubectl create clusterrolebinding(orrolebinding --clusterrole), thenkubectl auth can-i ... --as.
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.
Grant read access to cluster-scoped resources for a group, and use one built-in ClusterRole inside a single namespace only.
Build · Level 2 · standard · target 15 min
Section capstone. Prepare a namespace for an audit: a short-lived login for the auditor, read-only access for her group, an identity of its own for one app, a hardened container, and network policies that close the namespace.
Build · Level 3 · challenge · target 40 min
Discussion
Learners ask and answer questions here. Sign in to read and join the discussion.