How to set an environment variable to diffetent values in different instances of same POD?

12/19/2019

I want to have two instances of same POD with an environment variable with different values in them. How can we acheive this ?

THanks

-- Chandu
kubernetes
pod

1 Answer

12/19/2019

You can achieve what you want using one pod containing 2 different containers.

Here is an example on how to achieve that:

apiVersion: v1
kind: Pod
metadata:
  name: busybox
spec:
  containers:
  - name: busybox1
    image: busybox:1.28
    env:
    - name: VAR1
      value: "Hello I'm VAR1"
    command:
      - sleep
      - "3600"
    imagePullPolicy: IfNotPresent
  - name: busybox2
    image: busybox:1.28
    env:
    - name: VAR2
      value: "VAR2 here"
    command:
      - sleep
      - "3600"
    imagePullPolicy: IfNotPresent
  restartPolicy: Always

We are creating 2 containers, one with VAR1 and the second with VAR2.

$ kubectl exec -ti busybox -c busybox1 -- env
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
HOSTNAME=busybox
TERM=xterm
VAR1=Hello I'm VAR1
KUBERNETES_PORT_443_TCP_ADDR=10.31.240.1
KUBERNETES_SERVICE_HOST=10.31.240.1
KUBERNETES_SERVICE_PORT=443
KUBERNETES_SERVICE_PORT_HTTPS=443
KUBERNETES_PORT=tcp://10.31.240.1:443
KUBERNETES_PORT_443_TCP=tcp://10.31.240.1:443
KUBERNETES_PORT_443_TCP_PROTO=tcp
KUBERNETES_PORT_443_TCP_PORT=443
HOME=/root
$ kubectl exec -ti busybox -c busybox2 -- env
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
HOSTNAME=busybox
TERM=xterm
VAR2=VAR2 here
KUBERNETES_PORT=tcp://10.31.240.1:443
KUBERNETES_PORT_443_TCP=tcp://10.31.240.1:443
KUBERNETES_PORT_443_TCP_PROTO=tcp
KUBERNETES_PORT_443_TCP_PORT=443
KUBERNETES_PORT_443_TCP_ADDR=10.31.240.1
KUBERNETES_SERVICE_HOST=10.31.240.1
KUBERNETES_SERVICE_PORT=443
KUBERNETES_SERVICE_PORT_HTTPS=443
HOME=/root

As you can see, they have the same hostname (inheritance from Pod name) and different variables.

-- mWatney
Source: StackOverflow