Search code examples
kubernetes-helm

data from values file lost when I pass parameter in template file in hele


That's how I passed variable to template file

{{ template "fluentd-config" (dict "replica" "bbcc" "pattern" "aabb"  ) }}

and here is template file

{{- define "fluentd-config" -}}
image: {{ .Values.fluentd.kinesis_image }}
myname: {{ .replica }}
pattern: {{ .pattern }}
{{- end -}}

and when I run it, .Values.fluentd.kinesis_image gone null. Please let me know how to resolve it. Thanks.


Solution

  • Inside a Go text/template template, the special variable . is the parameter to the template. Also remember that the syntax .foo means looking up the field foo in the object .. So in this context, the template parameter replaces the Helm global object; .Values tries to look it up in the dictionary you're passing as a parameter.

    One solution to this is to also pass in .Values at the call site (if you need any of the other top-level Helm objects you also need to manually pass those in):

    {{ template "fluentd-config" (dict "replica" "bbcc" "pattern" "aabb" "Values" .Values) }}
    

    A more complex pattern I've used is to pass a list as the template parameter, and then extract fields out of that. You can use the Sprig list functions to construct and deconstruct the list. (You could do something similar with dict to have named parameters and that might be syntactically simpler.)

    {{- define "fluentd-config" -}}
    {{- $top := index . 0 -}}
    {{- $params := index . 1 -}}
    image: {{ $top.Values.fluentd.kinesis_image }}
    myname: {{ $params.replica }}
    pattern: {{ $params.pattern }}
    {{- end -}}
    
    {{- $params := dict "replica" "bbcc" "pattern" "aabb" -}}
    {{ template "fluentd-config" (list . $params) }}