Search code examples
kubernetes-helmgo-templates

Creating a "insert if exists" helper function in Helm


I'm creating a library chart that will be used across over a dozen different deployments. Each has only one container, and in the container description I have the following definitions in some but not in others:

spec:
  containers: 
    - image: hostname/imagename:versionNumber
      **imagePullPolicy: Always** # only some charts list this
      **ports:             
      - containerPort: xxxx** # also not in every yaml file

I've gotten it to work with this in the library chart, but to have to re-use multiple times seems not very DRY.

{{ if .Values.container }}
{{ if .Values.container.port }}
ports: {{ .Values.container.port }}
{{ end }}
{{ end }}

Is there an existing helm function that already has this functionality? If not, is there a way of writing a helper function, preferably 1 argument for clarity, that runs these if checks given the full path?


Solution

  • The absolute shortest path I can think of for this uses the dig template function to extract a version from a nested path, combined with the with block expression to assign its result to the . special variable.

    {{- with .Values | dig "container" "port" "" }}
    ports: {{ . }}
    {{- end }}
    

    If you're going to do multiple lookups in the same dictionary, another useful technique is to extract it into a variable, substituting an empty dictionary for a nil missing value.

    {{- $containers := .Values.containers | default dict }}
    {{- with $containers.port }}
    ports: {{ . }}
    {{- end }}
    

    This can be a little tricky to do in a helper function, since you need to marshal multiple arguments into a single parameter and then the helper can only return a string. Your invocation would look something like

    {{- with include "check-path" (list .Values "container" "port") }}
    ports: {{ . }}
    {{- end }}
    

    which doesn't seem better than the preceding options.