SkillByAIOpen interactive version →

Lesson 10 / 25

Template Basics and Built-in Objects

Use Go template actions, built-in objects and common functions safely.

Go templates plus Sprig

Helm templates use Go's text/template language plus the Sprig function library and some Helm-specific functions. Everything between {{ and }} is an action. Built-in objects give you context: .Values (merged values), .Release (.Release.Name, .Release.Namespace, .Release.IsUpgrade, .Release.Revision), .Chart (fields of Chart.yaml, such as .Chart.Name and .Chart.AppVersion), .Capabilities (Kubernetes version and available API versions), .Template and .Files (access to non-template files in the chart). Functions are called with arguments or through pipelines: {{ .Values.env | default "dev" | quote }}. Useful ones: default, quote, required (fail with a message if a value is missing), upper, trim, b64enc, toYaml, indent/nindent. Whitespace control with {{- and -}} trims spaces and newlines on that side, which is how you keep the output valid YAML.

From template to manifest

The template engine combines templates with values and built-in objects to produce plain YAML.

Figure 4.1 — Rendering combines templates, values and built-in objects.

Common patterns in one ConfigMap

required turns a missing value into a clear install-time error instead of a broken pod.

apiVersion: v1
kind: ConfigMap
metadata:
  name: {{ .Release.Name }}-config
  namespace: {{ .Release.Namespace }}
data:
  APP_ENV: {{ .Values.env | default "dev" | quote }}
  API_URL: {{ required "apiUrl is required, e.g. --set apiUrl=https://..." .Values.apiUrl | quote }}
  LOG_LEVEL: {{ .Values.logLevel | default "info" | upper | quote }}
  RELEASE_INFO: "{{ .Chart.Name }}-{{ .Chart.Version }} rev {{ .Release.Revision }}"

Quote strings that look like other types

YAML turns true, yes, on, 1.10 and 0123 into booleans or numbers. Environment variables and annotation values must be strings, so pipe them through quote. A version 1.10 without quotes becomes the number 1.1.

Quick check: What does `{{-` (with a dash) do?

  • Subtracts one from a value
  • Comments out the line
  • Trims whitespace and newlines to the left of the action
  • Marks the value as required
Answer

Trims whitespace and newlines to the left of the action — The dash trims whitespace on that side of the action, keeping rendered YAML tidy.