kubectl Token Retrieval Pattern¶
The kubectl Token Retrieval Pattern is a command-line technique used to extract and decode the authentication token for a Kubernetes ServiceAccount.^[400-devops__06-Kubernetes__k8s-learning__linux__03-dashboard__README.md] This method is commonly used to access the Kubernetes Dashboard or interact with the API via a user account associated with a service account token.
Command Syntax¶
The pattern involves a compound command that first identifies the secret name associated with the service account, and then retrieves and decodes the token.
The standard command structure is:
[kubectl](<./kubectl.md>) -n <namespace> get secret $([kubectl](<./kubectl.md>) -n <namespace> get sa/<service-account-name> -o jsonpath="{.secrets[0].name}") -o go-template="{{.data.token | base64decode}}"
In a typical dashboard setup (e.g., in the kubernetes-dashboard namespace for the admin-user), the command looks like this:
[kubectl](<./kubectl.md>) -n kubernetes-dashboard get secret $([kubectl](<./kubectl.md>) -n kubernetes-dashboard get sa/admin-user -o jsonpath="{.secrets[0].name}") -o go-template="{{.data.token | base64decode}}"
How It Works¶
The command functions by chaining two kubectl operations:
-
Inner Command (Secret Name Resolution):
kubectl -n <namespace> get sa/<service-account-name> -o jsonpath="{.secrets[0].name}"- This fetches the ServiceAccount (
sa) details. - It uses
jsonpathto output the name of the first secret stored in the ServiceAccount's.secretsfield^[400-devops__06-Kubernetes__k8s-learning__linux__03-dashboard__README.md].
- This fetches the ServiceAccount (
-
Outer Command (Token Extraction):
kubectl -n <namespace> get secret <secret-name-from-inner-command> -o go-template="{{.data.token | base64decode}}"- This retrieves the Kubernetes Secret object identified by the inner command.
- It uses a Go template to access the
.data.tokenfield. - It applies
base64decodeto convert the Base64-encoded token string into a readable, usable authentication token^[400-devops__06-Kubernetes__k8s-learning__linux__03-dashboard__README.md].
Usage Example¶
Once the ServiceAccount and ClusterRoleBinding are created, the token can be retrieved to log in via the web interface.
For example, after applying RBAC rules for an admin-user, the output of the command will be a long JWT string (starting with eyJhbGci...), which can be pasted directly into the Dashboard login screen^[400-devops__06-Kubernetes__k8s-learning__linux__03-dashboard__README.md].
Sources¶
^[400-devops__06-Kubernetes__k8s-learning__linux__03-dashboard__README.md]