How to concatinate random generated string in Kubernetes secret yaml

139 views Asked by At

I have MongoDB and the backend pod needed to be running in the cluster. I want to generate the random password for Mongodb and use it as a connection string in my backend. Here is what my K8s secret looks like:

apiVersion: v1
kind: Secret
metadata:
  name: mongo-secrets
type: Opaque
data:
  MONGO_ROOT_USER: "root"
  MONGO_ROOT_PASS: $(head -c 24 /dev/random | base64)
  MONGO_DSN: 'mongodb://root:%{MONGO_ROOT_PASS}@localhost:27017/db'

MONGO_ROOT_USER, MONGO_ROOT_PASS is for MongoDB pod which is working fine. MONGO_DSN is for the backend pod which will connect to MongoDB.

As you can see MONGO_DSN value wouldn't work like that. I have tried with anchor reference also but the anchor in YAML doesn't support concatenation.

How to achieve this? My requirement is to generate the random password in K8s secret and use it again in the backend pod. Or this is not possible at all.

Thanks for your help.

1

There are 1 answers

1
David Maze On

Plain Kubernetes YAML can't run shell commands. Environment-variable substitution is only possible at one very specific point (inside the env: block of a Pod spec). You can't really build this as you describe.

Normally I'd recommend creating YAML files, checking them into source control, and using kubectl apply -f to install things in the cluster. If you need to generate an actually-random password, though, you may need kubectl create secret at the command line

kubectl create secret generic mongo-secrets \
  --from-literal=MONGODB_ROOT_PASS=$(head -c 24 /dev/random | base64)

Note that your local shell runs the subcommand before passing the argument to kubectl (try putting echo at the very start of the line to see the result of shell processing); Kubernetes still doesn't know anything about the subcommand.

The MONGO_DSN syntax isn't especially sensitive and you need to assemble it at the point where you use it. You can use $(VARIABLE_NAME) syntax to include other variables specifically inside an env: block in a Pod spec (usually embedded in a Deployment, Job, or StatefulSet object).

env:
  - name: MONGODB_ROOT_USER  # inlined for simplicity, could also be
    value: root              # embedded in the Secret
  - name: MONGODB_ROOT_PASS
    valueFrom:
      secretKeyRef:
        name: mongodb-secrets
        key: MONGODB_ROOT_PASS
  - name: MONGO_DSN
    value: mongodb://$(MONGODB_ROOT_USER):$(MONGODB_ROOT_PASS)@localhost:27017/db