How to create one user which have access to all the namespaces except one in kubernetes

10/30/2020

How to create one user called kubernetes-dashboard and that user access my all the namespaces ns1, ns2, ns3, ns5 except ns4.

-- Gaurav Agnihotri
amazon-eks
kubernetes

1 Answer

10/30/2020
  • I have created sample namespaces ns1,ns2,ns3 & ns4. i want my new user to have access to ns1,ns2,ns3 but not to ns4
kubectl get ns
NAME              STATUS   AGE
calico-system     Active   21h
default           Active   21h
kube-node-lease   Active   21h
kube-public       Active   21h
kube-system       Active   21h
ns1               Active   36m
ns2               Active   36m
ns3               Active   36m
ns4               Active   36m
tigera-operator   Active   21h
  1. Create a sample service account named "kubernetes-dashboard" in default namespace:
[root@project1kubemaster ~]# kubectl create serviceaccount kubernetes-dashboard
serviceaccount/kubernetes-dashboard created
  1. Create ClusterRole named "kubernetes-dashboard-role"
[root@project1kubemaster ~]# kubectl create clusterrole kubernetes-dashboard-role --verb=* --resource=*
clusterrole.rbac.authorization.k8s.io/kubernetes-dashboard-role created
  1. Create separate RoleBinding in each namespaces of our interest (ns1,ns2,n3) but not on ns4:
[root@project1kubemaster ~]# kubectl create rolebinding kubernetes-dashboard-rolebinding-ns1 --clusterrole=kubernetes-dashboard-role --namespace=ns1 --serviceaccount=default:kubernetes-dashboard
rolebinding.rbac.authorization.k8s.io/kubernetes-dashboard-rolebinding-ns1 created

[root@project1kubemaster ~]# kubectl create rolebinding kubernetes-dashboard-rolebinding-ns2 --clusterrole=kubernetes-dashboard-role --namespace=ns2 --serviceaccount=default:kubernetes-dashboard
rolebinding.rbac.authorization.k8s.io/kubernetes-dashboard-rolebinding-ns2 created

[root@project1kubemaster ~]# kubectl create rolebinding kubernetes-dashboard-rolebinding-ns3 --clusterrole=kubernetes-dashboard-role --namespace=ns3 --serviceaccount=default:kubernetes-dashboard
rolebinding.rbac.authorization.k8s.io/kubernetes-dashboard-rolebinding-ns3 created
  1. Testing :
[root@project1kubemaster ~]# kubectl auth can-i get pods -n ns1 --as  system:serviceaccount:default:kubernetes-dashboard
yes
[root@project1kubemaster ~]# kubectl auth can-i get pods -n ns2 --as  system:serviceaccount:default:kubernetes-dashboard
yes
[root@project1kubemaster ~]# kubectl auth can-i get pods -n ns3 --as  system:serviceaccount:default:kubernetes-dashboard
yes
[root@project1kubemaster ~]# kubectl auth can-i get pods -n ns4 --as  system:serviceaccount:default:kubernetes-dashboard
no
-- confused genius
Source: StackOverflow