Search code examples
kubernetes-helmgo-templates

Helm pass single string to a template


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!


Solution

  • 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.