I try to prepare environment variables with an init container, such that these can be used in the “actual” container. Here is the essential code I used:
apiVersion: apps/v1
kind: Deployment
metadata:
name: myapp-deployment
labels:
app.kubernetes.io/name: MyApp
spec:
replicas: 1 # You can adjust the number of replicas as needed
selector:
matchLabels:
app: myapp
template:
metadata:
labels:
app: myapp
spec:
containers:
- name: myapp-container
image: busybox:1.28
command: ['sh', '-c', 'echo here && echo $MY_VARIABLE && sleep 3600']
initContainers:
- name: init-myservice
image: busybox:1.28
command: ['sh', '-c', 'export MY_VARIABLE="some_value" && sleep 1']
However, the main container does not recognize the variable I create in the initContainer.
Could you help me how to make that possible?
What you can do is define a shared volume for init container and the main container. In the init container create a file in the shared volume and include all required environment variables as key-value pairs.
Then in the main container export the key-value pairs from the file in shared volume ( source /shared-vol/myVars.txt ) and run the startup script.
Thank you for your question. Questions focused specifically on Kubernetes, such as configuring or deploying a cluster, may be better answered by the experts in either the Server Fault or DevOps. These platforms are highly knowledgeable in Kubernetes and can provide comprehensive support tailored to your needs. As a reminder, all questions on Stack Overflow must be specifically related to programming. We appreciate your understanding and encourage you to visit the “on-topic” pages of either site before posting there to ensure a more relevant and helpful response.
Where does the actual value come from; why does it need to be set at run time? Could you set it as an
ENV
value in your Dockerfile, or via deploy-time configuration using a tool like Kustomize or Helm?@DavidMaze I want to use Pgbouncer, but I do not like that I would have to use secrets. Instead I would like to use vault, prepare the secrets then, such that I can use them in the actual pgbouncer container.
initContainers cannot directly set environment variables for main containers, better to use ConfigMap/Secret.