Composing environment variables with other environment variables in k8s containers

5/19/2021

Can environment variables passed to containers be composed from environment variables that already exist? Something like:

apiVersion: apps/v1
kind: Deployment
metadata:
  name: nginx-deployment
  labels:
    app: nginx
spec:
  replicas: 3
  selector:
    matchLabels:
      app: nginx
  template:
    metadata:
      labels:
        app: nginx
    spec:
      containers:
      - name: nginx
        image: nginx:1.14.2
        ports:
        - containerPort: 80
        env:
        - name: URL
          value: $(HOST):$(PORT)
-- Marko Galesic
environment-variables
kubernetes

3 Answers

5/19/2021

Helm with it's variables seems like a better way of handling that kind use cases. In the example below you have a deployment snippet with values and variables:

    spec:
      containers:
        - name: {{ .Chart.Name }}
          image: "image/thomas:{{ .Values.image.tag }}"
          imagePullPolicy: {{ .Values.image.pullPolicy }}
          env:
            - name: URL
              value: {{ .Values.host }}:{{ .Values.port }}

And here is one of the ways of deploying it with some custom variables:

helm upgrade --install  myChart . \
  --set image.tag=v2.5.4 \
  --set host=example.com \
  --set-string port=12345 \

Helm allows you also to use template functions. You can have defaultfunctions and this will go to default values if they're not filled. In the example above you can see required which display the message and fails to go further with installing the chart if you won't specify the value. There is also include function that allows you to bring in another template and pass results to other template functions.

-- acid_fuji
Source: StackOverflow

5/19/2021

These manifests are complete files. Not a good way to use variables in it. Though you can.

use the below command to replace and pipe it to kubectl.

sed -i -e "s#%%HOST%%#http://whatever#" file.yml;

Though I would suggest to use Helm.

Read more: https://kubernetes.io/docs/tasks/inject-data-application/define-environment-variable-container/

-- Supritam
Source: StackOverflow

5/19/2021

Within a single Pod spec, this works with exactly the syntax you described, but the environment variables must be defined (earlier) in the same Pod spec. See Define Dependent Environment Variables in the Kubernetes documentation.

<!-- language: lang-yaml -->
env:
  - name: HOST
    value: host.example.com
  - name: PORT
    value: '80'
  - name: URL
    value: '$(HOST):$(PORT)'

Beyond this, a Kubernetes YAML file needs to be totally standalone, and you can't use environment variables on the system running kubectl to affect the file content. Other tooling like Helm fills this need better; see @thomas's answer for an example.

-- David Maze
Source: StackOverflow