TExcelTAD
Home › Kubernetes Packaging: Helm & Kustomize › Templates & Pipelines

Templates & Pipelines

Everything under templates/ is a Go template that must render to YAML. Helm adds the Sprig function library and a few functions of its own (include, tpl, required, toYaml, lookup, …). This lesson covers the syntax you use on every line; the next ones cover objects, control flow and named templates.

Actions and pipelines

Anything between {{ and }} is an action. {{ .Values.image.tag }} inserts a value. A pipeline passes a value through functions left to right with |, exactly like a shell pipe: {{ .Values.logLevel | upper | quote }} is quote (upper .Values.logLevel).

bash · try it yourself
mkdir -p linkly/templates && cd linkly
printf 'apiVersion: v2\nname: linkly\nversion: 0.1.0\nappVersion: "1.4.0"\n' > Chart.yaml
cat > values.yaml <<'EOF'
image:
  repository: ghcr.io/acme/linkly
  tag: ""
logLevel: info
port: 8080
baseUrl: https://lnk.example.com
EOF
cat > templates/configmap.yaml <<'EOF'
apiVersion: v1
kind: ConfigMap
metadata:
  name: {{ .Release.Name }}-config
data:
  LOG_LEVEL: {{ .Values.logLevel | upper | quote }}
  LISTEN_ADDR: {{ printf ":%d" (.Values.port | int) | quote }}
  BASE_URL: {{ .Values.baseUrl | trimSuffix "/" | quote }}
  IMAGE: {{ printf "%s:%s" .Values.image.repository (.Values.image.tag | default .Chart.AppVersion) | quote }}
EOF
helm template demo .
helm template demo . --set image.tag=1.5.0 --set baseUrl=https://lnk.example.org/ | tail -4
---
# Source: linkly/templates/configmap.yaml
apiVersion: v1
kind: ConfigMap
metadata:
  name: demo-config
data:
  LOG_LEVEL: "INFO"
  LISTEN_ADDR: ":8080"
  BASE_URL: "https://lnk.example.com"
  IMAGE: "ghcr.io/acme/linkly:1.4.0"
  LOG_LEVEL: "INFO"
  LISTEN_ADDR: ":8080"
  BASE_URL: "https://lnk.example.org"
  IMAGE: "ghcr.io/acme/linkly:1.5.0"

Things to notice:

  • quote wraps a value in double quotes. ConfigMap data must be strings, and YAML would otherwise read 8080, true or 1.10 as a number or a boolean. Quote every string you insert.
  • default X returns X when the piped value is empty: "", 0, false, nil, an empty list or map. That is why the empty tag fell back to appVersion. It also means default 3 .Values.replicas turns a deliberate 0 into 3; for numbers where 0 is valid, test with hasKey instead.
  • Parentheses group a sub-pipeline: (.Values.image.tag | default .Chart.AppVersion).
  • int converts: values from YAML numbers arrive as float64, and printf "%d" needs an integer.

Common functions

Function Example Result
quote, squote {{ "a" | quote }} "a"
default {{ .Values.x | default "y" }} y if x is empty
required {{ required "host is required" .Values.host }} fails rendering with the message if empty
upper, lower, title, trim, trimSuffix, replace {{ "Ab" | lower }} ab
printf {{ printf "%s-%s" .Release.Name "db" }} demo-db
toYaml, toJson, fromYaml {{ toYaml .Values.resources }} a YAML block
indent N, nindent N {{ toYaml . | nindent 4 }} the block indented (nindent adds a newline first)
b64enc, sha256sum {{ "pw" | b64enc }} cHc=
trunc N, trimSuffix {{ $name | trunc 63 | trimSuffix "-" }} a valid DNS label
ternary {{ ternary "yes" "no" .Values.on }} yes or no
semverCompare {{ semverCompare ">=1.33-0" .Capabilities.KubeVersion.Version }} true/false

Whitespace control

Actions that produce no text, such as {{ if }} and {{ end }}, still leave their line's newline behind. A - next to the braces trims whitespace on that side: {{- eats everything before it (including newlines), -}} everything after. The session renders the same template with and without trimming; cat -A marks each line end with $ so the blank lines are visible:

bash · try it yourself
mkdir -p ws/templates && cd ws
printf 'apiVersion: v2\nname: ws\nversion: 0.1.0\n' > Chart.yaml
printf 'debug: true\n' > values.yaml
cat > templates/a.yaml <<'EOF'
data:
  {{ if .Values.debug }}
  LOG_LEVEL: debug
  {{ end }}
  PORT: "8080"
EOF
cat > templates/b.yaml <<'EOF'
data:
  {{- if .Values.debug }}
  LOG_LEVEL: debug
  {{- end }}
  PORT: "8080"
EOF
helm template demo . | cat -A
---$
# Source: ws/templates/a.yaml$
data:$
  $
  LOG_LEVEL: debug$
  $
  PORT: "8080"$
$
---$
# Source: ws/templates/b.yaml$
data:$
  LOG_LEVEL: debug$
  PORT: "8080"$

The untrimmed version still parses, but the stray $ lines are trailing whitespace that linters flag and diffs show. The usual idiom is {{- on control actions and nothing on value actions. Trimming too much is the opposite mistake: {{- .Values.x -}} glues the value to the previous and next lines and produces invalid YAML.

Inserting YAML blocks: toYaml and nindent

Resource requests, tolerations or annotations are maps that users supply whole. Don't template each key; insert the block with toYaml and indent it to the right depth with nindent:

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'
resources:
  requests: {cpu: 100m, memory: 64Mi}
  limits: {memory: 128Mi}
podAnnotations:
  prometheus.io/scrape: "true"
EOF
cat > templates/deployment.yaml <<'EOF'
apiVersion: apps/v1
kind: Deployment
metadata:
  name: {{ .Release.Name }}
spec:
  selector:
    matchLabels: {app: linkly}
  template:
    metadata:
      labels: {app: linkly}
      {{- with .Values.podAnnotations }}
      annotations:
        {{- toYaml . | nindent 8 }}
      {{- end }}
    spec:
      containers:
        - name: linkly
          image: ghcr.io/acme/linkly:1.4.0
          resources:
            {{- toYaml .Values.resources | nindent 12 }}
EOF
helm template demo . | kubeconform -strict -summary
helm template demo . -s templates/deployment.yaml | sed -n '/template:/,$p'
Summary: 1 resource found parsing stdin - Valid: 1, Invalid: 0, Errors: 0, Skipped: 0
  template:
    metadata:
      labels: {app: linkly}
      annotations:
        prometheus.io/scrape: "true"
    spec:
      containers:
        - name: linkly
          image: ghcr.io/acme/linkly:1.4.0
          resources:
            limits:
              memory: 128Mi
            requests:
              cpu: 100m
              memory: 64Mi

nindent 12 starts a new line and indents every line of the block by 12 spaces, the column where keys under resources: belong. Getting the number wrong is the most common Helm bug: too few spaces and the keys move up a level (often still valid YAML, but wrong), too many and parsing fails. Always render and validate after changing indentation, as the session does. (with is explained in Flow Control & Scope.)

Comments

{{/* a template comment */}} disappears from the output; a YAML # comment stays in the rendered manifest (and, unlike template comments, can still contain actions that are evaluated). Use template comments to explain template logic, YAML comments for things the reader of the rendered manifest should see.

Test yourself

What does {{ .Values.tag | default .Chart.AppVersion }} render when tag: ""?

  1. An empty string
  2. The chart's appVersion
  3. An error
  4. The word default

Why is {{ toYaml .Values.resources | nindent 12 }} preferred over indent 12?

  1. nindent is faster
  2. nindent starts with a newline, so the action can sit at the end of the parent line or on its own trimmed line
  3. indent doesn't exist
  4. nindent sorts the keys

Which action removes the newline *before* it?

  1. {{ x -}}
  2. {{- x }}
  3. {{/* x */}}
  4. {{ x }}