How to Read Kubernetes Secrets

John John (304)
5 minutes

So you've started using Kubernetes secrets. At some point, you'll probably want to see the secret in plain text, either to validate it or use it in another context. In this guide, I'll show you how to read Kubernetes secrets from the command line using kubectl.

tl;dr

$ kubectl get secret <SECRET_NAME> -o jsonpath="{.data.<DATA>}" | base64 --decode

Replace <SECRET_NAME> and <DATA>.

Posted in these interests:
h/kubernetes7 guides

If you're running multiple kubernetes clusters or haven't authenticated yet, you'll need to do so first. There are a handful of authentication strategies so I will not cover them each in this guide.

I run my clusters on GKE, so there's a handy gcloud command to get the configuration for a particular cluster and handle authentication.

Once you've authenticated you can confirm your current context with:

kubectl config current-context

Now let's assume we want to read from a secret called mysecret. The terminology might be a little bit tricky, so I'll try to explain. In Kubernetes, "secret" refers to the Secret object, and Secret objects can be composed of multiple pieces of sensitive information. In this demo, mysecret includes both a username and password.

So first we'll locate our secret:

$ kubectl get secrets
NAME                            TYPE                                  DATA      AGE
mysecret                        Opaque                                2         2d

And there's our secret. We can also confirm it has two pieces of data (presumably username and password).

Now let's describe the secret:

$ kubectl describe secret mysecret
Name:         mysecret
Namespace:    default
Labels:       <none>
Annotations:  
Type:         Opaque

Data
====
username: 20 bytes
password: 20 bytes

Ok. So we've got our secret with the username and password data.

Now, if we use kubectl get and set the output to yaml, we'll see the base64 encoded secret data.

$ k get secret mysecret -o yaml
apiVersion: v1
data:
  username: YWJjZGVmZ2hpamtsbW5vcHFyc3QK
  password: MTIzNDU2Nzg5MDEyMzQ1Njc4OTAK
...

Now to see the output in plain text you can simply copy the base64 encoded string, and decode it:

$ echo "YWJjZGVmZ2hpamtsbW5vcHFyc3QK" | base64 --decode
abcdefghijklmnopqrst

The previous step is useful for understanding how this breaks down, but here's a much easier way to read a secret:

$ kubectl get secret mysecret -o jsonpath="{.data.username}" | base64 --decode
abcdefghijklmnopqrst

Do you need to visualize data from multiple sources? Visit our guide for steps on how to install Apache Superset on a GKE Kubernetes Cluster.

John John (304)
5 minutes

As a Kubernetes user, I find that I often need to trigger a kubernetes cron job manually, outside of its schedule. Fortunately, since the release of Kubernetes 1.