Import a ServiceAccount token into kubeconfig

ServiceAccount token kubeconfig import user credentials

2 min read | by Jordi Prats

To locally run some process we might need to use some ServiceAccount credentials to make sure it has the same exact permissions it would have running it as a Pod. To do se we can import the ServiceAccount token into our kubeconfig to be able to impersonate it.

Let's assume we want to use the test-sa:

$ kubectl get sa
NAME      SECRETS   AGE
default   0         10d
test-sa   0         113s

If we haven't any available yet, will have to create a new token for the ServiceAccount by creating the Secret that's going to hold it:

cat <<"EOF" | kubectl apply -f -
apiVersion: v1
kind: Secret
type: kubernetes.io/service-account-token
metadata:
  name: test-sa-token
  annotations:
    kubernetes.io/service-account.name: test-sa
EOF

We'll need to retrieve data.token and imported it into kubeconfig as a token. We can use kubectl as follows to do it:

kubectl config set-credentials test-sa --token="$(kubectl get secret test-sa-token -o jsonpath='{.data.token}' | base64 -d)"

This will update the kubeconfig, adding the test-sa user which will look something like this:

apiVersion: v1
kind: Config
(...)
users:
- name: test-sa
  user:
    token: hejda...

To start using it we can just update the context, choosing which user we want to use using the --user option:

kubectl config set-context --current --user=test-sa

If we want to change it back we'll just need to specify which user we want to use.


Posted on 29/05/2023