Kubernetes Pod Dynamic Environment Variables

12/19/2018

I need to be able to assign custom environment variables to each replica of a pod. One variable should be some random uuid, another unique number. How is it possible to achieve? I'd prefer continue using "Deployment"s with replicas. If this is not feasible out of the box, how can it be achieved by customizing replication controller/controller manager? Are there hooks available to achieve this?

-- rubenhak
controller
environment-variables
kubernetes

3 Answers

7/9/2019
kubectl run hello  --restart Never --image busybox  -- /bin/sh -c  "while true; do echo \$RANDOM; sleep 1;done"

or

kubectl run busybox --image busybox --env=random=$RANDOM --restart Never -- /bin/sh -c "echo \$random"

This works fine

[root@master 41-jobs]# kubectl logs hello

3298

16447

9517

3082

32611

19179

21098

12943

-- EAT
Source: StackOverflow

12/19/2018

You can use the downward API to inject the metadata.uid of the pod as an envvar, which is unique per pod

-- Jordan Liggitt
Source: StackOverflow

12/19/2018

If this is not feasible out of the box, how can it be achieved by customizing replication controller/controller manager? Are there hooks available to achieve this?

Your best bet is a mixture of an initContainer: and/or a custom -- possibly overridden -- entrypoint command:. The Pods are all going to be carbon copies of each other, except for their names and a few other trivial changes. Any per-Pod specific behavior is the responsibility of the containers in the Pod themselves.

containers:
- image: whatever
  command:
  - bash
  - -c
  - |
      export RANDOM_UUID=`uuidgen`
      export UNIQ=/usr/bin/generate-some-awesome-sauce
      exec /usr/local/bin/dockerfile-entrypoint.sh or whatever else
-- mdaniel
Source: StackOverflow