Obtaining the Service Account Token

Service Account Token is one of the authorization methods in the Kubernetes API, an alternative to the Static Token File and client certificates.

To obtain the token, you need to create a service account (ServiceAccount) and associate it with the cluster role. Each created service account will have a token stored in the Kubernetes Secret API.

To obtain the Service Account Token:

  1. Create ServiceAccount:

    kubectl -n kube-system create serviceaccount <service-account-name>
  2. Create ClusterRoleBinding and add an admin role (cluster-admin):

    kubectl create clusterrolebinding <clusterrolebinding-name> --clusterrole=cluster-admin --serviceaccount=kube-system:<service-account-name>
  3. Get the secret name of the created ServiceAccount that stores the token:

    export TOKENNAME=$(kubectl -n kube-system get serviceaccount/<service-account-name> -o jsonpath='{.secrets[0].name}')
  4. Get the token from the secret in base64, decode it and add to the TOKEN environment variable:

    export TOKEN=$(kubectl -n kube-system get secret $TOKENNAME -o jsonpath='{.data.token}' | base64 --decode)
  5. Check the token health level, make a request to the Kubernetes API with the token in the "Authorization: Bearer <TOKEN-HERE>" header:

    curl -k -H "Authorization: Bearer $TOKEN" -X GET "https://<KUBE-API-IP>:6443/api/v1/nodes" | json_pp
  6. Add the service account to kubeconfig:

    kubectl config set-credentials <service-account-name> --token=$TOKEN
  7. Change the current context:

    kubectl config set-context --current --user=<service-account-name>
  8. Perform a health check:

    kubectl get no                                                                                                      
    NAME                  STATUS   ROLES    AGE   VERSION
    test-psp-node-tv9rb   Ready    <none>   33d   v1.16.9

The updated kubeconfig will be located in the $HOME/.kube/config home directory.