Felipe
Felipe

Reputation: 339

Usage of variables in Helm

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?

Upvotes: 0

Views: 8801

Answers (3)

Peter L
Peter L

Reputation: 3361

Variable Scope & Overwriting

I just got hit by a similar problem. Be aware:

  1. Variables have scope (you have 2 vars in different code blocks)
  2. Variables are overwritten with = (not :=)
  3. Empty string evaluates to false

Result:

{{- $bkDate := "2022-01-01" }}
{{- if .Value.persistence.home.restoreBackup.date }}
{{-   $bkDate = .Value.persistence.home.restoreBackup.date }}
{{- end }}

(Yes, simple string situations can use default but maybe this information is useful to others)

Upvotes: 1

David Maze
David Maze

Reputation: 159820

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.

Upvotes: 1

Harsh Manvar
Harsh Manvar

Reputation: 30178

Try

{{- if ((.Value.persistence.home.restoreBackup).date) }}
{{- $bkDate := .Value.persistence.home.restoreBackup.date }}
{{- else }}
{{- $bkDate := "2022-01-01" }}
{{- end }}

You can check the with option : https://helm.sh/docs/chart_template_guide/control_structures/#modifying-scope-using-with

{{ with PIPELINE }}
  # restricted scope
{{ end }}

Upvotes: 0

Related Questions