Setting secret into a environment variable

Although it's not a best practice to feed secrets into environment variables it's still something that it is possible to do. Let's take a glance on how to do it

We are going to use the same secret we uses for accessing secrets through a volumes:

$ kubectl create secret generic democredentials \
                --from-literal=username=jordi.prats \
                --from-literal=password='not_so_secret'

To be able to feed the secret into the environment variable we will have to use secretKeyRef setting the name of the secret as name and the key on that secret that we would like to use. For example, for the example secret we can create two environment variables with both keys as follows:

apiVersion: v1
kind: Pod
metadata:
  name: secret2env
spec:
  containers:
    - name: demo
      image: busybox
      command: ["sleep"]
      args: ["1h"]
      # mount volume at a given path; secret to volume declared below:
      env:
      - name: USERNAME
        valueFrom:
          secretKeyRef:
              name: democredentials
              key: username
      - name: PASSWORD
        valueFrom:
          secretKeyRef:
              name: democredentials
              key: password

Once we deploy the pod it will keep running for an hour:

$ kubectl apply -f ~/pod.yaml
pod/secret2env created
$ kubectl get pod
NAME         READY   STATUS    RESTARTS   AGE
secret2env   1/1     Running   0          6s

So we can use either create an interactive shell on the pod or just run the commands using kubectl exec:

$ kubectl exec secret2env -- sh -c 'echo $USERNAME'
jordi.prats
$ kubectl exec secret2env -- sh -c 'echo $PASSWORD'
not_so_secret

Posted on 5/3/2021