'How to refer the current namespace for the service account in rolebinding yaml

Having a rolebinding with a serviceaccount on the same namespace as subject. Is it possible to specify the current namespace through reference. Something simillar to setting env from fieldreference in containers and using them without hardcoding it multiple places.

    env:
    - name: NS
      valueFrom:
        fieldRef:
          fieldPath: metadata.namespace

The rolebinding yaml is given below, Is it possible to avoid the mynamespace in the subject with some kind of reference to the current namespace .metadata.namespace

apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
  name: pod-reader
  namespace: mynamespace
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: Role
  name: reader-service
subjects:
- kind: ServiceAccount
  namespace: mynamespace
  name: default


Solution 1:[1]

I have added environment variables to the First role binding config file and used this environment variable in the Second role binding config file and the role binding was successful.

First role binding config file:

apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
 name: pod-reader
 namespace: mynamespace
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: Role
  name: reader-service
subjects:
- kind: ServiceAccount
  namespace: mynamespace
  name: default
spec:
  containers:
    - name: test-container
      image: k8s.gcr.io/busybox
      command: [ "sh", "-c"]
      env:
        - name: MY_POD_NAMESPACE
          valueFrom:
            fieldRef:
              fieldPath: metadata.namespace

Second role binding config file:

apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
  name: pod-reader1
  namespace: default
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: Role
  name: reader-service
subjects:
- kind: ServiceAccount
  namespace: MY_POD_NAMESPACES
  name: default

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Goli Nikitha