How to restrict user to create namespace in kubernetes

2/22/2021

Say i have a k8s cluster.

I would like to restrict user to create their own namespace. And only allow admin to create namespace.

I am trying to use of cluster role rules:

apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
  name: my-role
rules:
- apiGroups: ["v1"]
  resources: ["namespaces"]
  verbs: ["get", "list", "watch"]

But I found user still can create namespace. Any solution to do so?

-- user3739811
kubernetes
namespaces

1 Answer

2/22/2021

You need to create a ClusterRoleBinding to apply the ClusterRole my-role to the user. Assuming the user is jane below is an example. The problem in this approach is you need to keep updating it as and when new users gets onboarded.

apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
  name: namespace-reader
subjects:
# You can specify more than one "subject"
- kind: User
  name: jane # "name" is case sensitive
  apiGroup: rbac.authorization.k8s.io
roleRef:
  # "roleRef" specifies the binding to a Role / ClusterRole
  kind: ClusterRole #this must be Role or ClusterRole
  name: my-role # this must match the name of the Role or ClusterRole you wish to bind to
  apiGroup: rbac.authorization.k8s.io

An alternative and better approach would be to restrict all authenticated users from creating namespace using below ClusterRoleBinding. Since we are applying the ClusterRole to the group system:authenticated and every user who is successfully authenticated is placed into this group automatically by kubernetes, no user except admin user will be able to create namespace.

apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
  name: namespace-reader
subjects:
# You can specify more than one "subject"
- kind: Group
  name: system:authenticated
  apiGroup: rbac.authorization.k8s.io
roleRef:
  # "roleRef" specifies the binding to a Role / ClusterRole
  kind: ClusterRole #this must be Role or ClusterRole
  name: my-role # this must match the name of the Role or ClusterRole you wish to bind to
  apiGroup: rbac.authorization.k8s.io

Since admin user is part of a set of admin groups it will be possible to create namespace as admin user.

-- Arghya Sadhu
Source: StackOverflow