How to deploy a secret resource?

12/19/2020

I am new to Kubernetes, and trying to wrap my head around how to set secrets. I will try to illustrate with an example. Let's say I have a secret resource that looks like:

apiVersion: v1
kind: Secret
metadata:
  name: big-secrets
type: Opaque
data:
  secret-password: "secretMeow"
  secret-key: "angryWoof"
  database-password: "happyWhale"

How do I set up (not sure if set up is the right word here) these secrets using kubectl, and how do I retrieve them? I have tried reading through the following documentation but I am still not sure how to set up from a yaml file as mentioned above.

-- alt-f4
kubernetes

2 Answers

12/20/2020

Using stringData it is possible to create a secret using plain text values:

apiVersion: v1
kind: Secret
metadata:
  name: big-secrets
type: Opaque
stringData:
  secret-password: "secretMeow"
  secret-key: "angryWoof"
  database-password: "happyWhale"

However it's worth noting it's provided more for convenience and the docs say:

It is provided as a write-only convenience method. All keys and values are merged into the data field on write, overwriting any existing values. It is never output when reading from the API.

For the question of how to read the secret, if you wanted it programatically, you could use a tool like jq to parse the Kubernetes output and base64 decode:

kubectl get secret big-secrets -o json | jq -r '.data["secret-password"] | @base64d'

This would get the created secret as JSON (-o yaml is also an option), read the data field for a given secret (secret-password in this case) and then base64 decode it.

-- Dom
Source: StackOverflow

12/19/2020

Using yaml file you cannot create secret without encoded string value. Secret data value must be in base64 encoded in yaml file. If you want to create a secret from yaml file then you need to decode data value like below.

apiVersion: v1
kind: Secret
metadata:
  name: big-secrets
type: Opaque
data:
  secret-password: c2VjcmV0TWVvdwo=
  secret-key: YW5ncnlXb29mCg==
  database-password: aGFwcHlXaGFsZQo=

Or

You can use kubectl imperative command to create a secret from literal values like below.

kubectl create secret generic big-secrets --from-literal=secret-password="secretMeow" --from-literal=secret-key="angryWoof"
-- Kiruba
Source: StackOverflow