This is useful in cases when you want to limit access for specific cluster elements -for example Kubernetes Dashboard.
Create SA:
kubectl create sa simpleuser
Manually create a long-lived API token for SA:
kubectl apply -f - <<EOF
apiVersion: v1
kind: Secret
metadata:
name: simpleuser-secret
annotations:
kubernetes.io/service-account.name: simpleuser
type: kubernetes.io/service-account-token
EOF
Describe SA to check if secret was assigned to SA:
kubectl describe sa simpleuser
kubectl describe secret simpleuser-secret
You should have a bearer token. This token will be lately used in kubectl config.kubectl create clusterrole simpleusercr --verb=get,list,watch --resource=pods,deployments,services,configmaps
Create a clusterrolebinding which bounds SA with clusterrole:
kubectl create clusterrolebinding simpleusercrb --clusterrole=simpleusercr --serviceaccount=default:simpleuser
Prepare user token (from the secret created earlier):
USER_TOKEN=$(kubectl get secret simpleuser-secret -o json | jq -r '.data["token"]' | base64 -d)
echo $USER_TOKEN
Set kubectl credentials for this SA:
kubectl config set-credentials simpleuser --token="$USER_TOKEN"
Set a new context:
kubectl config set-context simpleuser --cluster=kubernetes --user simpleuser
Get all contexts:
kubectl config get-contexts
And switch the current context to this new created one:
kubectl config use-context simpleuser
Test - these operations you allowed:
kubectl get po
kubectl get deploy
kubectl get configmap
For getting secrets - you are not allowed:
kubectl get secret
You will get the following error:
Error from server (Forbidden): secrets is forbidden: User "system:serviceaccount:default:simpleuser" cannot list resource "secrets" in API group "" in the namespace "default"