Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

kubectl: get specific value from a secret in plaintext

I want to get the value of a specific field of a secret in a shell script.

From the kubectl get secret documentation, it seems the standard way to get a secret returns the whole thing, in a specified format, with the values base64 encoded.

So, to get the bar field of the foo secret, output as an unencoded string, I'm doing this:

kubectl get secret foo -o json | jq -r ".data.bar" | base64 --decode

That is

  • get the whole foo secret as JSON
  • pipe to jq to read the bar field from the JSON
  • decode the value using base64

Is there a way to do this only using kubectl?

Or an elegant way in POSIX-compliant shell that doesn't rely on any dependencies like jq?

like image 623
davnicwil Avatar asked Aug 06 '19 15:08

davnicwil


People also ask

How do I get Kubernetes secret value?

If you want to access data from a Secret in a Pod, one way to do that is to have Kubernetes make the value of that Secret be available as a file inside the filesystem of one or more of the Pod's containers. To configure that, you: Create a secret or use an existing one. Multiple Pods can reference the same secret.

How would you describe secret in Kubernetes?

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 . And there's our secret. We can also confirm it has two pieces of data (presumably username and password).

What is Type opaque in Kubernetes secrets?

type: Opaque means that from kubernetes's point of view the contents of this Secret is unstructured, it can contain arbitrary key-value pairs. In contrast, there is the Secret storing ServiceAccount credentials, or the ones used as ImagePullSecret . These have a constrained contents.


2 Answers

Try this

kubectl get secret foo --template={{.data.bar}} | base64 --decode

No need of jq.

like image 72
mchawre Avatar answered Sep 22 '22 08:09

mchawre


This should work since Kubernetes 1.11 (see PR 60755):

kubectl get secret foo -o go-template='{{ .data.bar | base64decode }}'

like image 37
SEBiGEM Avatar answered Sep 20 '22 08:09

SEBiGEM