How do I restrict ClusterRole PolicyRule to a Namespace?

3/5/2020

I have a service account with a Policy Rule that works perfectly in mynamespace. But it also works perfectly in other namespaces, which I want to prevent.

---
kind: ClusterRole
apiVersion: rbac.authorization.k8s.io/v1
metadata:
  name: myapp
  namespace: mynamespace
rules:
- apiGroups: ["extensions"]
  resources: ["deployments"]
  verbs: ["get", "patch"]

---
apiVersion: v1
kind: ServiceAccount
metadata:
  name: myapp
  namespace: mynamespace

---
kind: ClusterRoleBinding
apiVersion: rbac.authorization.k8s.io/v1
metadata:
  name: myapp
  namespace: mynamespace
subjects:
- kind: ServiceAccount
  name: myapp
  namespace: mynamespace
roleRef:
  kind: ClusterRole
  name: myapp
  apiGroup: rbac.authorization.k8s.io
-- grahamoptibrium
kubernetes

1 Answer

3/5/2020

You use a RoleBinding instead of a ClusterRoleBinding.

-- coderanger
Source: StackOverflow