Skip to content
Tutorials Center
My learning

Topics

Lesson 53 of 78 ยท Packaging and Delivery

Writing Helm Charts

Write your own Helm chart: template syntax, helpers, pipelines, if and range, hooks, tests and dependencies, plus a runnable mini template engine.

In the previous lesson you used charts other people wrote. Now you write one. A chart template is a Kubernetes manifest with small programs embedded in {{ }} delimiters. Helm uses Go's text/template language plus a library of about sixty extra functions, and it feeds the template an object tree: your merged values, information about the release, and information about the chart.

The language is simple but unforgiving, because the output is YAML and YAML cares about every space. Most of the craft in chart writing is controlling whitespace and indentation. This lesson walks through the building blocks and then lets you run a miniature template engine so the rules feel concrete.

No Helm and no cluster run in this page. Chart files and commands are read-only. The Python stand-in implements a small subset of the template language (if, range, define, include, pipelines and a handful of functions) to show how rendering works; the real engine has far more features and some different edge cases.

What a template can see

.Values Merged configuration from defaults, files and --set.
.Release Name, Namespace, IsInstall, IsUpgrade, Revision.
.Chart Fields from Chart.yaml, like Name and AppVersion.
.Files Read extra files bundled in the chart.
1 / 2

A first template

A Deployment template in templates/deployment.yaml might start like this:

YAML
apiVersion: apps/v1
kind: Deployment
metadata:
  name: {{ .Release.Name }}-web
  labels:
    {{- include "shop.labels" . | nindent 4 }}
spec:
  replicas: {{ .Values.replicaCount }}
  selector:
    matchLabels:
      app.kubernetes.io/instance: {{ .Release.Name }}
  template:
    metadata:
      labels:
        {{- include "shop.labels" . | nindent 8 }}
    spec:
      containers:
        - name: web
          image: "{{ .Values.image.repository }}:{{ .Values.image.tag | default .Chart.AppVersion }}"
          {{- with .Values.resources }}
          resources:
            {{- toYaml . | nindent 12 }}
          {{- end }}

Everything outside the braces is copied through. Inside them:

  • {{ .Values.replicaCount }} prints a value. The leading dot means "the current context".
  • {{ expr | func }} is a pipeline: the left value becomes the last argument of the function. .Values.image.tag | default .Chart.AppVersion means "use the tag, or the chart's appVersion if the tag is empty".
  • {{- and -}} trim whitespace, including newlines, on that side. Without them an if block leaves blank lines behind, and a blank line in the wrong place is harmless while a wrong indent is not.
  • with rebinds the dot to a value and skips the block if the value is empty.
  • toYaml turns a map into YAML text, and nindent 12 adds a newline and indents every line by twelve spaces. Use nindent when the block starts on a new line and indent when it continues the current line.

Templates are always rendered, even for objects that end up empty. A file whose output is blank (for example an if that is false) simply creates nothing.

Helpers and named templates

Labels, names and selectors repeat in every file. Put them in templates/_helpers.tpl. Files starting with an underscore are not rendered as manifests; they only hold definitions.

TEXT
{{- define "shop.labels" -}}
app.kubernetes.io/name: {{ .Chart.Name }}
app.kubernetes.io/instance: {{ .Release.Name }}
app.kubernetes.io/version: {{ .Chart.AppVersion | quote }}
{{- end }}

You call it with include "shop.labels" ., passing the context as the last argument. Prefix helper names with the chart name (shop.labels), because named templates are global across a chart and its subcharts, and a clash overwrites silently. Prefer include over template, because include returns a string you can pipe into nindent.

Two other idioms are worth knowing. required "image.tag is needed" .Values.image.tag aborts rendering with that message when the value is empty, which turns a silent mistake into a clear error. And to restart pods when a ConfigMap changes, put a checksum of the rendered ConfigMap in the pod's annotations:

YAML
      annotations:
        checksum/config: {{ include (print $.Template.BasePath "/configmap.yaml") . | sha256sum }}

Helm will not restart pods because a ConfigMap changed (see ConfigMaps), but a changed annotation changes the pod template, and a changed pod template triggers a rolling update.

Conditionals and loops

if takes any value; empty strings, zero, false, empty lists and missing keys are all false.

YAML
{{- if .Values.ingress.enabled }}
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: {{ .Release.Name }}
spec:
  rules:
    {{- range .Values.ingress.hosts }}
    - host: {{ . | quote }}
    {{- end }}
{{- end }}

Inside range, the dot becomes the current item. That has a classic trap: .Values no longer works there, because the item has no Values. Use the variable $, which always points to the root context, as in $.Release.Name. A comparison looks like {{ if eq .Values.env "prod" }}; Go templates use prefix functions (eq, ne, and, or, not) instead of operators.

Run a stand-in engine that supports these constructs. It tokenizes the template, builds a tree of text, if, range and define nodes, and evaluates pipelines.

Python A mini template engine

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.

Look at how the tag fell back to 2.7.1, how nindent lined the labels up under labels:, and how the whole resources block disappeared once the value was empty. The dashes in {{- are what keep the output free of blank lines.

Hooks and tests

A hook is a template that Helm runs at a particular moment of the release instead of treating it as a normal part of the release. You turn any manifest into a hook with an annotation:

YAML
apiVersion: batch/v1
kind: Job
metadata:
  name: {{ .Release.Name }}-migrate
  annotations:
    "helm.sh/hook": pre-install,pre-upgrade
    "helm.sh/hook-weight": "-5"
    "helm.sh/hook-delete-policy": before-hook-creation,hook-succeeded
spec:
  backoffLimit: 0
  template:
    spec:
      restartPolicy: Never
      containers:
        - name: migrate
          image: {{ .Values.image.repository }}:{{ .Values.image.tag }}
          command: ["./migrate"]

Hook points include pre-install, post-install, pre-upgrade, post-upgrade, pre-delete, post-delete, pre-rollback and post-rollback. Hooks at the same point run in order of hook-weight (lowest first, numbers written as strings). Helm waits for a hook Job to complete before moving on, and a failed hook fails the release step. The delete policy matters: hook objects are not part of the release, so without a policy old hook Jobs pile up and the next run fails because the name already exists. The classic use is a database migration; see Jobs and CronJobs.

Tests are hooks with the annotation "helm.sh/hook": test, kept under templates/tests/. They are usually Pods that exit 0 on success. You run them against a live release:

Terminal
helm test web --namespace shop

A typical test pod calls the Service with curl or wget and fails if it gets no answer.

Dependencies

A chart can depend on other charts, for example your app on a PostgreSQL chart. You declare them in Chart.yaml:

YAML
dependencies:
  - name: postgresql
    version: "16.x.x"
    repository: oci://registry-1.docker.io/bitnamicharts
    condition: postgresql.enabled

helm dependency update downloads the packages into charts/ and writes Chart.lock with the exact versions, and helm dependency build reinstalls from that lock file. The parent configures a subchart through a values key that has the subchart's name, and a top-level global: map is visible to every subchart. The condition lets users switch the dependency off (to use a managed database, say). Databases in charts are fine for development; for production, think through running databases on Kubernetes.

The stand-in below resolves a parent chart with one conditional subchart, shows how values flow down and prints the hook order.

Python Dependencies, conditions and hook order

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.

The sort key includes the name because Helm breaks weight ties by resource name too, so the order is stable between runs.

Debugging and good habits

  • helm lint catches structural mistakes, helm template shows the output, and helm template --debug prints the partially rendered YAML even when parsing fails, so you can see which line broke.
  • Add values.schema.json so bad values (a string where a number belongs) fail early with a readable message.
  • Quote strings that must stay strings ({{ .Values.x | quote }}). Numbers and words like no or on change type otherwise; see YAML and the Shape of a Manifest.
  • Keep templates thin. If you find yourself nesting if four levels deep, move the choice into values.
  • Document every value in values.yaml with comments, since that file is the chart's public interface.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does {{- (a dash right after the opening braces) do?

    The dash trims whitespace on that side of the action. It keeps if and range blocks from leaving blank lines or odd indentation in the output.
  2. 2. Inside {{ range .Values.hosts }}, why does {{ .Values.env }} print nothing?

    Within range the dot is the current item. Use $.Values.env, where $ always refers to the root context.
  3. 3. Which annotation makes a Job run before every upgrade?

    The helm.sh/hook annotation names the moment, such as pre-install or pre-upgrade. Weights order hooks at the same point.
  4. 4. How does a parent chart set a value in its postgresql subchart?

    Values under a key named after the subchart are passed to it, and the global map is shared with all subcharts.
  5. 5. Why use a checksum annotation of a ConfigMap on the pod template?

    Pods do not restart when a ConfigMap changes. A changing checksum alters the pod template, which makes the Deployment perform a rolling update.

Summary

  • Templates are YAML plus {{ }} actions; the context holds .Values, .Release, .Chart and more.
  • Pipelines chain functions (default, quote, toYaml, nindent); {{- and -}} control whitespace.
  • if and range handle optional blocks and lists; inside range use $ to reach the root.
  • Put shared snippets in _helpers.tpl with chart-prefixed names and call them with include.
  • Hooks (helm.sh/hook) run Jobs at defined points and tests run with helm test; dependencies come from Chart.yaml and are configured through values keyed by subchart name.

Next, see how a whole delivery process can be driven from Git: GitOps with Argo CD and Flux.