Create per-file Kubernetes secrets from a directory of text files in Kustomize

7/2/2019

I have a number of secret "environment variables" I want to get into a kubernetes cluster. Currently, I have a directory of these secrets where each var has a corresponding file named the same way as the variable it is supposed to be assigned to. Using docker-compose, this gives me a script like for secret in .secrets/*; do export "$(basename $secret)"="$(cat $secret)" ; done

I'm hoping to avoid explicitly specifying each one of these secrets in the kustomize file(s). Is there a simple way to create one secret per file by only specifying the directory?

-- Ben
kubectl
kubernetes
kustomize

1 Answer

7/2/2019

Here is one way you could accomplish this outside of Kustomize.

Secrets can be consumed as environment variables in the Pod spec using the valueFrom keyword. Documentation about this is at https://kubernetes.io/docs/concepts/configuration/secret/#using-secrets-as-environment-variables.

Knowing this, you could modify your script to create a main secret and a key per file. An example (untested) might look something like:

for secret in .secrets/*; do
    literals="$literals --from-literal=$(basename $secret)=$(cat $secret)"
done

kubectl create secret generic prod-secrets "$literals"

Then, in your specs reference the specific key from that secret to get the corresponding environment variable. Assuming one of them was SECRET_USERNAME:

apiVersion: v1
kind: Pod
metadata:
  name: secret-env-pod
spec:
  containers:
  - name: mycontainer
    image: redis
    env:
      - name: SECRET_USERNAME
        valueFrom:
          secretKeyRef:
            name: prod-secrets
            key: SECRET_USERNAME
  restartPolicy: Never
-- Andy Shinn
Source: StackOverflow