Skip to content

ServiceAccount token extraction from Kubernetes Secret

ServiceAccount token extraction from Kubernetes Secret refers to the manual retrieval of an authentication token from a Kubernetes Secret object that is associated with a [[ServiceAccount]]. This process is commonly used to authenticate with the Kubernetes Dashboard or the API server when direct command-line access is insufficient^[400-devops__06-Kubernetes__k8s-ithelp__Day5__README.md].

Background

In Kubernetes, [[ServiceAccounts]] provide identities for processes that run in a Pod. When a [[ServiceAccount]] is created, Kubernetes automatically generates a Secret containing a bearer token. This token can be used to authenticate with the Kubernetes API^[400-devops__06-Kubernetes__k8s-ithelp__Day5__README.md].

While pods typically mount this token automatically, administrators or users may need to extract this token explicitly to log into Web UIs or configure external clients.

Prerequisites

Before extracting a token, ensure that the [[ServiceAccount]] exists and has the appropriate [[RBAC]] permissions (such as ClusterRoleBinding) to perform the intended actions^[400-devops__06-Kubernetes__k8s-ithelp__Day5__README.md]. If the associated Secret does not exist, it can be created manually^[400-devops__06-Kubernetes__k8s-ithelp__Day5__README.md].

Extraction Process

The extraction process typically involves identifying the Secret associated with the target [[ServiceAccount]] and decoding its content.

1. Retrieve the Token Data

Use kubectl get secrets to list secrets in the namespace, and kubectl describe secret to view the details of the specific secret (e.g., default token in kube-system namespace)^[400-devops__06-Kubernetes__k8s-ithelp__Day5__README.md].

[kubectl](<./kubectl.md>) -n kube-system describe secret default

The output will contain a token: field with an encoded string.

2. Process and Decode

The raw token string can be extracted using text processing tools like awk^[400-devops__06-Kubernetes__k8s-ithelp__Day5__README.md].

TOKEN=$([kubectl](<./kubectl.md>) -n kube-system describe secret default | awk '$1=="token:"{print $2}')

Once captured in a variable, the token can be printed to the terminal or injected into a configuration file^[400-devops__06-Kubernetes__k8s-ithelp__Day5__README.md].

echo $TOKEN

3. Usage

The extracted token is a Bearer Token. It can be entered directly into login fields for tools like the Kubernetes Dashboard or used to configure kubectl credentials^[400-devops__06-Kubernetes__k8s-ithelp__Day5__README.md].

Sources

^[400-devops__06-Kubernetes__k8s-ithelp__Day5__README.md]