One liner command to get secret name and secret's token One liner command to get secret name and secret's token kubernetes kubernetes

One liner command to get secret name and secret's token


Answer that I discovered was below. By using jsonpath to retrieve and xargs to pass the secret name/output to second command. Will need to decode the encrypted token with base64 at the end.

$ kubectl get serviceaccount default -o=jsonpath='{.secrets[0].name}' | xargs kubectl get secret -ojsonpath='{.data.token}' | base64 --decodeTOKENHERE%

The tailing % is not part of the token

This should be able to work on MacOS without install additional app like jq which should be able to do the same. Hope this is helpful for others.


You generally don't need to run either command. Kubernetes will automatically mount the credentials to /var/run/secrets/kubernetes.io/serviceaccount/token in a pod declared using that service account, and the various Kubernetes SDKs know to look for credentials there. Accessing the API from a Pod in the Kubernetes documentation describes this setup in more detail.

Configure Service Accounts for Pods describes the Pod-level setup that's possible to do, though there are reasonable defaults for these.

apiVersion: v1kind: Pod # or a pod spec embedded in a Deployment &c.spec:  serviceAccountName: my-service-account # defaults to "default"  automountServiceAccountToken: true     # defaults to true

I wouldn't try to make requests from outside the cluster as a service account. User permissions are better suited for this use case. As a user you could launch a Job with service-account permissions if you needed to.


Example using kubectl describe instead of kubectl get and adding the namespace definition:

kubectl -n kube-system describe secret $(kubectl -n kube-system describe sa default | grep 'Mountable secrets' | awk '{ print $3 }') | grep 'token:' | awk '{ print $2 }'