Skip to content
Tutorials Center
My learning

Topics

Lesson 13 of 38 ยท Templates and Values

Control Flow: if, with, range and Variables

Use if/else, with, range, variables, break and continue in Helm templates; learn Go truthiness rules, comparison functions and how $ and the dot change scope.

Static templates only get you so far. Real charts switch features on and off, loop over lists of hosts and environment variables, and narrow their scope to part of the values. Go templates provide if, with and range for this, plus variables to keep track of things. The rules about what counts as true and what the dot means inside a block are the source of most beginner confusion, so this lesson spends time on them.

if, else if and else

YAML
{{- if .Values.ingress.enabled }}
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: {{ include "webapp.fullname" . }}
{{- end }}

Every control structure ends with {{ end }}. You can chain alternatives:

YAML
{{- if eq .Values.service.type "NodePort" }}
nodePort: {{ .Values.service.nodePort }}
{{- else if eq .Values.service.type "LoadBalancer" }}
loadBalancerIP: {{ .Values.service.loadBalancerIP | quote }}
{{- else }}
# ClusterIP needs nothing extra
{{- end }}

What is true?

A pipeline is false when its value is one of: boolean false, the number 0, an empty string "", nil (missing or null), or an empty list or map. Everything else is true. Two consequences:

  • {{ if .Values.replicas }} is false when replicas: 0. To test "was it set at all" you need hasKey (see Functions and Pipelines).
  • An empty map {} is false, so {{ if .Values.resources }} renders the block only when the user supplied something. That is exactly how charts treat resources: {}.

The string "false" is true (non-empty). If a value arrives as text from --set-string, compare it explicitly.

Python Stand-in: Go template truthiness

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Comparison and logic functions

In Go templates operators are functions written first: eq .a .b, not .a == .b.

Function Meaning
eq a b equal; eq a b c means a equals b or c
ne, lt, le, gt, ge not equal, less, less or equal, greater, greater or equal
and a b first false argument, otherwise the last
or a b first true argument, otherwise the last
not a boolean negation
YAML
{{- if and .Values.ingress.enabled (not .Values.ingress.disabledForTests) }}
{{- if or (eq .Values.env "prod") (eq .Values.env "staging") }}
{{- if gt (int .Values.replicaCount) 1 }}

Parentheses group sub-expressions. Mixed types do not compare: eq .Values.port "80" fails when port is the number 80; use int, toString or quote to make types agree (the int64 problem appears when YAML numbers are read as floats, so eq (int .Values.port) 80 is the safe form).

with: narrow the scope

with sets the dot to a value and runs the block only if the value is true:

YAML
{{- with .Values.nodeSelector }}
nodeSelector:
  {{- toYaml . | nindent 2 }}
{{- end }}

Inside the block the dot is .Values.nodeSelector, so .Release.Name no longer works there. Use $ (the top-level context) to reach the outside:

YAML
{{- with .Values.image }}
image: {{ .repository }}:{{ .tag | default $.Chart.AppVersion }}
{{- end }}

with also supports else, which runs when the value is empty:

YAML
{{- with .Values.hostAliases }}
hostAliases: {{ toYaml . | nindent 2 }}
{{- else }}
# no aliases configured
{{- end }}

range: loops

range loops over a list, a map, or an integer in recent Go versions. Inside the loop the dot is the current item.

YAML
# list
{{- range .Values.ingress.hosts }}
- host: {{ .host | quote }}
{{- end }}

# map: key and value
{{- range $name, $value := .Values.env }}
- name: {{ $name }}
  value: {{ $value | quote }}
{{- end }}

# list with index
{{- range $i, $host := .Values.hosts }}
# host number {{ $i }} is {{ $host }}
{{- end }}

Maps are always visited in sorted key order, which makes the output deterministic; this is important because Helm compares manifests between revisions. Like with, an else branch runs when the collection is empty. You can stop early with {{ break }} or skip with {{ continue }} inside an if. To count, build a list with until: {{- range until 3 }}...{{- end }} repeats three times (dot = 0, 1, 2).

The next stand-in implements range over a map plus with and if behavior with the same rules, so you can try new data.

Python Stand-in: range, with and else

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Variables

A variable is declared with := inside an action and read with its name. Its scope is the block where it is declared:

YAML
{{- $fullname := include "webapp.fullname" . -}}
{{- $port := .Values.service.port -}}
apiVersion: v1
kind: Service
metadata:
  name: {{ $fullname }}
spec:
  ports:
    - port: {{ $port }}
      targetPort: http

Re-assign with = (not :=), which updates the variable from an outer scope:

YAML
{{- $total := 0 -}}
{{- range .Values.disks }}
  {{- $total = add $total .sizeGb }}
{{- end }}
totalGb: {{ $total }}

Use variables to save the top-level context before entering a loop: {{- $root := . -}} (or just $), then refer to $root.Release.Name inside range. This one habit avoids the infamous "nil pointer evaluating interface" errors after a range or with.

flowchart TB
  A["Top level: dot = everything"] --> B["with .Values.image"]
  B --> C["Inside: dot = the image map"]
  C --> D["Use $ to reach .Release and .Chart"]
  A --> E["range .Values.hosts"]
  E --> F["Inside: dot = one host"]
  F --> D

with and range replace the dot. $ always keeps the top-level context.

Common mistakes

  1. Forgetting end: the error is unexpected EOF. Count your if/with/range against ends.
  2. Losing the dot: using .Values or .Release inside range or with. Use $.Values.
  3. Trimming too much: -}} on an if line can pull the next line's content onto the same line. Prefer {{- if ... }} (left trim only).
  4. Comparing mismatched types: eq .Values.port "80" errors with incompatible types for comparison.
  5. Testing zero: if .Values.replicas is false for 0 (and hasKey tells you whether it was set).

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which values are false in a Go template condition?

    All of false, 0, "", nil, empty list and empty map are false; the string "false" is true.
  2. 2. Inside {{- with .Values.image }}, how do you access .Release.Name?

    $ is the top-level context, unaffected by with or range.
  3. 3. In which order does range visit a map?

    Go sorts map keys when ranging, which keeps rendered output stable.
  4. 4. How do you write the test 'service.type equals NodePort'?

    Operators are functions: eq a b.
  5. 5. What does := do versus =?

    Declare with :=, update an outer variable with =.

Summary

  • if, else if, else, with and range all close with end; false means false, 0, empty string, nil or an empty collection.
  • Comparisons are functions (eq, ne, lt, and, or, not) and types must match.
  • with and range rebind the dot; use $ for the top-level context.
  • Maps are ranged in sorted key order; else handles empty collections; break and continue exist.
  • Variables use := to declare and = to update.

Next: Named Templates and _helpers.tpl