Skip to content
Tutorials Center
My learning

Topics

Lesson 18 of 38 ยท Template Functions and Pipelines

tpl, lookup and Other Advanced Template Functions

Go beyond the basics: render strings from values with tpl, read live cluster objects with lookup, keep generated secrets stable, and use semverCompare and must functions.

You now know enough Helm to write useful charts. A few more functions separate a tidy chart from a flexible, production-grade one: tpl lets users write templates inside values, lookup reads objects that already exist in the cluster, the must family fails loudly instead of returning empty, and semverCompare handles version-dependent output. Each has sharp edges, which this lesson points out.

tpl: templates inside values

Normally values are plain data: whatever the user writes is copied as it is. tpl renders a string as a template, with a context you choose. That allows values such as:

YAML
# values.yaml
ingress:
  host: "{{ .Release.Name }}.apps.example.com"
extraEnv:
  - name: SERVICE_URL
    value: "http://{{ .Release.Name }}-backend:8080"
YAML
# templates/ingress.yaml
- host: {{ tpl .Values.ingress.host . | quote }}

tpl STRING CONTEXT takes the template text and the data it may reference (usually ., the top-level context, so .Release and .Values are available). Typical uses: host names built from the release name, annotation values that reference other values, and whole blocks such as extraVolumes supplied as a multi-line string and rendered with tpl (toYaml .) $.

Cautions:

  • tpl evaluates whatever the user wrote, including calls to functions like include. Only render strings from trusted values files. Never pass user-submitted input to it.
  • Inside range or with, remember to pass $ as the context, otherwise .Release is missing.
  • A value containing {{ that should stay literal (for instance a Prometheus alert annotation) gets rendered by mistake; escape it with {{ "{{" }}.
  • Errors point at tpl, not at the line of the values file, so keep embedded templates short.

The stand-in reuses the tiny renderer idea: a string from values is rendered against a context at install time.

Python Stand-in: tpl renders a string from values

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.

lookup: read the live cluster

lookup apiVersion kind namespace name queries the Kubernetes API while rendering and returns the object as a map, or an empty map when it does not exist:

YAML
{{- $existing := lookup "v1" "Secret" .Release.Namespace "db-credentials" }}
{{- if $existing }}
password: {{ index $existing.data "password" }}
{{- else }}
password: {{ randAlphaNum 24 | b64enc | quote }}
{{- end }}

Pass an empty name to list: lookup "v1" "Pod" "prod" "" returns a list under .items, and an empty namespace searches all namespaces.

Two facts matter:

  1. helm template and --dry-run (client mode) do not contact a cluster, so lookup always returns an empty map there. Your templates must work in that case, and logic like "only if the Secret does not exist yet" runs as if it did not exist. Use --dry-run=server (or helm install --dry-run=server) to let lookups hit the API.
  2. It needs RBAC permission to read those objects, and it makes the chart's output depend on cluster state, which makes it harder to review and to run through GitOps tools that render offline (Argo CD, for instance, renders charts without cluster access, so lookups return empty there too).

The stable secret idiom

A generated password should be created once and then reused on upgrades; otherwise each upgrade changes it and breaks the database. The idiom above does that with lookup. The stand-in simulates three consecutive upgrades with and without the lookup:

Python Stand-in: a password that stays stable

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.

A simpler, more robust alternative is to let the user supply the password (or an existing Secret name) and not generate anything in the chart, or to use an external secrets tool. If you keep the idiom, mark the Secret with helm.sh/resource-policy: keep as appropriate and document that lookup needs cluster access.

The must functions

Many functions silently return an empty value or a default when they fail, which hides problems. Most have a must twin that aborts the render with the underlying error: mustToJson, mustFromJson, mustRegexMatch, mustRegexReplaceAll, mustFirst, mustLast, mustHas, mustUniq, mustMerge. Use them where bad input should stop the chart:

YAML
{{- if not (mustRegexMatch "^[a-z][a-z0-9-]{1,30}$" .Values.appName) }}
{{- fail "appName must be 2-31 lowercase letters, digits or dashes" }}
{{- end }}

semverCompare

Chart output sometimes depends on the Kubernetes version or an image version. semverCompare CONSTRAINT VERSION returns a boolean:

YAML
{{- if semverCompare ">=1.28.0-0" .Capabilities.KubeVersion.Version }}
# use a field that exists only on 1.28 and later
{{- end }}
{{- if semverCompare "^2.0.0" (.Values.image.tag | default .Chart.AppVersion) }}

Constraints support >=, <, ~ (patch changes), ^ (minor changes) and || for alternatives. The -0 suffix again lets vendor versions like v1.28.3-gke.100 match, as explained in Chart Structure. The next stand-in is a small version of the comparison for plain >=, < and ^ constraints.

Python Stand-in: semverCompare

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.

A few more useful functions

Function Use
lookup Read live objects (needs a cluster)
genCA, genSignedCert, genSelfSignedCert Generate TLS material (new every render, combine with lookup)
getHostByName "host" DNS lookup at render time (avoid: output depends on the network)
fromYaml, fromYamlArray Parse a YAML string, for example .Files.Get "config.yaml"
toToml, toJson Other serializations
regexMatch, regexReplaceAll, regexFind Pattern matching
typeOf, kindOf, kindIs "map" . Inspect types; useful when a value may be a string or a map
deepEqual Compare structures
include + sha256sum Config checksum annotations for restarts
.Release.IsInstall Run something only on first install

Anything that depends on the outside world (lookup, getHostByName, now, random functions) makes helm template output differ from what helm install produces. Keep such code to a few well-commented places, make it optional behind a value where you can, and test both modes.

Where to go from here

You now have the whole language of Helm templates: syntax, values, objects, control flow, helpers and functions. Next the course moves to dependencies (subcharts and global values), hooks, repositories and OCI registries, testing and security, and CI/CD. Return to the track overview to see the full list of chapters.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does tpl do?

    tpl evaluates template syntax found in a string, using the context you pass.
  2. 2. What does lookup return under helm template?

    Client-side rendering cannot query the API; use --dry-run=server for real lookups.
  3. 3. Why use lookup around a randomly generated password?

    Random functions give a new value on each render; lookup finds the existing one.
  4. 4. What is the benefit of mustRegexMatch over regexMatch?

    must functions fail loudly where the plain versions swallow errors.

Summary

  • tpl STRING CONTEXT renders template syntax stored in values; only use it with trusted input and pass $ inside loops.
  • lookup reads live objects and returns an empty map in helm template and client dry runs; use it to keep generated secrets stable.
  • must functions fail the render on errors; semverCompare handles version-dependent output.
  • Be careful with anything non-deterministic, because it makes offline rendering differ from the real install.

Next: Chart Dependencies and Subcharts