I'm using a Helm chart and I was wondering how I can define a value by default. In my case, I wanna define a date when it isn't defined in values.yaml and I have the following code:
{{- if ne .Value.persistence.home.restoreBackup.date "" }}
{{- $bkDate := .Value.persistence.home.restoreBackup.date }}
{{- else }}
{{- $bkDate := "2022-01-01" }}
{{- end }}
I wanna set $bkDate to an specific date if it is not defined in .Value.persistence.home.restoreBackup.date
but when I try to print $bkDate it is empty.
Do you know what is wrong here?
The Go text/template
documentation notes (under "Variables"):
A variable's scope extends to the "end" action of the control structure ("if", "with", or "range") in which it is declared....
This essentially means you can't define a variable inside an if
block and have it visible outside the block.
For what you want to do, the Helm default
function provides a straightforward workaround. You can unconditionally define the variable, but its value is the Helm value or else some default if that's not defined.
{{- $bkDate := .Value.persistence.home.restoreBackup.date | default "2022-01-01" -}}
(Note that a couple of things other than empty-string are "false" for purposes of default
, including "unset", nil
, and empty-list, but practically this won't matter to you.)
If you need more complex logic than this then the ternary
function could meet your needs {{- $var := $someCondition | ternary "trueValue" "falseValue" -}}
but this leads to hard-to-read expressions, and it might be better to refactor to avoid this.