How to give all service accounts in namespace the same cluster role?

12/14/2020

I have a group of service accounts in namespace prometheus and I have a cluster role for reading all pods in my cluster. How can I build ClusterRoleBinding to do it?

-- faoxis
kubernetes

1 Answer

12/15/2020

If you go to K8s docs about Using RBAC Authorization

And scroll down to examples, you can see this one:

For all service accounts in the "qa" namespace:

subjects:
- kind: Group
  name: system:serviceaccounts:qa
  apiGroup: rbac.authorization.k8s.io

You can now take it and apply to your usecase:

apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
  creationTimestamp: null
  name: <some-fancy-name>
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: ClusterRole
  name: <clusterrolename>
subjects:
- kind: Group
  name: system:serviceaccounts:prometheus
  apiGroup: rbac.authorization.k8s.io

There is also one different example worth to notice:

  1. Grant a role to all service accounts in a namespace

If you want all applications in a namespace to have a role, no matter what service account they use, you can grant a role to the service account group for that namespace.

For example, grant read-only permission within "my-namespace" to all service accounts in that namespace:

kubectl create rolebinding serviceaccounts-view \
  --clusterrole=view \
  --group=system:serviceaccounts:my-namespace \
  --namespace=my-namespace
-- Matt
Source: StackOverflow