Skip to content
Hands-on IT IT Drills

Day 5: Whitespace, Control Structures and Scope

Goal: Write templates that produce clean YAML – with {{-, nindent, if, with and range – plus an optional Ingress with several hosts through Traefik. · Duration: approx. 75 min · Prerequisite: Day 4

Briefing

  • An action leaves its line behind, even when it prints nothing. {{- eats the whitespace on the left including the line break, -}} the whitespace on the right.
  • False values are false, 0, "", null and empty lists or maps. That includes a 0 you set on purpose.
  • with and range move the dot. You always get back to the root with $.
  • Today notes grows to 0.4.0: resources, an optional team label, a nodeSelector and an Ingress that prod.yaml switches on.
 curl -H 'Host: notes.lab' localhost ──> Traefik :80 ──> Ingress notes-api
                                                          ├─ notes.lab
                                                          └─ api.notes.lab ──> svc :80

Drill 1: Make blank lines visible

As on Day 4, you work in a playground template (spielwiese.yaml) that disappears again at the end. cat -A shows every line ending as $.

# on prod
mkdir -p ~/helm/tag05 && cd ~/helm/charts
cat > notes/templates/spielwiese.yaml <<'EOF'
apiVersion: v1
kind: ConfigMap
metadata:
  name: ws
  labels:
    app: notes
    {{ if .Values.team }}
    team: {{ .Values.team }}
    {{ end }}
data:
  x: "1"
EOF
helm template notes ./notes -s templates/spielwiese.yaml --set team=plattform \
  | cat -A | sed -n '8,12p'

Expected:

    app: notes$
    $
    team: plattform$
    $
data:$

The lines with if and end stay behind as blank lines with four spaces. The YAML is still valid, but messy – and inside lists or blocks it breaks. With a minus on the left they disappear:

# on prod
sed -i 's/{{ if/{{- if/; s/{{ end/{{- end/' notes/templates/spielwiese.yaml
helm template notes ./notes -s templates/spielwiese.yaml --set team=plattform \
  | sed -n '8,11p'
helm template notes ./notes -s templates/spielwiese.yaml | sed -n '8,10p'

Expected:

    app: notes
    team: plattform
data:
  x: "1"
    app: notes
data:
  x: "1"

{{- eats the line break before the action and the indentation in front of it. What remains is exactly the line you want to see.

Save your progress? Sign up for free

Drill 2: One minus too many

# on prod
cat > notes/templates/spielwiese.yaml <<'EOF'
apiVersion: v1
kind: ConfigMap
metadata:
  name: ws
  labels:
    app: {{- .Chart.Name -}}
    tier: backend
data:
  x: "1"
EOF
helm template notes ./notes -s templates/spielwiese.yaml | sed -n '7,9p'

Expected:

  labels:
    app:notestier: backend
data:

The left minus eats the space after app:, the right one the line break before tier. The result is a single label with the key app:notestier – valid YAML, so helm template reports no error. Only the API rejects the label name. Put a minus on the right only if you really want to glue the next line on.

Save your progress? Sign up for free

Drill 3: Blocks with toYaml and nindent

You pass whole structures such as resources through with toYaml. The Deployment gets resources, an optional team label and an optional nodeSelector:

# on prod
cat > notes/templates/deployment.yaml <<'EOF'
{{/* notes/templates/deployment.yaml – Stand Tag 05 */}}
apiVersion: apps/v1
kind: Deployment
metadata:
  name: notes-api
  labels:
    app.kubernetes.io/name: notes-api
    {{- with .Values.team }}
    team: {{ . | quote }}
    {{- end }}
spec:
  replicas: {{ hasKey .Values "replicaCount" | ternary .Values.replicaCount 2 }}
  selector:
    matchLabels: {app.kubernetes.io/name: notes-api}
  template:
    metadata:
      labels:
        app.kubernetes.io/name: notes-api
        {{- with .Values.team }}
        team: {{ . | quote }}
        {{- end }}
    spec:
      containers:
        - name: notes-api
          image: "{{ .Values.image.repository }}:{{ .Values.image.tag }}"
          ports: [{name: http, containerPort: 8080}]
          env:
            - name: NOTES_API_KEY
              value: {{ .Values.apiKey | quote }}
            {{- range $name, $value := .Values.env }}
            - name: {{ $name }}
              value: {{ $value | quote }}
            {{- end }}
          readinessProbe:
            httpGet: {path: /healthz, port: http}
          resources:
            {{- toYaml .Values.resources | nindent 12 }}
      {{- with .Values.nodeSelector }}
      nodeSelector:
        {{- toYaml . | nindent 8 }}
      {{- end }}
EOF
cat > notes/values.yaml <<'EOF'
# notes/values.yaml – Stand Tag 05

# -- Anzahl der notes-api-Pods (0 ist erlaubt, null = Standard 2)
replicaCount: 2

image:
  # -- Image ohne Tag
  repository: ghcr.io/thomaszachmann/notes-api
  # -- Tag des Images
  tag: "0.7.1"

# -- API-Key (nur Labor! Ab Tag 8 aus einem Secret)
apiKey: lab-key-123

# -- Zusätzliche Umgebungsvariablen: Name -> Wert (Map, damit -f ergänzen kann)
env:
  NOTES_LOG_LEVEL: info
  NOTES_PAGE_SIZE: "50"

# -- Team-Label an Deployment und Pods (leer = kein Label)
team: ""

# -- Ressourcen des Containers
resources:
  requests:
    cpu: 20m
    memory: 32Mi
  limits:
    memory: 128Mi

# -- nodeSelector der Pods (leer = keiner)
nodeSelector: {}

service:
  # -- Port des Service
  port: 80

ingress:
  # -- Ingress anlegen
  enabled: false
  # -- IngressClass (k3s: traefik)
  className: traefik
  # -- Hostnamen, alle zeigen auf notes-api
  hosts: []
EOF
sed -i 's/^version: .*/version: 0.4.0/; s/Tag 04/Tag 05/' notes/Chart.yaml
helm template notes ./notes -s templates/deployment.yaml | grep -A5 'resources:'

The new # -- comments in values.yaml document the new keys: team is the team label on Deployment and Pods (empty = no label), resources the container resources, nodeSelector the Pods’ nodeSelector (empty = none), and under ingress you find the switch to create an Ingress, the IngressClass and the hostnames, all pointing to notes-api.

Expected:

          resources:
            limits:
              memory: 128Mi
            requests:
              cpu: 20m
              memory: 32Mi

nindent 12 starts with a line break and indents every line by 12 spaces. The number is the indentation of the block in the target file. Compare with indent:

# on prod
cp notes/templates/deployment.yaml ~/helm/tag05/deployment.bak
sed -i '/resources | nindent/s/{{- \(.*\) nindent/{{ \1 indent/' \
  notes/templates/deployment.yaml
grep 'indent 12' notes/templates/deployment.yaml
helm template notes ./notes -s templates/deployment.yaml --debug 2>&1 \
  | grep -A3 'resources:'
cp ~/helm/tag05/deployment.bak notes/templates/deployment.yaml

Expected:

            {{ toYaml .Values.resources | indent 12 }}
          resources:
                        limits:
              memory: 128Mi
            requests:

indent also indents the first line – on top of the spaces that already stand before the action. With nindent and {{- the action sits readably aligned in the template, and the result starts cleanly on a new line.

Save your progress? Sign up for free

Drill 4: When 0 is false

replicaCount: 0 is a legitimate choice, for example during maintenance. default sees it differently:

# on prod
cat > notes/templates/spielwiese.yaml <<'EOF'
apiVersion: v1
kind: ConfigMap
metadata:
  name: ws
data:
  mitDefault: {{ .Values.replicaCount | default 2 | quote }}
  hasKey: {{ hasKey .Values "replicaCount" | ternary .Values.replicaCount 2 | quote }}
  art: {{ kindOf .Values.replicaCount | quote }}
  istNull: {{ kindIs "invalid" .Values.replicaCount | quote }}
EOF
for s in replicaCount=0 replicaCount=null; do echo "== $s"
  helm template notes ./notes -s templates/spielwiese.yaml --set $s | tail -5; done

The keys are German: mitDefault (‘with default’), art (‘kind’) and istNull (‘is null’).

Expected:

== replicaCount=0
  mitDefault: "2"
  hasKey: "0"
  art: "int64"
  istNull: "false"
== replicaCount=null
  mitDefault: "2"
  hasKey: "2"
  art: "invalid"
  istNull: "true"

default replaces every false value, so 0 as well. hasKey asks whether the key exists – null deleted it on Day 3, a 0 does not. kindIs "invalid" detects null. That is why the Deployment from Drill 3 uses hasKey … | ternary.

# on prod
helm template notes ./notes -s templates/deployment.yaml --set replicaCount=0 \
  | yq .spec.replicas

Expected: 0

Save your progress? Sign up for free

Drill 5: if, and, eq and with

with checks for empty and sets the dot to the value. That is the clean form for optional blocks such as the team label and the nodeSelector:

# on prod
helm template notes ./notes -s templates/deployment.yaml --set team=plattform \
  --set 'nodeSelector.kubernetes\.io/hostname=prod' | grep -E -A1 'team|nodeSelector'

Expected:

    team: "plattform"
spec:
--
        team: "plattform"
    spec:
--
      nodeSelector:
        kubernetes.io/hostname: prod

The dot in the key needs a backslash with --set. Without values, neither the label nor nodeSelector: appears – no empty keys to confuse Kubernetes. Comparisons are functions and come first: eq, ne, lt, gt, and, or, not. You need them in a moment for the Ingress.

Save your progress? Sign up for free

Drill 6: range, $ and variables

# on prod
cat > notes/templates/spielwiese.yaml <<'EOF'
{{- $mitGleich := 0 }}
{{- $mitDoppelpunkt := 0 }}
{{- range .Values.ingress.hosts }}
{{- $mitGleich = add1 $mitGleich }}
{{- $mitDoppelpunkt := add1 $mitDoppelpunkt }}
{{- end }}
apiVersion: v1
kind: ConfigMap
metadata:
  name: ws
data:
  mitGleich: {{ $mitGleich | quote }}
  mitDoppelpunkt: {{ $mitDoppelpunkt | quote }}
  {{- range $i, $h := .Values.ingress.hosts }}
  host{{ $i }}: {{ $h }}.{{ $.Release.Namespace }}
  {{- end }}
  {{- range .Values.ingress.hosts }}
  ohneDollar: {{ . }}.{{ .Release.Namespace }}
  {{- end }}
EOF
helm template notes ./notes -s templates/spielwiese.yaml -n notes \
  --set 'ingress.hosts={notes.lab,api.notes.lab,www.notes.lab}'

$mitGleich means ‘with equals sign’, $mitDoppelpunkt ‘with colon’, and ohneDollar ‘without dollar’.

Expected:

Error: notes/templates/spielwiese.yaml:18:33
  executing "notes/templates/spielwiese.yaml" at <.Release.Namespace>:
    can't evaluate field Release in type interface {}

Inside range the dot is the current host, a string. A string has no .Release. You delete the last three lines (the second loop) and render again:

# on prod
head -n -3 notes/templates/spielwiese.yaml > ~/helm/tag05/sw.yaml
mv ~/helm/tag05/sw.yaml notes/templates/spielwiese.yaml
tail -3 notes/templates/spielwiese.yaml
helm template notes ./notes -s templates/spielwiese.yaml -n notes \
  --set 'ingress.hosts={notes.lab,api.notes.lab,www.notes.lab}' | sed -n '7,$p'

Expected:

  {{- range $i, $h := .Values.ingress.hosts }}
  host{{ $i }}: {{ $h }}.{{ $.Release.Namespace }}
  {{- end }}
data:
  mitGleich: "3"
  mitDoppelpunkt: "0"
  host0: notes.lab.notes
  host1: api.notes.lab.notes
  host2: www.notes.lab.notes

$ always points to the root. range $i, $h := … gives index and element their own names. := declares a variable, = assigns a new value: the := inside the loop creates a new, local variable on every pass – the outer one stays 0.

Save your progress? Sign up for free

Drill 7: An optional Ingress

An Ingress is only created when it is switched on and has hosts. For Traefik an annotation is added.

# on prod
rm notes/templates/spielwiese.yaml
cat > notes/templates/ingress.yaml <<'EOF'
{{/* notes/templates/ingress.yaml – Stand Tag 05 */}}
{{- if and .Values.ingress.enabled .Values.ingress.hosts }}
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: notes-api
  {{- if eq .Values.ingress.className "traefik" }}
  annotations:
    traefik.ingress.kubernetes.io/router.entrypoints: web
  {{- end }}
spec:
  {{- with .Values.ingress.className }}
  ingressClassName: {{ . }}
  {{- end }}
  rules:
    {{- range .Values.ingress.hosts }}
    - host: {{ . | quote }}
      http:
        paths:
          - path: /
            pathType: Prefix
            backend:
              service:
                name: notes-api
                port:
                  number: {{ $.Values.service.port }}
    {{- end }}
{{- end }}
EOF
helm template notes ./notes -s templates/ingress.yaml --set ingress.enabled=true
cat > values/prod.yaml <<'EOF'
# values/prod.yaml – Stand Tag 05
replicaCount: 2
team: plattform
env:
  NOTES_LOG_LEVEL: warn
ingress:
  enabled: true
  hosts:
    - notes.lab
    - api.notes.lab
EOF
helm upgrade notes ./notes -n notes -f values/prod.yaml --wait | grep REVISION
kubectl -n notes get ingress

Expected:

Error: could not find template templates/ingress.yaml in chart
REVISION: 13
NAME        CLASS     HOSTS                     ADDRESS        PORTS   AGE
notes-api   traefik   notes.lab,api.notes.lab   172.16.0.123   80      5s

Without hosts the file renders empty – you know the message from Day 1. Traefik listens on port 80 of the VM through the k3s ServiceLB. You pass the hostname as a header:

# on prod
curl -s -H 'Host: notes.lab' localhost/healthz
curl -s -H 'Host: api.notes.lab' 172.16.0.123/version; echo
curl -s -o /dev/null -w '%{http_code}\n' -H 'Host: falsch.lab' localhost/healthz

Expected:

ok
0.7.1
404

Save your progress? Sign up for free

Exercise: Speed Drills

  1. Render the Deployment with team web and show only the labels. Target time: 30 s
  2. Show all hosts of the Ingress in the cluster on one line. Target time: 30 s
  3. Render the Deployment for arm64 nodes and show the nodeSelector. Target time: 45 s
  4. Show the team label and memory limit of the running Deployment. Target time: 45 s

Solution

# on prod
helm template notes ./notes -s templates/deployment.yaml --set team=web \
  | yq .metadata.labels
kubectl -n notes get ingress notes-api -o jsonpath='{.spec.rules[*].host}{"\n"}'
helm template notes ./notes -s templates/deployment.yaml \
  --set 'nodeSelector.kubernetes\.io/arch=arm64' | yq .spec.template.spec.nodeSelector
kubectl -n notes get deploy notes-api -o yaml \
  | yq '.metadata.labels.team,
  .spec.template.spec.containers[0].resources.limits.memory'

Expected:

app.kubernetes.io/name: notes-api
team: "web"
notes.lab api.notes.lab
kubernetes.io/arch: arm64
plattform
128Mi

Save your progress? Sign up for free

Checkpoint

# on prod
helm list -n notes

Expected: Revision 13, notes-0.4.0, deployed.

# on prod
curl -s -H 'Host: notes.lab' localhost/healthz

Expected: ok

# on prod
ls notes/templates

Expected: NOTES.txt configmap.yaml deployment.yaml ingress.yaml service.yaml

Challenge

A host should optionally get its own paths: an entry in ingress.hosts is either a string (path /) or a map with name and paths. Try it live in a copy of the chart with tag05.lab and api.tag05.lab (only /notes and /healthz).

Hint: kindIs "map" . tells the two forms apart, list "/" is the default.

Solution

# on prod
cd ~/helm/tag05
cp -r ~/helm/charts/notes .
cat > notes/templates/ingress.yaml <<'EOF'
{{/* notes/templates/ingress.yaml – Challenge Tag 05 */}}
{{- if and .Values.ingress.enabled .Values.ingress.hosts }}
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: notes-api
spec:
  {{- with .Values.ingress.className }}
  ingressClassName: {{ . }}
  {{- end }}
  rules:
    {{- range .Values.ingress.hosts }}
    {{- $host := . }}
    {{- $paths := list "/" }}
    {{- if kindIs "map" . }}
    {{- $host = .name }}
    {{- $paths = .paths }}
    {{- end }}
    - host: {{ $host | quote }}
      http:
        paths:
          {{- range $paths }}
          - path: {{ . }}
            pathType: Prefix
            backend:
              service:
                name: notes-api
                port:
                  number: {{ $.Values.service.port }}
          {{- end }}
    {{- end }}
{{- end }}
EOF
cat > hosts.yaml <<'EOF'
ingress:
  enabled: true
  hosts:
    - tag05.lab
    - name: api.tag05.lab
      paths: [/notes, /healthz]
EOF
helm template notes ./notes -s templates/ingress.yaml -f hosts.yaml \
  | yq -o json -I0 '[.spec.rules[] | {"h": .host, "p": [.http.paths[].path]}]'
helm install challenge ./notes -n tag05 --create-namespace -f hosts.yaml \
  --set replicaCount=1 --wait | grep STATUS
curl -s -H 'Host: api.tag05.lab' localhost/healthz
curl -s -o /dev/null -w '%{http_code}\n' -H 'Host: api.tag05.lab' localhost/version
curl -s -H 'Host: tag05.lab' localhost/version; echo

Expected:

[{"h":"tag05.lab","p":["/"]},{"h":"api.tag05.lab","p":["/notes","/healthz"]}]
STATUS: deployed
ok
404
0.7.1

In the inner loop the dot is the path – so the port comes through $. The variables $host and $paths are declared with := and overwritten with = inside the if; with := inside the if they would be back to the old values afterwards.

Save your progress? Sign up for free

Cleanup

# on prod
helm uninstall challenge -n tag05
kubectl delete namespace tag05
cd ~/helm/charts
git add -A
git commit -qm "Tag 05: Whitespace, if/with/range, Ingress, notes 0.4.0"

Expected:

release "challenge" uninstalled
namespace "tag05" deleted

Interview Note

  • Why nindent instead of indent? nindent starts with a line break; together with {{- the action sits readably at the start of the line and the block starts cleanly on a new line.
  • if or with? Both check for empty. with also sets the dot to the value; inside it you only reach .Release through $.
  • What do you do when 0 must be an allowed value? Do not use default; check with hasKey or kindIs instead – default treats 0 and false like “not set”.

Enterprise Note

  • Blank lines and wrong indentation often only show up at the API – or not at all, like app:notestier. That is why you run kubeconform and unit tests in CI (Day 17).
  • range over maps is sorted. That keeps renderings stable; otherwise every helm diff would show phantom changes.
  • Ingress classes and annotations differ per controller; charts make them configurable through values and only hard-code something for the default controller.
  • Many platforms are moving from Ingress to the Gateway API (HTTPRoute). A chart can offer both and choose with .Capabilities (Day 4).