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 onto kubernetes cluster.
But you want to restrict the qa team to access only test
namespace. Not only that! you want to restrict specific resources like pods, daemonsets, deployments
also withtin that namespace.
This is where you can use the RBAC concept in kubernetes,
In this example, we will go through the steps to acheive this.
Note: If you are using docker for desktop, you need to delete existing cluster rolebinding docker-for-desktop-binding, other wise 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 test.
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