Sub topic 8
Conditionals and loops: if, with, range
This chapter assumes you can read a basic chart layout, know that .Values holds your settings, and have used pipelines such as default and quote. You also need the whitespace trimming markers {{- and -}} from the previous chapter, because every block action below leaves blank lines unless you trim them.
What counts as false
if, with and range all test a value for emptiness. Go templates treat these as false: false, 0, an empty string, nil, and an empty list or map. Everything else is true.
if and else
Use if to include text only under a condition. Combine it with comparison functions such as eq, ne, lt and and/or. These are prefix functions, so the operator comes first.
{{- if eq .Values.service.type "NodePort" }}
type: NodePort
{{- else if eq .Values.service.type "LoadBalancer" }}
type: LoadBalancer
{{- else }}
type: ClusterIP
{{- end }}with
with is an if that also rebinds the dot (.) to the tested value. Inside the block, . is no longer the root context. This shortens deep paths, but it hides .Chart, .Release and .Values.
{{- with .Values.image }}
image: "{{ .repository }}:{{ .tag | default $.Chart.AppVersion }}"
{{- end }}The $ variable always points to the root context, so $.Chart.AppVersion still works inside the block.
range
range repeats its body for each item in a list or map. Like with, it rebinds the dot to the current item. Suppose values.yaml contains this list:
extraPorts:
- name: metrics
containerPort: 9090
- name: admin
containerPort: 9100The template loops over it:
ports:
{{- range .Values.extraPorts }}
- name: {{ .name }}
containerPort: {{ .containerPort }}
{{- end }}To loop over a map, declare variables for the key and value. Helm visits map keys in sorted order, so output is stable between renders.
{{- range $key, $value := .Values.env }}
- name: {{ $key | quote }}
value: {{ $value | quote }}
{{- end }}You can add an else branch to range. It runs when the collection is empty.
Common errors
- Lost context. Inside
withorrange,.Release.Namefails because dot is now the item. Write$.Release.Name. - Zero is false.
{{ if .Values.replicaCount }}skips the block when the value is0. TesthasKeyor compare witheqif zero is a valid setting. - Wrong comparison types.
eq .Values.port "80"fails or misleads when the value is an integer. Quote strings and leave numbers bare. - Stray blank lines or bad indentation. A missing
{{-leaves an empty line, and a list item at the wrong indent breaks the YAML. Runhelm templateafter each change.
Exercise
A template contains {{- range .Values.hosts }} and, inside it, the line name: {{ .Release.Name }}-{{ . }}. Rendering fails. What is wrong, and how do you fix it?
Show answer
Inside range, dot is the current item (a string from hosts), so .Release does not exist. Use the root variable: name: {{ $.Release.Name }}-{{ . }}.