Skip to main content

Working with Advanced Template Functions

1. Using String Functions

Function Description Example Notes
quote Wraps a value in quotes {{ quote "hello" }} Useful for ensuring values are treated as strings
lower Converts a string to lowercase {{ lower "HELLO" }} Returns hello
upper Converts a string to uppercase {{ upper "hello" }} Returns HELLO
trim Removes leading and trailing whitespace {{ trim " hello " }} Returns hello
splitList Splits a string into a list using a delimiter {{ splitList "," "a,b,c" }} Returns [a b c]
join Joins a list into a string with a delimiter {{ join "," (splitList "," "a,b,c") }} Returns a,b,c

Example: Using splitList and join

config:
  hosts: {{ join "," .Values.hosts }}

Example: Using lower

name: {{ lower .Chart.Name }}
Note: String functions are particularly useful in templates where you need to format or manipulate values before rendering them into Kubernetes manifests.

2. Using List Functions

Function Description Example Notes
list Creates a list from the arguments list "a" "b" "c" Useful for creating lists dynamically
splitList Splits a string into a list using the specified delimiter splitList "," "a,b,c" Returns a list of strings
join Joins a list into a string with the specified separator join "," (list "a" "b" "c") Reverses splitList
compact Removes empty strings from a list compact (list "a" "" "b") Useful for cleaning up lists with empty values
uniq Removes duplicate items from a list uniq (list "a" "b" "a") Returns a list with unique items
sortAlpha Sorts a list of strings alphabetically sortAlpha (list "c" "a" "b") Case-sensitive sorting

Example: Using list and splitList

{{- $myList := list "app1" "app2" "app3" }}
{{- $joined := join "," $myList }}
{{- $split := splitList "," $joined }}

Example: Using compact and uniq

{{- $dirtyList := list "app1" "" "app2" "app1" "" }}
{{- $cleanList := compact $dirtyList }}
{{- $uniqueList := uniq $cleanList }}

3. Using Dict Functions

Function Description Example Notes
dict Creates a dictionary from key-value pairs {{ $d := dict "key1" "value1" "key2" "value2" }} Useful for organizing data in templates
merge Merges two or more dictionaries {{ $merged := merge (dict "a" 1) (dict "b" 2) }} Values from the rightmost dict override leftmost
get Retrieves a value from a dictionary by key {{ $val := get $d "key1" }} Safe to use even if key does not exist
hasKey Checks if a key exists in the dictionary {{ $exists := hasKey $d "key1" }} Returns boolean true or false
keys Returns list of keys from dictionary {{ $keys := keys $d }} Useful for iterating over dictionary contents
values Returns list of values from dictionary {{ $vals := values $d }} Useful for extracting all values from a dict

Example: Merging Dictionaries

{{ $base := dict "name" "app" "version" "1.0" }}
{{ $overrides := dict "version" "2.0" "replicaCount" 3 }}
{{ $final := merge $base $overrides }}
Name: {{ $final.name }}
Version: {{ $final.version }}
Replicas: {{ $final.replicaCount }}

Example: Using get with Default Value

{{ $config := dict "port" 8080 }}
Port: {{ get $config "port" "defaultPort" }}
Timeout: {{ get $config "timeout" "30s" }}
Note: The dict function is particularly useful for creating configuration maps or setting up default values in Helm templates.

4. Using Type Functions

Function Description Usage Notes
typeOf Returns the type of a value as a string typeOf .Values.myValue Useful for conditional logic in templates
kindOf Returns the kind of a value (array, object, string, etc.) kindOf .Values.myArray Helps in type checking within templates
isArray Checks if a value is an array isArray .Values.myList Returns true or false
isObject Checks if a value is an object isObject .Values.myMap Returns true or false
isString Checks if a value is a string isString .Values.myString Returns true or false
isNumber Checks if a value is a number isNumber .Values.myNumber Returns true or false

Example: Using typeOf in a template

{{- if (eq (typeOf .Values.database.port) "string") }}
port: {{ .Values.database.port }}
{{- else }}
port: {{ quote .Values.database.port }}
{{- end }}

Example: Using isArray to handle lists

{{- range .Values.ingress.hosts }}
host: {{ . }}
{{- end }}
Note: These type functions are part of the Sprig library, which is included in Helm charts by default.

5. Using Path Functions

Function Description Example Notes
base Returns the last element of a path {{ base "/var/log/app.log" }} Result: app.log
dir Returns all but the last element of a path {{ dir "/var/log/app.log" }} Result: /var/log
clean Removes redundant elements from a path {{ clean "/var//log/app.log" }} Result: /var/log/app.log
ext Returns the file extension of a path {{ ext "/var/log/app.log" }} Result: .log
join Joins path elements with the OS-specific separator {{ join "var" "log" "app.log" }} Result: var/log/app.log (Unix) or var\log\app.log (Windows)

Example: Using path functions in a template

apiVersion: v1
kind: ConfigMap
metadata:
  name: {{ include "myapp.fullname" . }}-config
data:
  logFile: {{ .Values.logPath }}
  logDir: {{ dir .Values.logPath }}
  logBase: {{ base .Values.logPath }}
Note: These path functions are particularly useful for dynamically constructing paths in Helm templates, especially when dealing with log files or configuration directories.

6. Using Crypto Functions

When working with Helm charts, you may need to incorporate cryptographic functions for generating secure values or hashing data. Helm provides built-in template functions that can be used to perform cryptographic operations within your templates.

Function Description Usage Example
sha256 Generates a SHA-256 hash of the input string. {{ sha256 "secret-key" }}
sha1 Generates a SHA-1 hash of the input string. {{ sha1 "secret-key" }}
md5 Generates an MD5 hash of the input string. {{ md5 "secret-key" }}

Example: Generating a SHA-256 Hash

{{ sha256 "my-secret-key" }}
Note: While SHA-256 is suitable for most cryptographic uses, ensure that the context of usage aligns with security best practices.
Warning: MD5 and SHA-1 are considered cryptographically weak and should not be used for security-sensitive applications.

7. Using URL Functions

Function Description Example Notes
urlParse Parses a URL string into components {{ urlParse "https://example.com/path?query=value" }} Available in Helm v3.10+
urlJoin Joins URL components into a full URL {{ urlJoin "https://example.com" "/api" "v1" }} Available in Helm v3.10+
urlQueryEscape Escapes a string for use in a URL query parameter {{ urlQueryEscape "user input with spaces" }} Available in Helm v3.10+
urlPathEscape Escapes a string for use in a URL path segment {{ urlPathEscape "path/with/slashes" }} Available in Helm v3.10+

Example: Parsing a URL

{{- $parsed := urlParse "https://api.example.com/v1/users?id=123" -}}
Protocol: {{ $parsed.scheme }}
Host: {{ $parsed.host }}
Path: {{ $parsed.path }}
Query: {{ $parsed.rawQuery }}

Example: Building a URL

{{- $baseUrl := "https://api.example.com" -}}
{{- $path := "/v1/users" -}}
{{- $query := "?id=123&format=json" -}}
Full URL: {{ urlJoin $baseUrl $path $query }}
Note: These URL functions are part of the html template function family and require Helm v3.10 or later.

8. Using Regex Functions

Function Description Example Notes
regexMatch Checks if a string matches a regex pattern.
{{- if regexMatch "^v[0-9]+\.[0-9]+\.[0-9]+$" .Values.version -}}
Version is in semantic versioning format
{{- end -}}
Matches the version string against a semantic version regex
regexFind Finds the first match of a regex pattern in a string. {{ regexFind "[0-9]+" .Values.version }} Returns the first numeric part of the version
regexFindAll Finds all matches of a regex pattern in a string. {{ regexFindAll "[0-9]+" .Values.version }} Returns all numeric parts of the version as a slice
regexReplaceAll Replaces all matches of a regex pattern in a string with a replacement string. {{ regexReplaceAll "[^0-9]" .Values.version "" }} Removes all non-numeric characters from the version
regexSplit Splits a string by a regex pattern. {{ regexSplit "\\." .Values.version }} Splits the version string by dots into a slice

Example: Using regexMatch to validate version format

apiVersion: v1
kind: ConfigMap
metadata:
  name: {{ include "myapp.fullname" . }}
data:
  versionCheck: |
    {{- if regexMatch "^v[0-9]+\.[0-9]+\.[0-9]+$" .Values.version }}
    Valid version format
    {{- else }}
    Invalid version format - must be like v1.2.3
    {{- end }}

Example: Using regexReplaceAll to sanitize version

apiVersion: v1
kind: ConfigMap
metadata:
  name: {{ include "myapp.fullname" . }}
data:
  sanitizedVersion: |
    {{ regexReplaceAll "[^0-9.]" .Values.version "" }}

9. Using Sprig Functions

Sprig is a library of template functions for Helm charts, providing additional utility functions beyond the built-in Go template functions. These functions are particularly useful for string manipulation, date formatting, and conditional logic.

Function Description Example
lower Converts a string to lowercase {{ "HELLO WORLD" | lower }} → hello world
upper Converts a string to uppercase {{ "hello world" | upper }} → HELLO WORLD
trim Removes leading and trailing whitespace {{ " hello world " | trim }} → hello world
splitList Splits a string into a list using a delimiter {{ "a,b,c" | splitList "," }} → [a b c]
join Joins a list into a string with a delimiter {{ list "a" "b" "c" | join "," }} → a,b,c
date Formats a date using Go's time format {{ now | date "2006-01-02" }} → 2025-04-05
regexReplaceAll Replaces all matches of a regex pattern with a replacement string {{ "hello world" | regexReplaceAll "world" "universe" }} → hello universe
toJson Converts a value to JSON string {{ dict "key" "value" | toJson }} → {"key":"value"}

Example: Using Sprig Functions in Values

name: {{ .Chart.Name | lower }}
labels:
  app: {{ .Chart.Name | trim }}
  version: {{ .Chart.Version | splitList "." | first }}

Example: Date Formatting with Sprig

timestamp: {{ now | date "2006-01-02 15:04:05" }}
Note: Sprig functions are available in all Helm templates. They can be used in any context where Go templates are supported, including values files and template files.

10. Using Math Functions

Function Description Example Notes
mul Multiply two numbers {{ mul 5 3 }} Returns 15
div Divide two numbers {{ div 10 2 }} Returns 5
add Add two numbers {{ add 4 6 }} Returns 10
sub Subtract second number from first {{ sub 10 3 }} Returns 7
mod Modulo operation (remainder) {{ mod 17 5 }} Returns 2
max Return the larger of two numbers {{ max 3 8 }} Returns 8
min Return the smaller of two numbers {{ min 3 8 }} Returns 3

Example: Using math functions in values.yaml

replicaCount: {{ mul .Values.replicaCount 2 }}
memoryLimit: {{ div .Values.memoryLimit 1024 }}Mi

Example: Combining math with conditionals

resources:
  limits:
    cpu: {{ if gt (mul .Values.cpu 2) 2 }}{{ mul .Values.cpu 2 }}{{ else }}{{ .Values.cpu }}{{ end }}m
    memory: {{ mul .Values.memory 1024 }}Mi

Was this article helpful?