Skip to content
Kubernetes (K8s)

icon picker
Role based access control (RBACs) in k8s

image.png
Roles are limited to namespace, so before creating any role we need to create a namespace and then add user to the cluster and then define the role and use role binding to attach the role to the user.

Steps to create rbac in k8s:
**** Add User in Kubernetes Cluster **** 1. Create Name Space
kubectl create namespace development
2. Create private key and a CSR (Certificate Signing Request) for DevUser
$ cd ${HOME}/.kube
$ sudo openssl genrsa -out DevUser.key 2048
$ sudo openssl req -new -key DevUser.key -out DevUser.csr -subj "/CN=DevUser/O=development"
**The common name (CN) of the subject will be used as username for authentication request. The organization field (O) will be used to indicate group membership of the user.
3. Provide CA keys of Kubernetes cluster to generate the certificate
sudo openssl x509 -req -in DevUser.csr -CA ${HOME}/.minikube/ca.crt -CAkey ${HOME}/.minikube/ca.key -CAcreateserial -out DevUser.crt -days 45
4. Get Kubernetes Cluster Config
kubectl config view
5. Add the user in the Kubeconfig file.
kubectl config set-credentials DevUser --client-certificate ${HOME}/.kube/DevUser.crt --client-key ${HOME}/.kube/DevUser.key
6. Get Kubernetes Cluster Config
kubectl config view
*** User Creation end ***
7. Add a context in the config file, that will allow this user (DevUser) to access the development namespace in the cluster.
kubectl config set-context DevUser-context --cluster=minikube --namespace=development --user=DevUser
Create a Role for the DevUser : 1. Test access by attempting to list pods.
kubectl get pods --context=DevUser-context
*** As of now the user has no permission so the above command will give an error ***
2. Create a role resource using below manifest vi pod-reader-role.yml
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
namespace: development
name: pod-reader
rules:
- apiGroups: [""]
resources: ["pods", "pods/log"]
verbs: ["get", "watch", "list", "update"]
3. Create the role
kubectl apply -f pod-reader-role.yml
4. Verify Role
kubectl get role -n development
Bind the Role to the dev User and Verify Your Setup Works 1. Create the RoleBinding spec file vi pod-reader-rolebinding.yml
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
name: pod-reader
namespace: development
subjects:
- kind: User
name: DevUser
apiGroup: rbac.authorization.k8s.io
roleRef:
kind: Role
name: pod-reader
apiGroup: rbac.authorization.k8s.io
2. Create Role Binding
kubectl apply -f pod-reader-rolebinding.yml
3. Test access by attempting to list pods.
kubectl get pods --context=DevUser-context
4. Create Pod
kubectl run nginx --image=nginx --context=DevUser-context
Want to print your doc?
This is not the way.
Try clicking the ⋯ next to your doc name or using a keyboard shortcut (
CtrlP
) instead.