How to Read Kubernetes Secrets

Kubernetes secrets is a great way to store secret values that only Kubernetes can access in your hosted applications.

There are times when you might need to view these secrets in plain-text. This is probably because you want to validate the value or use it manually elsewhere.

In this tutorial we will go through how to achieve this and read Kubernetes secrets using kubectl for the command-line.

tl;dr

kubectl get secret <SECRET_NAME> -o jsonpath="{.data.<DATA>}" | base64 --decode
Code language: Bash (bash)

In the above sample code, simply replace <SECRET_NAME> and <DATA> with your own values.

Authenticate with your Kubernetes cluster

Start by authenticating into your Kubernetes cluster, you may need to first use an assume-role or awsume.

eval $(assume-role <PROFILE>)
Code language: Bash (bash)

If you are using AWS EKS, do this to update your local kubeconfig file:

aws eks --region <AWS_REGION> update-kubeconfig --name <CLUSTER_NAME>
Code language: Bash (bash)

If all else fails, it may be useful to check these authentication strategies.

Now you will need to confirm the context:

kubectl config current-context
Code language: Bash (bash)

List, read, and decode secret data

Let’s pretend that we want to read a secret called yoursecret. To do this we can use the below command to see the names of all the secrets, in order to narrow down what exists.

Let’s find our what our secret is called:

kubectl get secrets NAME TYPE DATA AGE yoursecret Opaque 2 3d
Code language: Bash (bash)

Now that we know what our secret is called, we can issue the next command and view it’s value.

Use the describe keyword to view the secret:

kubectl describe secret yoursecret Name: yoursecret Namespace: default Labels: <none> Annotations: Type: Opaque Data ==== username: 20 bytes password: 20 bytes
Code language: Bash (bash)

We now that the data contained in the secret contains a username and password.

This is where we use kubectl to get the outputs to YAML. This data is shown to us in a Base64 encoded string.

kubectl get secret yoursecret -o yaml apiVersion: v1 data: username: YWJjZGVmZ2hpamtsbW5vcHFyc3QK password: MTIzNDU2Nzg5MDEyMzQ1Njc4OTAK ...
Code language: Bash (bash)

Use the below command on the command-line to decode the Base64 value back to plain-text:

echo "YWJjZGVmZ2hpamtsbW5vcHFyc3QK" | base64 --decode abcdefghijklmnopqrst
Code language: Bash (bash)

A shortcut to decoding secret data

While the above is more of a tutorial on the steps to get this done, we can simplify these steps below into a single command:

kubectl get secret yoursecret -o jsonpath="{.data.username}" | base64 --decode abcdefghijklmnopqrst
Code language: Bash (bash)

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments