TExcelTAD
Home › Kubernetes Packaging: Helm & Kustomize › Flow Control & Scope

Flow Control & Scope

Templates need decisions ("create the HPA only if autoscaling is on") and loops ("one env var per entry"). Go templates provide if, with and range, plus variables. The subtle part is scope: with and range change what the dot means.

if / else if / else

A condition is false when it is empty: false, 0, "", nil, an empty list or map. Comparisons are functions written before their arguments: eq a b, ne, lt, gt, le, ge, and the logic functions and, or, not.

bash · try it yourself
mkdir -p linkly/templates && cd linkly
printf 'apiVersion: v2\nname: linkly\nversion: 0.1.0\n' > Chart.yaml
cat > values.yaml <<'EOF'
replicaCount: 2
autoscaling:
  enabled: false
  minReplicas: 2
  maxReplicas: 10
  targetCPU: 70
EOF
cat > templates/hpa.yaml <<'EOF'
{{- if .Values.autoscaling.enabled }}
{{- if gt (int .Values.autoscaling.minReplicas) (int .Values.autoscaling.maxReplicas) }}
{{- fail "autoscaling.minReplicas must not exceed autoscaling.maxReplicas" }}
{{- end }}
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
  name: {{ .Release.Name }}
spec:
  scaleTargetRef: {apiVersion: apps/v1, kind: Deployment, name: {{ .Release.Name }}}
  minReplicas: {{ .Values.autoscaling.minReplicas }}
  maxReplicas: {{ .Values.autoscaling.maxReplicas }}
  metrics:
    - type: Resource
      resource:
        name: cpu
        target: {type: Utilization, averageUtilization: {{ .Values.autoscaling.targetCPU }}}
{{- end }}
EOF
cat > templates/replicas.yaml <<'EOF'
apiVersion: v1
kind: ConfigMap
metadata:
  name: {{ .Release.Name }}-scaling
data:
{{- if .Values.autoscaling.enabled }}
  mode: "hpa {{ .Values.autoscaling.minReplicas }}-{{ .Values.autoscaling.maxReplicas }}"
{{- else if eq (int .Values.replicaCount) 1 }}
  mode: "single replica (no high availability)"
{{- else }}
  mode: "fixed {{ .Values.replicaCount }}"
{{- end }}
EOF
helm template demo . | grep -E '^kind|mode'
helm template demo . --set replicaCount=1 | grep mode
helm template demo . --set autoscaling.enabled=true | grep -E '^kind|mode'
helm template demo . --set autoscaling.enabled=true --set autoscaling.minReplicas=20
kind: ConfigMap
  mode: "fixed 2"
  mode: "single replica (no high availability)"
kind: ConfigMap
  mode: "hpa 2-10"
kind: HorizontalPodAutoscaler
Error: execution error at (linkly/templates/hpa.yaml:3:4): autoscaling.minReplicas must not exceed autoscaling.maxReplicas

Use --debug flag to render out invalid YAML

fail stops rendering with your message, so a bad combination of values is caught at helm template/install time instead of producing a broken object. Note the int conversions: --set passes numbers as int64 while values files give float64, and gt refuses to compare different types.

Note: When a template file renders to nothing (HPA disabled), Helm simply skips it. The Deployment must then omit replicas when autoscaling is on, or every helm upgrade will reset the replica count the HPA chose: {{- if not .Values.autoscaling.enabled }} replicas: … {{- end }}.

with: a scoped shortcut

with X runs its body only if X is non-empty and sets the dot to X inside it. That's handy for optional blocks, and it's where scope bites: inside with, .Release means X.Release, which doesn't exist. The root context is always available as $:

bash · try it yourself
mkdir -p c/templates && cd c
printf 'apiVersion: v2\nname: c\nversion: 0.1.0\n' > Chart.yaml
printf 'route:\n  host: lnk.example.com\n' > values.yaml
cat > templates/broken.yaml <<'EOF'
{{- with .Values.route }}
host: {{ .host }}
service: {{ .Release.Name }}
{{- end }}
EOF
helm template demo . 2>&1 | head -3
sed -i 's/{{ .Release.Name }}/{{ $.Release.Name }}/' templates/broken.yaml
helm template demo .
Error: c/templates/broken.yaml:3:20
  executing "c/templates/broken.yaml" at <.Release.Name>:
    nil pointer evaluating interface {}.Name
---
# Source: c/templates/broken.yaml
host: lnk.example.com
service: demo

nil pointer evaluating interface {}.Name is the message you will see for any path that leads through a missing key: here .Release didn't exist on the route map, so .Release.Name dereferenced nothing. The position 3:20 (line 3, column 20) points at the action. Replacing .Release with $.Release fixed it.

range: loops over lists and maps

range sets the dot to each element. Over a map, range $key, $value := .Values.env gives both, in sorted key order, which keeps rendering deterministic. Over a list, range $i, $item := … gives the index.

bash · try it yourself
mkdir -p linkly/templates && cd linkly
printf 'apiVersion: v2\nname: linkly\nversion: 0.1.0\n' > Chart.yaml
cat > values.yaml <<'EOF'
env:
  REDIS_ADDR: linkly-redis:6379
  LOG_LEVEL: info
  BASE_URL: https://lnk.example.com
  FEATURE_QR: true
hosts:
  - lnk.example.com
  - go.example.com
EOF
cat > templates/env.yaml <<'EOF'
env:
{{- range $name, $value := .Values.env }}
  - name: {{ $name }}
    value: {{ $value | quote }}
{{- end }}
hostnames:
{{- range $i, $host := .Values.hosts }}
  - {{ $host | quote }}  # {{ $i }} of {{ len $.Values.hosts }}
{{- end }}
EOF
helm template demo .
---
# Source: linkly/templates/env.yaml
env:
  - name: BASE_URL
    value: "https://lnk.example.com"
  - name: FEATURE_QR
    value: "true"
  - name: LOG_LEVEL
    value: "info"
  - name: REDIS_ADDR
    value: "linkly-redis:6379"
hostnames:
  - "lnk.example.com"  # 0 of 2
  - "go.example.com"  # 1 of 2

quote matters again: without it FEATURE_QR would render as the YAML boolean true, and Kubernetes rejects a non-string env value. Exposing env vars as a map (env: {NAME: value}) rather than a list also makes them easy to override per environment, because maps merge and lists are replaced (see Values Files & Overrides).

Variables

{{ $name := expr }} defines a variable, {{ $name = expr }} reassigns it. Variables are scoped to the block that defines them (if, with, range, define). Common uses:

  • capture something before a with/range changes the dot: {{- $fullName := include "linkly.fullname" . }};
  • the root: $ is predefined and always refers to the top-level context.

Test yourself

Inside {{ range .Values.hosts }}, how do you read the release name?

  1. .Release.Name
  2. $.Release.Name
  3. ..Release.Name
  4. root.Release.Name

Which values are false in an if?

  1. Only false
  2. false and nil
  3. false, 0, empty string, nil, empty list or map
  4. Only nil

In which order does range $k, $v := .Values.env visit a map?

  1. Insertion order
  2. Random
  3. Sorted by key
  4. Reverse