export MAGIC_GROUP=dev
export MAGIC_CXT=user1-context
Create namespace for testing purpose : kubectl create namespace dev
Generate a key using OpenSSL:
openssl req -new -key ${MAGIC_USER}.key -out ${MAGIC_USER}.csr -subj "/CN=${MAGIC_USER}/O=${MAGIC_GROUP}"
if you are getting below error then execute : cd ~/; openssl rand -writerand .rnd
Error :: Can't load /root/.rnd into RNG
140256120328640:error:2406F079:random number generator:RAND_load_file:Cannot open file:../crypto/rand/randfile.c:88:Filename=/root/.rnd
openssl x509 -req -in ${MAGIC_USER}.csr -CA ~/.minikube/ca.crt -CAkey ~/.minikube/ca.key -CAcreateserial -out ${MAGIC_USER}.crt -days 500
Set a user entry in kubeconfig :
kubectl config set-credentials ${MAGIC_USER} --client-certificate=${MAGIC_USER}.crt --client-key=${MAGIC_USER}.key
Set a context entry in kubeconfig :
kubectl config set-context ${MAGIC_CXT} --cluster=minikube --user=${MAGIC_USER} --namespace=${MAGIC_GROUP}
kubectl config view
Switching to the created user
Now, instead of using the minikube context, we want to use user1-context:
kubectl config use-context ${MAGIC_CXT}
$ kubectl config current-context
MAGIC_CXT
$ kubectl config use-context ${MAGIC_CXT}
Create a Role :
apiVersion: rbac.authorization.k8s.io/v1
metadata:
namespace: dev
name: user1-role
rules:
- apiGroups: [""]
resources: ["pods","deployments"]
verbs: ["get", "list"]
Resources: pod, deployment, namespace, secret, configmap, service, persistentvolume…
Verbs: get, list, watch, create, delete, update, edit, exec.
Create a BindingRole :
kind: RoleBinding
apiVersion: rbac.authorization.k8s.io/v1
metadata:
name: user1-bind
namespace: dev
subjects:
- kind: User
name: user1
apiGroup: rbac.authorization.k8s.io
roleRef:
kind: Role #this must be Role or ClusterRole
name: user1-role
apiGroup: rbac.authorization.k8s.io
Switched to context "minikube".
$ kubectl apply -f role.yaml
role.rbac.authorization.k8s.io/user1-role created
$ kubectl apply -f role-binding.yaml
rolebinding.rbac.authorization.k8s.io/user1-bind created
Switch for test :
kubectl config use-context minikube
kubectl config use-context user1-context
Testing :
$ kubectl config use-context user1-context
$ kubectl create namespace ns-test # won't succeed, Forbidden
But, when try one of the allowed operations, like getting the pods:
$ kubectl get pods # this will succeed !
0 Comments