Skip to content
LF Cert Trainer

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

1/10Cluster Roles
0:00 / 3:26

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.

What a ClusterRole reachessubjectroleRefrulesrulesrulesUser janethe subjectClusterRoleBindingno namespaceClusterRoleno namespaceNodes, PVscluster-scoped/healthz, /metricsnon-resource URLsPodsin all namespaces
What a ClusterRole reaches. A ClusterRole bound with a ClusterRoleBinding reaches three things a Role never can: cluster-scoped resources, non-resource URLs, and namespaced resources in every namespace at once.

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, /version or /metrics.
  • Namespaced resources in all namespaces at once: what kubectl get pods --all-namespaces needs.

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:

FieldMeaningExample
apiGroupsThe API group of the resources[""], ["apps"], ["storage.k8s.io"]
resourcesPlural resource names, optionally with a subresource["nodes"], ["pods", "pods/log"]
verbsThe allowed actions["get", "list", "watch", "create", "update", "patch", "delete"]
resourceNamesOptional: only these named objects["node01"]
nonResourceURLsPaths 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 kindapiGroupNamespace neededkubectl flag
Userrbac.authorization.k8s.ioNo--user=jane
Grouprbac.authorization.k8s.ioNo--group=ops
ServiceAccountnone (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.

The binding decides where the rules applyroleRefgrantsroleRefgrantsroleRefgrantsRolein namespace devRoleBindingin namespace devPods in devone namespaceClusterRolewritten onceRoleBindingin namespace devPods in devstill one namespaceClusterRolethe same roleClusterRoleBindingno namespacePods everywhereall namespaces
The binding decides where the rules apply. The role lists what may be done. The binding decides for whom and where. A RoleBinding always limits the rules to its own namespace, even when it points at a ClusterRole.

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 kindBinding kindResult
RoleRoleBindingThe rules apply in that one namespace
ClusterRoleRoleBindingThe rules apply only in the RoleBinding's namespace
ClusterRoleClusterRoleBindingThe rules apply in every namespace and to cluster-scoped resources
RoleClusterRoleBindingNot 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:

ClusterRoleWhat it allowsBind it with
cluster-adminEvery verb on every resource and every non-resource URLA ClusterRoleBinding for full control of the cluster. In a RoleBinding it gives full control of one namespace
adminRead and write most namespaced objects, plus Roles and RoleBindings. No write access to ResourceQuotas or the namespace itselfA RoleBinding
editRead and write most namespaced objects, including Secrets. Cannot see or change Roles and RoleBindingsA RoleBinding
viewRead most namespaced objects. Cannot read Secrets, Roles or RoleBindingsA 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.

Aggregated ClusterRolesmatchedcopiesroleRefsubjectClusterRolelabel aggregate-to-viewControllerwatches the labelsClusterRole viewrules filled inUser janecan read CronTabsRoleBindingin namespace dev
Aggregated ClusterRoles. A controller copies the rules of every ClusterRole that carries the matching label into the aggregated role. This is how installing a custom resource can extend the built-in view, edit and admin roles.

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 escalate verb on roles or clusterroles.
  • Creating a binding. You may only bind a role whose permissions you already hold, unless you have the bind verb 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=nodes succeeds, 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 its namespace field.
  • Putting -n on 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-admin to 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"] with resources: ["nodes"] matches nothing and gives no error. The Forbidden message names the group the API server expected.
  • Editing the rules of view, edit or admin directly. The aggregation controller overwrites them. Add a ClusterRole with the matching aggregate-to-... label.

Recap

  • A ClusterRole is a Role without a namespace. Its rules use the same apiGroups, resources and verbs, plus nonResourceURLs.
  • 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.
  • roleRef is fixed after creation, and RBAC has no deny rules: permissions only add up.
  • cluster-admin, admin, edit and view exist in every cluster; the last three grow through aggregation labels.
  • Exam routine: kubectl create clusterrole, kubectl create clusterrolebinding (or rolebinding --clusterrole), then kubectl 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.