Search code examples
yamlkubernetes-helm

How to range optional array on Helm


Consider the following template:

...
    {{- range .Values.additionalMetrics }}
    - interval: 1m
      port: {{ .name }}
    {{- end }}
...

And the following values:

additionalMetrics:
  - name: kamon-metrics
    port: 9096
    targetPort: 9096

If additionalMetrics is missing, the helm template will fail.

Is it possible to check first if additionalMetrics is defined, and then the range the values or continue otherwise?

Note: without making first if and then range, but in one condition, for example this is a not my desired solution:

    {{- if .Values.additionalMetrics }}
    {{- range .Values.additionalMetrics }}
    - name:       {{ .name }}
      port:       {{ .port }}
      targetPort: {{ .targetPort }}
    {{- end }}
    {{- end }}

Thanks in advvance


Solution

  • The solution, which is not desired by you, is alright imo. It's simple and does what it's supposed to do. There is no need to make things complicated.

    You could make it a bit more pretty with a with clause:

    {{- with .Values.additionalMetrics }}
    {{- range . }}
    - name:       {{ .name }}
      port:       {{ .port }}
      targetPort: {{ .targetPort }}
    {{- end }}
    {{- end }}
    

    If you really want to do it in a single statement, you could use as default an empty list:

    {{- range .Values.additionalMetrics | default list }}
    - name:       {{ .name }}
      port:       {{ .port }}
      targetPort: {{ .targetPort }}
    {{- end }}