Search code examples
kubernetes-helm

modify variable in outer scope of a Kubernetes Helm template


I can append characters to a variable (i.e. concatenate) in Helm like that

{{- $myvar := "foo" }}
{{- $myvar := printf "%s-%s" $myvar "bar" }}
myvar: {{ $myvar }} # myvar: foo-bar

I do need this concatenation when iterating over files. Unfortunately - probably due to the variable scope - changing the variable is local to the scope. Let's use tuples for the sake of simplicity:

data:
{{- $myvar := "foo" }}
{{- $myvar := printf "%s-%s" $myvar "bar" }}
{{- range tuple "vala" "valb" "valc" }}
  {{- $myvar := printf "%s-%s" $myvar . }}
  {{ . }}: {{ $myvar }}
{{- end }}
  myvar: {{ $myvar }}

is rendered as

data:
  vala: foo-bar-vala
  valb: foo-bar-valb
  valc: foo-bar-valc
  myvar: foo-bar

How do I get the code rewritten, so I can actually append values to the $myvar variable in the outer scope?


Solution

  • The problem is that due to usage of := operator a new $myvar variable is declared and modified in the inner scope of the range operator which has no effect on the $myvar variable declared in the outer scope

    To achieve modification of the $myvar from outer scope the = operator needs to be used.

    So this template

    data:
    {{- $myvar := "foo" }}
    {{- $myvar := printf "%s-%s" $myvar "bar" }}
    {{- range tuple "vala" "valb" "valc" }}
      {{- $myvar = printf "%s-%s" $myvar . }}
      {{ . }}: {{ $myvar }}
    {{- end }}
      myvar: {{ $myvar }}
    

    is rendered as

    data:
      vala: foo-bar-vala
      valb: foo-bar-vala-valb
      valc: foo-bar-vala-valb-valc
      myvar: foo-bar-vala-valb-valc