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.
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 needkubectl create secret
at the command lineNote that your local shell runs the subcommand before passing the argument to
kubectl
(try puttingecho
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 anenv:
block in a Pod spec (usually embedded in a Deployment, Job, or StatefulSet object).