Scenario
Suppose, in your organization, different teams are using a CI/CD pipeline. QA team is asking you to share the kubeconfig & the service account token to run the job to deploy on the Kubernetes cluster.
But you want to restrict the QA team to access the only test
namespace. Not only that! you want to restrict specific resources like pods, daemonsets, deployments
also within that namespace.
This is where you can use the RBAC (Role Based Access Control) concept in Kubernetes,
In this example, we will go through the steps to achieve this.
Note: If you are using docker for desktop, you need to delete existing cluster rolebinding docker-for-desktop-binding, otherwise RBAC rules won’t be respected. please read here
kubectl delete clusterrolebinding docker-for-desktop-binding
ClusterRole and RoleBinding
Create service accounts, test-user
in namespace qa
kubectl create ns qa
kubectl create sa test-user -n qa
Create clusterRole and Rolebinding using the config below.
Before this step! remember my friend,
A RoleBinding grants permissions within a specific namespace whereas a ClusterRoleBinding grants that access cluster-wide
So, you have to use a RoleBinding but NOT ClusterRoleBinding
kubectl apply -f <config.yaml> -n qa --- kind: ClusterRole apiVersion: rbac.authorization.k8s.io/v1 metadata: name: test-namespace-role namespace: qa rules: - apiGroups: ["*"] resources: ["pods", "deployments","statefulsets", "daemonsets"] verbs: ["create", "update", "get", "list"] --- kind: RoleBinding apiVersion: rbac.authorization.k8s.io/v1 metadata: name: test-namespace-only namespace: qa subjects: - kind: ServiceAccount
name: test-user namespace: qa roleRef: kind: ClusterRole name: test-namespace-role apiGroup: rbac.authorization.k8s.io
Generate token
TOKEN=$(kubectl describe secrets "$(kubectl describe sa test-user -n qa | grep -i Tokens | awk '{print $2}')" -n qa| grep token: | awk '{print $2}') echo $TOKEN
Set token to the context
Set the token to the kubeconfig to test the access granted to this token,
kubectl config set-context test-user --cluster=docker-desktop --user=test-user kubectl config set-credentials test-user --token=$TOKEN
kubectl config use-context test-user
Now, test if you have access to resources on namespaces other than the test
namespace.
kubectl get pods kubectl get pods -n test kubectl get cm -n test
Similarly, you can also test this accessibility using can-i
as shown below,
kubectl auth can-i get pods
Now, you can export the kubeconfig
, and share it with your qa
team
kubectl config view --minify > qa-config.yaml
For personal training on Kubernetes join the CKA course here