Is it possible to define variables use if/else condition in helm chart?

8/22/2019

In my values.yaml I have:

isLocal: false
localEnv:
  url: abcd
prodEnv:
  url: defg

Then I have a service.yaml:

{{- if .Values.isLocal }}
{{- $env := .Values.localEnv }}
{{- else}}
{{- $env := .Values.prodEnv }}
{{- end}}
url: {{ $env.url}}

Unfortunately I got a 'undefined variable "$env"' error, does anyone have idea how to achieve this? Thanks!

-- disccip
kubernetes-helm

1 Answer

8/22/2019

The Go text/template documentation notes:

A variable's scope extends to the "end" action of the control structure ("if", "with", or "range") in which it is declared....

so your declarations of $env go out of scope at the end of the {{ if }}...{{ end }} block, which isn't so useful.

Helm also includes (almost all of) a support template library called Sprig which includes a ternary function, which acts sort of like an inline "if" statement. For your example you could write

{{- $env := ternary .Values.localEnv .Values.prodEnv .Values.isLocal -}}

(Also consider just writing totally separate Helm values files for each environment, and installing your chart with helm install -f prod.yaml, instead of trying to encapsulate every possible environment in a single file.)

-- David Maze
Source: StackOverflow