Helm’s Horrible Hyphens of Hell
Honestly, I think that Helm is a terrible templating tool if you use it for anything complicated. One of the worst things in Helm charts looks like this: {{- and -}}.
Helm uses the Go templating engine. If you see a minus (hyphen) sign after the opening brackets, this means that the engine will “chomp” all the whitespace before the brackets, including a newline. If a hyphen appears before the closing brackets, all the whitespace after the brackets will get chomped too.
Let’s look at a simple example. If you place this snippet anywhere inside your Helm templates, both those expressions will turn into completely valid single-line comments:
# {{ "Hello," }}
{{- " world" }}
# {{ "Hello, " -}}
{{ "world" }}
In the first case, {{- at the beginning of the second expression will chomp the preceding newline and join the strings.
In the second case, -}} at the end of the first expression will chomp the following newline and join the strings.
# Hello, world
# Hello, world
Using hyphens is described as one of the “best practices” of formatting in the official documentation:
Templates should chomp whitespace where possible:
foo:
{{- range .Values.items }}
{{ . }}
{{ end -}}
Please, don’t follow this best practice blindly. Usually, the point of removing whitespace is to avoid having empty lines in the generated file. But empty lines are not as problematic as accidentally clumping together two different lines, which renders the whole template invalid.
Here’s an example of a section where we define environment variables for the Deployment. Based on some flag in values.yaml, we need to define either variable VAR1 or variable VAR2.
Try to find an issue with this simple snippet of code just by looking at it:
env:
{{- if .Values.myFlag -}}
- name: "VAR1"
value: "value1"
{{- else -}}
- name: "VAR2"
value: "value2"
{{- end -}}
image: "ubuntu"
Here’s the absolute mess it renders to. Rightfully so, because we’ve “chomped” the newline after env and before image:
env:- name: "VAR1"
value: "value1"image: "ubuntu"
We could easily fix this by removing the opening hyphen for if and the closing hyphen after end:
env:
{{ if .Values.myFlag -}}
- name: "VAR1"
value: "value1"
{{- else -}}
- name: "VAR2"
value: "value2"
{{- end }}
image: "ubuntu"
However, the real problem is, it’s very easy to make such a mistake, and it’s completely unclear how to consistently write Helm code to avoid it.
It’s not so bad when the error simply leads to yaml syntax failure, and the template just doesn’t get applied. But it’s not always so. Sometimes the yaml is completely correct, but it doesn’t work as you would expect. And that can cost you hours of investigation.
The takeaway: don’t use those hyphens of hell as a rule of thumb just to avoid newlines. Use them only if you absolutely need to.