How to use if/else loop in Helm

6/7/2021

I am trying to use if/else-if/else loop in helm chart. Basically, I want to add ENV configs in configfile based on the if/else condition. Below is the logic:

apiVersion: v1
kind: ConfigMap
metadata:
  name: {{ .Values.applicationName }}-configmap
  labels:
    projectName: {{ .Values.applicationName }}
    environment: {{ .Values.environment }}
    type: configmap
data:
{{- if eq .Values.environment "production" }}
{{ .Files.Get "config-prod.yaml" | nindent 2}}
{{- else if eq .Values.environment "development" }}
{{ .Files.Get "config-dev.yaml" | nindent 2}}
{{- else }}
{{ .Files.Get "config-stage.yaml" | nindent 2}}
{{- end }}

But I am not getting the desired output and facing some issue. Can anybody help me out with this?

Edit1: I have added my modified configmap.yaml as per the suggestions, helm install/template command gives Error: YAML parse error on demo2/templates/configmap.yaml: error converting YAML to JSON: yaml: line 14: did not find expected keyerror.

also my config-prod and config-stage is being rendered (as per the condition if I give environment: production then config-prod.yaml is being added and if I give environment: stage/null then config-stage.yaml is being added.

-- dharmendra kariya
kubernetes
kubernetes-helm

2 Answers

6/8/2021

Sorry guys, it was my mistake, my dev-config.yaml has envs and it was defined like key=value, instead of key: value.

-- dharmendra kariya
Source: StackOverflow

6/7/2021

Your question would benefit from more specifics.

Please consider adding the following to your question:

  • How are you trying this? What commands exactly did you run?
  • How are you "not getting the desired output"? What output did you get?

Please also include:

  • the relevant entries from your values.yaml
  • the config-dev.yaml and config-stage.yaml files

Have you run helm template to generate the templates that Helm would apply to your cluster? This would be a good way to diagnose the issue.

I wonder whether you're chomping too much whitespace.

And you should just chomp left, i.e. {{- .... }} rather than left+right {{- ... -}}.

-- DazWilkin
Source: StackOverflow