K8s - using service accounts across namespaces

8/10/2021

I have a service account, in the default namespace, with a clusterRoleBinding to a clusterRole that can observe jobs.

I wish to use this service account in any namespace rather than have to define a new service account in each new namespace. The service account is used by an init container to check a job has completed before allowing deployment to continue.

Not sure what extra info I need to provide but will do so on request.

-- lurker
k8s-serviceaccount
kubernetes

1 Answer

8/10/2021

You can simply reference a ServiceAccount from another namespace in the RoleBinding:

For example, below is sample use to refer the service account in one namespace to another for just reading the pods.

apiVersion: rbac.authorization.k8s.io/v1beta1
kind: Role
metadata:
  name: pod-reader
  namespace: ns2
rules:
- apiGroups: [""]
  resources: ["pods"]
  verbs: ["get", "list", "watch"]
---
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
  name: pod-reader-from-ns1
  namespace: ns2
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: Role
  name: pod-reader
subjects:
- kind: ServiceAccount
  name: ns1-service-account
  namespace: ns1
-- Chandra Sekar
Source: StackOverflow