Search code examples
kubernetes-helm

If condition checking value returned by helm template


I have a parent chart with 2 subcharts. The parent chart has global.myflag while the subcharts have myflag fields, in their respective values.yaml. I want the flexibility, where the sub-charts could be deployed independently. So, I have added a template function in the sub-chart _helper.tpl where I want to check - if global.myflag exists, use that value - else use value of myflag from the subchart

The template will return true/false. Something like this -

{{- define "isFlagEnabled" -}}
{{- $flag := false -}}
{{- if .Values.myflag -}}
{{- $flag := .Values.myflag -}}
{{- end -}}
{{- if .Values.global.myflag -}}
{{- $flag := .Values.global.myflag -}}
{{- end -}}
{{- printf "%s" $flag -}}
{{- end -}}

And using this value (true/false), I want to set some values in my config.yaml.

{{- if eq (value from template) true -}}

I am having two questions here - 1. Can we do 'if' condition on the template values? How? 2. Is there a better way to do this?


Solution

  • Definition of isFlagEnabled template

    Retouched and cleaned your function

    {{- define "isFlagEnabled" -}}
    {{- if .Values.global -}} {{/* <-- check parent exists to avoid nil pointer evaluating interface {}.myflag */}}
    {{- if .Values.global.myflag -}}
    {{- .Values.global.myflag -}}
    {{- end -}}
    {{- else if .Values.myflag -}} {{/* <-- make sure its else if so you wont override if both defined */}}
    {{- .Values.myflag -}}
    {{- else -}}
    {{- printf "false" }}
    {{- end -}}
    {{- end -}}
    

    Using the template

    Inside another template

    When using template inside golang template syntax, you will need to escape them with round brackets:

    {{- define "flagUsage" -}}
    {{- if eq (include "isFlagEnabled" .) "true" -}}
    {{- printf "%s" (include "isFlagEnabled" .) -}}
    {{- end -}}
    {{- end -}}
    

    another example used inside a resource

    Pay attention the template is being used twice in the example, once as an operand for the if operator and one as text for the label

    {{- if eq (include "isFlagEnabled" .) "true" -}} {{/* <--- operand used in spring function surrounded by `{{ }}` */}}
    apiVersion: v1
    kind: Service
    metadata:
        name: {{ include "my-chart.fullname" . }}
        labels:
            my-meta-label: {{ include "isFlagEnabled" . }} {{/* <---- plain text */}}
    spec:
        type: {{ .Values.service.type }}
        ports:
            - port: {{ .Values.service.port }}
            targetPort: http
            protocol: TCP
            name: http
        selector:
            {{- include "my-chart.selectorLabels" . | nindent 4 }}
    {{- end }}