kubernetesansibleyamlrbac

RBAC: roles with multiple namespaces


Trying to write my first set of RBAC roles. So trying to figure out the best way to have 2 roles for multiple namespaced components.

Admin-role (RW for 3 namespaces say default, ns1 & ns2) user-role (Read-only for 3 namespaces say default, ns1 & ns2)

Was thinking will need a service account with 2 clusterRoles for admin/user

apiVersion: rbac.authorization.k8s.io/v1
kind: ServiceAccount
metadata:
  name: sa
  namespace: default

apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
apiVersion: rbac.authorization.k8s.io/v1
metadata:
  name: admin-master
rules:
- apiGroups:
    - batch
  resources:
    - pods
  verbs:
    - create
    - delete
    - deletecollection
    - get
    - list
    - patch
    - update
    - watch

apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
apiVersion: rbac.authorization.k8s.io/v1
metadata:
  name: user-master
rules:
- apiGroups:
    - batch
  resources:
    - pods
  verbs:
    - get
    - list
    - watch

Then make use of roleBindings:

apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
  name: admin-rw
  namespace: ns1
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: ClusterRole
  name: admin-master
subjects:
  - kind: ServiceAccount
    name: sa
    namespace: default
---
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
  name: user-readonly
  namespace: ns1
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: ClusterRole
  name: user-master
subjects:
  - kind: ServiceAccount
    name: sa
    namespace: default

But not sure how the best way to bind roles admin-rw/user-readonly with namespace 2 (ns2)?


Solution

  • Roles are scoped, either bound to an specific namespace or cluster-wide. For namespace-scoped roles, you can just simply deploy the same role in multiple namespaces.

    The idea behind this is to have partitioned permissions in the cluster, although it implies more administrative effort but is a safer practice.

    Additionally, in your definition, you're trying to bind permissions to specific namespaces, however, you're using ClusterRole which is a cluster-scoped resource. You might want to change that to Role if you want namespace-scoped permissions.

    You might find this CNCF article useful on this matter.