Kubernetes RBAC: use one Role in multiple namespaces
You would like to create one RBAC Role, which defines certain permissions over objects, then grant these permissions to a ServiceAccount or User in multiple namespaces?
TL;DR
Create a ClusterRole and bind it to multiple namespaces using a RoleBinding.
Just because it’s called a ClusterRole doesn’t mean it grants cluster-wide permissions. The scope a ClusterRole is applied to depends on its binding. The binding can be a ClusterRoleBinding (cluster wide) or RoleBinding (namespace wide).
Example Scenario
Make sure to use a cluster with RBAC enabled, like GKE. Docker For Desktop doesn’t as of today as far as I know
We would like to create a ServiceAccount which is allowed to manage cronjobs in two namespaces, namespace1 and namespace2.
ServiceAccount
First let’s create a ServiceAccount to grant permissions to:
apiVersion: v1
kind: ServiceAccount
metadata:
name: sa
namespace: default
ClusterRole
Now we create a ClusterRole. This is a “Role” which is available in the whole cluster, but doesn’t itself grant permissions for the whole cluster:
kind: ClusterRole
apiVersion: rbac.authorization.k8s.io/v1
metadata:
name: job-master
rules:
- apiGroups:
- batch
resources:
- cronjobs
verbs:
- create
- delete
- deletecollection
- get
- list
- patch
- update
- watch
The job-master ClusterRole will allow everything regarding cronjobs.
RoleBinding
We will now create two RoleBinding objects (not ClusterRoleBinding) which will use the ClusterRole job-master from above to allow the ServiceAccount sa to perform various actions (verbs) on cronjobs in two namespaces:
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
name: job-master-1
namespace: namespace1
roleRef:
apiGroup: rbac.authorization.k8s.io
kind: ClusterRole
name: job-master
subjects:
- kind: ServiceAccount
name: sa
namespace: default
---
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
name: job-master-2
namespace: namespace2
roleRef:
apiGroup: rbac.authorization.k8s.io
kind: ClusterRole
name: job-master
subjects:
- kind: ServiceAccount
name: sa
namespace: default
Test it
kubectl auth can-i get cronjobs -n namespace1 --as system:serviceaccount:default:sa #yeskubectl auth can-i delete cronjobs -n namespace2 --as system:serviceaccount:default:sa #yeskubectl auth can-i get cronjobs -n namespace3 --as system:serviceaccount:default:sa #nokubectl auth can-i get pod -n namespace2 --as system:serviceaccount:default:sa #no
Here you can see some examples of more role definitions: