Passing dictionary from one template to another in Helm

8/16/2019

I'm trying to pass a dictionary from one helm template to another but it's resolved to null inside the called template.

Calling template - deployment.yaml
Called template - storageNodeAffinity

I see myDict printed as map inside deployment.yaml but inside storageNodeAffinity it's printed as null.

Eventually I need to pass nodeAffn from the values file.

deployment.yaml

{{- $myDict := dict "cpu" "amd" }}
{{- include "storageNodeAffinity" $myDict | indent 6 }}
{{printf "%q" $myDict}}

storage-affinity.tpl

{{- define "storageNodeAffinity" }}
{{/*        {{- $myDict := dict "cpu" "amd" }}*/}}
 {{printf "%q" .myDict}}
        {{- range $key, $val := .myDict }}
        - key: {{ $key }}
          operator: In
          values:
          - {{ $val }}
        {{- end }}
{{- end }}

values.yaml

nodeAffn:
  disktype: "ssd"
  cpu:  intel
-- user5857902
go-templates
kubernetes-helm

2 Answers

8/16/2019

I figured it out. The trick is to pass context of the parent variable for the variable you want to use in the called template. So here I'm passing "csAffn" as context and then using "nodeAffn" inside this context, in the called template (_additionalNodeAffinity)

_additionalNodeAffinity.tpl
    {{- define "additionalNodeAffinity" }}
            {{- range $key, $val := .nodeAffn }}
            - key: {{ $key }}
              operator: In
              values:
              - {{ $val }}
            {{- end }}
    {{- end }}

deployment.yaml
    {{- include "additionalNodeAffinity" ( .Values.csAffn )

values.yaml
    csAffn:
      nodeAffn:
        disktype: "ssd"
        cpu: "intel"
-- user5857902
Source: StackOverflow

8/18/2019

When you call a template

{{- include "storageNodeAffinity" $myDict -}}

then within the template whatever you pass as the parameter becomes the special variable .. That is, . is the dictionary itself; you don't need to use a relative path to find its values.

{{- define "storageNodeAffinity" }}
{{/* ., not .myDict */}}
{{printf "%q" .}}
{{- range $key, $val := . }}...{{ end -}}
{{- end -}}
-- David Maze
Source: StackOverflow