Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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!

like image 528
disccip Avatar asked Aug 22 '19 00:08

disccip


2 Answers

One more way would be to create the variable before starting the if/else block. For example:

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

Notice that I've not used the := operator inside the if block as the variable is already created.

and then

url: {{ $env.url}}
like image 168
Pallav Jha Avatar answered Sep 27 '22 22:09

Pallav Jha


You actually can define the variable $env outside the if block and assign its value using = with if block.

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

Please note: := will declare the variable while assigning the value. On the other hand, = will assign the value only. If you use := in if, it will declare a new local variable $env which will not impact the value of $env declared outside the if block.

like image 36
Jacky Jiang Avatar answered Sep 27 '22 23:09

Jacky Jiang