Skip to content
Tutorials Center
My learning

Topics

Lesson 15 of 38 ยท Template Functions and Pipelines

Functions and Pipelines: Sprig in Helm Templates

Learn how pipelines pass values as the last argument, and tour the most useful Sprig functions: default, quote, trunc, printf, lists, dicts, math and encoding.

Go templates ship with only a few built-in functions. Helm adds the large Sprig library (around 100 functions) plus Helm-specific ones such as include, toYaml, required, tpl and lookup. Together with the pipeline operator | they let a template clean, default and reshape values in a line. This lesson explains how pipelines pass arguments (the one rule everyone trips over) and tours the functions you will use daily.

Calling a function

A function call is its name followed by space-separated arguments. No commas, no parentheses unless you nest:

YAML
name: {{ upper "web" }}
url: {{ printf "https://%s:%d" .Values.host (int .Values.port) }}
tag: {{ default "latest" .Values.image.tag }}

Parentheses group a call that is itself an argument: printf "%d" (add 1 2).

Pipelines: the value becomes the last argument

The pipe feeds the result of the left side into the function on the right as its last argument:

YAML
name: {{ .Values.name | upper | quote }}
tag: {{ .Values.image.tag | default "latest" }}

These two lines are exactly equivalent to quote (upper .Values.name) and default "latest" .Values.image.tag. That is why default takes the default first and the value last: it was designed for pipelines. When you pipe into a function that takes more arguments, the others come first and the piped value goes at the end:

YAML
{{ "world" | printf "hello %s" }}        # printf "hello %s" "world"  ->  hello world
{{ .Release.Name | trunc 10 }}           # trunc 10 .Release.Name
{{ .Values.items | join "," }}           # join "," .Values.items
flowchart LR
  A[".Values.name"] -->|pipe| B["upper"] -->|pipe| C["quote"] --> D["Result: WEB in quotes"]

Each stage receives the previous result as its last argument.

The following program implements this exact rule with a small set of functions, so you can build pipelines of your own and see the evaluation order.

Python Stand-in: a pipeline evaluator

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.

Follow trunc 9: the number 9 is the first argument and the release name is appended as the last. The trimSuffix "-" after it removes a dangling dash left by cutting mid-name, a pattern used in every fullname helper.

Functions you will use constantly

Strings

Function Example Result
quote, squote {{ "a" | quote }} "a" / 'a'
upper, lower, title {{ "ada" | title }} Ada
trim, trimPrefix "x", trimSuffix "x" {{ "-a-" | trimSuffix "-" }} -a
trunc N {{ "abcdef" | trunc 3 }} abc
replace old new {{ "a b" | replace " " "-" }} a-b
contains, hasPrefix, hasSuffix {{ contains "ab" "cabd" }} true
printf {{ printf "%s-%d" "a" 3 }} a-3
indent N, nindent N see the next lesson indentation helpers
kebabcase, snakecase, camelcase {{ "myApp" | kebabcase }} my-app
randAlphaNum N {{ randAlphaNum 16 }} random, changes on every render

Defaults and logic

Function Meaning
default d v v unless it is empty (false, 0, "", nil, empty collection), then d
empty v true when v is empty
coalesce a b c the first non-empty argument
ternary a b cond a if cond is true, otherwise b
required "msg" v fail with msg if v is empty (see the validation lesson)

Math: add, sub, mul, div, mod, max, min, ceil, floor, round, plus conversions int, int64, float64, toString.

Lists: list "a" "b", first, last, rest, append, prepend, concat, has "x" $list, uniq, sortAlpha, reverse, join ",", splitList ",", until 5, seq 1 5.

Dictionaries: dict "k" "v", get $d "k", set $d "k" "v", hasKey $d "k", keys, values, pick, omit, merge $dest $src1 $src2, mergeOverwrite, deepCopy.

Encoding and hashing: b64enc, b64dec, sha256sum, sha1sum, toJson, toPrettyJson, fromJson, toYaml, fromYaml.

Semver and dates: semverCompare ">=1.27.0-0" .Capabilities.KubeVersion.Version, now, date "2006-01-02" now.

Functions with random or time output (randAlphaNum, now, genPrivateKey, uuidv4) give a different result every time Helm renders. On helm upgrade that changes the manifest, causing pods to restart and Secrets to be regenerated. Generate such values once and reuse them (see lookup in tpl, lookup and Other Advanced Functions), or take them from values.

default is the workhorse

YAML
replicas: {{ .Values.replicaCount | default 1 }}
tag: {{ .Values.image.tag | default .Chart.AppVersion | quote }}

Because default treats 0 and false as empty, replicaCount: 0 would be replaced by 1. If zero is legitimate, check hasKey .Values "replicaCount" instead, or use ternary:

YAML
{{- if hasKey .Values "replicaCount" }}
replicas: {{ .Values.replicaCount }}
{{- end }}

Working with lists and dicts

The stand-in below mirrors a few of the collection functions. Note that Sprig's merge gives priority to the destination (first) map, which surprises people: use mergeOverwrite when the later map should win.

Python Stand-in: dict and list helpers

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.

Reading function errors

  • function "foo" not defined: typo, or the function is not in Sprig. Helm removes a few Sprig functions that touch the environment (env, expandenv) for safety.
  • wrong type for value; expected string; got int: convert with toString or quote.
  • error calling add: ...: arguments must be numbers; YAML numbers are float64, so wrap them in int.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does {{ "x" | printf "%s-%s" "a" }} produce?

    The piped value is appended as the last argument: printf "%s-%s" "a" "x".
  2. 2. Why is replicaCount: 0 a problem with | default 1?

    default replaces false, 0, empty strings, nil and empty collections.
  3. 3. In Sprig, merge $dest $src gives priority to which map?

    merge keeps existing keys of the destination; mergeOverwrite lets later maps win.
  4. 4. Why is randAlphaNum risky in templates?

    Random values regenerate on each render, causing rollouts or new Secrets.

Summary

  • Function calls are name arg arg; a pipe passes the left result as the last argument of the right function.
  • default, quote, trunc, trimSuffix, printf, join, dict, hasKey and merge cover most chart code.
  • default treats 0 and false as empty; use hasKey when zero is valid.
  • Avoid random or time functions unless the result is stored and reused.

Next: Rendering YAML: toYaml, indent and nindent