1

there are multiple stackoverflow answers regarding passing multiple variables to a template in Helm, using dictionary.

However, I want to pass a single variable to a template. For example, I want to define template such as below, receiving input (a string to be exact).

{{- define "blahblah" $var }}
  {{- if .Values.nameOverride }}
  name: {{ .Values.nameOverride }}-$var
  {{- else }}
  name: $var
  {{- end }}
{{- end }}

Thus, writing like below, I expect the result to be name: myname-whatever or name:whatever (assuming .Values.nameOverride was defined as 'myname')

{{- include "blahblah" "whatever" }}

How can I let helm know which is the input variable to the template? Thank you!

David Maze
  • 130,717
  • 29
  • 175
  • 215
Piljae Chae
  • 987
  • 10
  • 23

1 Answers1

7

A Go text/template template only accepts one parameter, and its value inside the template is the special variable .. So you could, for example:

{{- define "name" -}}
name: {{ . }}
{{ end -}}
{{- template "name" "foo" -}}
name: foo

Or, you can pass in the Helm top-level object

{{- define "name-override" -}}
name: {{ .Values.nameOverride }}
{{ end -}}
{{- template "name-override" . -}}

Notice in this case that, inside the defined template, we're referring to the Values field of ., and when we call it via template, we're explicitly passing down . as the parameter. Again, though, you only get one parameter.

Here you need two parameters: the Helm root value plus the additional value you're trying to pass in. I tend to use a list to package the two parameters together into one value:

{{- define "blahblah" -}}
{{- $top := index . 0 -}}
{{- $var := index . 1 -}}
{{- if $top.Values.nameOverride -}}
name: {{- $top.Values.nameOverride -}}-{{ $var }}
{{ else -}}
name: {{ $var }}
{{ end -}}
{{- end -}}

{{ include "blahblah" (list . "whatever") | indent 2 }}

So the parameter to the template, when you call it, is a list; index . 0 is the first item out of ., or the top-level Helm value, and index . 1 is the second item. The reverse of this is, since . is a list, you need to qualify values that actually are part of the top-level Helm value with the variable name $top that holds that value.

David Maze
  • 130,717
  • 29
  • 175
  • 215
  • https://stackoverflow.com/questions/70927158/cant-evaluate-field-values-in-type-string-when-using-helm-template – Piljae Chae Jan 31 '22 at 13:55
  • Opened up one more question! Thanks. – Piljae Chae Jan 31 '22 at 13:56
  • If these functions are written in a helper file, wouldn't they be able to directly access .Values without having to pass them in the function as a param? – MuKa Sep 16 '22 at 09:13
  • No, `.Values` is the `Values` field on the object `.`, which is the single function parameter here, and you need to explicitly pass the top-level Helm object down in `template` and `include` calls (no matter where they're defined). – David Maze Sep 16 '22 at 10:56