I'm deploying two statefulset pods of same image running as headless service. I wish to pass seperate env variables to containers running same images inside statefulset pods. May anyone tell me how to achieve this ?
It is not possible to expose different values of same environment variable to different containers of a Statefulsets
as the pods in a Statefulsets
are identical replicas of the same application.
From the docs:
Like a Deployment, a StatefulSet manages Pods that are based on an identical container spec. Unlike a Deployment, a StatefulSet maintains a sticky identity for each of their Pods. These pods are created from the same spec, but are not interchangeable: each has a persistent identifier that it maintains across any rescheduling.
However, as noted in the above doc, as each pod of a Statefulset has sticky identity using which you can pass the same set of environment variables to the pods and take appropriate actions using the different environment variables based on the identity of the pods.
You can expose the pod name to the containers via environment variables through Downward API and use it inside the scripts to take appropriate action:
env:
- name: MY_POD_NAME
valueFrom:
fieldRef:
fieldPath: metadata.name
- name: env0
value: value0
- name: env1
value: value1
So, if you have two replicas of a Statefulset
with name myapp
then the pods will have the names as myapp-0
and myapp-1
and you can then use the environment variable based on the name of the pod (env0
if pod name is myapp-0
and env1
if pod name is myapp-1
).
Note: Although the solution works yet it should not be preferred and we should instead have separate statefulsets objects for exposing different environment variables depending on the use case.