Kubernetes multiple environment variables per environment using Helm 3 go template

2/12/2020

I have 2 different values.yaml files per stage and production environment such as values.dev.yaml > values.prod.yaml and using with Helm 3. I would like to learn the best practices how to pass environment variables per environments.For instance we need to set different parameters to NODE_ENV variable.

-Should I specify the variable as hard coded as below and pass the environment variables when running helm upgrade/install command with --set flag?

-What is the correct way to use go template to do this. Can we specify something {{ .Values.node_env.value}} and then pass this env value in values yaml and use only -f values.yaml flag?

      containers:
            - name: {{ .Chart.Name }}
              securityContext:
                {{- toYaml .Values.securityContext | nindent 12 }}
              image: "{{ .Values.image.repository }}:{{ .Values.image.tag }}"
              imagePullPolicy: {{ .Values.image.pullPolicy }}
              ports:
                - name: http
                  containerPort: 8080
                  protocol: TCP
              resources:
                {{- toYaml .Values.resources | nindent 12 }}
              env: 
              - name: "NODE_ENV"
                value: "stage"
              - name: "NODE_ENV"
                value: "production"
-- semural
kubernetes
kubernetes-helm

1 Answer

2/13/2020

If you have one value file per environment (it is not clear to me this is your case.) like values.prod.yaml (for prod) and values.dev.yaml (for dev), then your templeate can look like this.

This will cause the template to look for extraEnv: in your values{dev/prod}.yaml and iterate over all key/values from that section.

  env:
    {{- range $key, $value := .Values.extraEnv }}
    - name: {{ $key }}
      value: {{ $value | quote }}
    {{- end }}

In your values.dev.yaml files you add all your KEY: values that are specific for this environment. Note you can have multiple key values here, all of them will be loaded. In this case we have NODE_ENV, ANOTHER_KEY, YET_ANOTHER_KEY - all of them will be loaded.

extraEnv:
  NODE_ENV: stage
  ANOTHER_KEY: value
  YET_ANOTHER_KEY: value

same in your values.prod.yaml multiple KEY: value pairs can be specified and all of them will be loaded.

extraEnv:
  NODE_ENV: production
  ANOTHER_KEY: value
-- Filip Nikolov
Source: StackOverflow