Search code examples
gokubernetes-helmgo-templates

How to return a default false if a property dont exists in values.yaml file?


yaml file . i have a value as below defined under global

global:
  logging:
    log4j:
     enabled: true

I am also have a helper function

{{- define "helm-basic-template.logging-enabled" -}}
{{ .Values.global.logging.log4j.enabled | default "false" }}
{{- end -}}

it is possible the property global.logging.log4j.enabled may not exist , in that case i expect the helper function to return false, otherwise return the value of the property . however it is not working as i expected . any idea what is wrong with my function ? or any other better way to re write it ? thank you


Solution

  • To avoid variables being undefined, additional checks are needed here.

    According to the helm document, when the object is empty, the if statement judges to return false.

    A pipeline is evaluated as false if the value is:

    • a boolean false
    • a numeric zero
    • an empty string
    • a nil (empty or null)
    • an empty collection (map, slice, tuple, dict, array)

    Use the following checks directly.

    {{- if .Values.global }}
    {{- if .Values.global.logging }}
    {{- if .Values.global.logging.log4j }}
    {{- if .Values.global.logging.log4j.enabled }}
    apiVersion: v1
    kind: ConfigMap
    metadata:
      name: logging-cm
    data:
      conf.json: |
        xxxxx
    ...
    {{- end }}
    {{- end }}
    {{- end }}
    {{- end }}
    

    Or employ a named template approach.

    {{- define "helm-basic-template.logging-enabled" -}}
    {{- $val := false }}
    {{- if .Values.global -}}
    {{- if .Values.global.logging -}}
    {{- if .Values.global.logging.log4j -}}
    {{- if .Values.global.logging.log4j.enabled -}}
    {{- $val = true }}
    {{- end -}}
    {{- end -}}
    {{- end -}}
    {{- end -}}
    {{ $val }}
    {{- end -}}
    

    Or use default to set a simple default value.

    {{- define "helm-basic-template.logging-enabled" -}}
    {{- .Values.global.logging.log4j.enabled | default false .Values.global.logging.log4j.enabled -}}
    {{- end -}}
    

    Or use dig to select keys from a list of values.

    {{- define "helm-basic-template.logging-enabled" -}}
    {{- dig "logging" "log4j" "enabled" false .Values.global -}}
    {{- end -}}