Helm & Kustomize · Lesson 3 of 7 · 4 min read
Templating in depth
The basics
Enlarge diagram
Swipe sideways to see all of it, or tap to open it full screen.
# templates/deployment.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
name: {{ include "orders.fullname" . }}
labels:
{{- include "orders.labels" . | nindent 4 }}
spec:
{{- if not .Values.autoscaling.enabled }}
replicas: {{ .Values.replicaCount }}
{{- end }}
selector:
matchLabels:
{{- include "orders.selectorLabels" . | nindent 6 }}
template:
metadata:
annotations:
checksum/config: {{ include (print $.Template.BasePath "/configmap.yaml") . | sha256sum }}
labels:
{{- include "orders.selectorLabels" . | nindent 8 }}
spec:
containers:
- name: app
image: "{{ .Values.image.repository }}:{{ .Values.image.tag | default .Chart.AppVersion }}"
{{- with .Values.env }}
env:
{{- range $k, $v := . }}
- name: {{ $k }}
value: {{ $v | quote }}
{{- end }}
{{- end }}
resources:
{{- toYaml .Values.resources | nindent 12 }}
Key pieces:
- Built-in objects:
.Values,.Release(.Release.Name,.Release.Namespace,.Release.Revision,.Release.IsUpgrade),.Chart(.Chart.Name,.Chart.Version,.Chart.AppVersion),.Capabilities(.Capabilities.KubeVersion,.Capabilities.APIVersions.Has),.Template,.Files. - Whitespace control:
{{-and-}}trim whitespace;nindent Nadds a newline then indents — the main tool to keep YAML valid. - Control structures:
if/else,with(changes.scope; use$for the root),range. - Functions (Go templates + Sprig):
default,quote,toYaml,required,tpl,lookup,b64enc,sha256sum,printf,trunc 63 | trimSuffix "-". requiredfails rendering if a value is missing:{{ required "image.tag is required" .Values.image.tag }}.lookupqueries live cluster objects during install/upgrade (returns empty inhelm template— design for that).- Config checksum annotation — rolling restart when a ConfigMap changes, since pods don't restart on ConfigMap edits by themselves.
Named templates (_helpers.tpl)
{{- define "orders.fullname" -}}
{{- printf "%s-%s" .Release.Name .Chart.Name | trunc 63 | trimSuffix "-" -}}
{{- end -}}
{{- define "orders.selectorLabels" -}}
app.kubernetes.io/name: {{ .Chart.Name }}
app.kubernetes.io/instance: {{ .Release.Name }}
{{- end -}}
include (unlike template) returns a string you can pipe (| nindent 4). Names over 63 characters break Kubernetes object names — hence trunc 63.
Never change selector labels in an upgrade: Deployment selectors are immutable, so the upgrade fails ("field is immutable") and you'd have to delete and recreate.
Library charts and an internal "service chart"
Platform teams often publish one internal application chart (Deployment, Service, HPA, PDB, ServiceMonitor, NetworkPolicy, ingress) with secure defaults — non-root, resource requests, probes, topology spread — and each service supplies only a small values file. A type: library chart provides shared named templates without rendering anything itself.
Enlarge diagram
Swipe sideways to see all of it, or tap to open it full screen.