पाठ 12 / 25
Named Templates, include and tpl
Reuse snippets with define and include, and know when tpl and lookup are useful.
Write it once in _helpers.tpl
Repeated snippets such as names and labels belong in named templates, defined with {{ define "chart.name" }}...{{ end }} in a file starting with _ (usually _helpers.tpl). Prefix names with the chart name, because named templates are global across a chart and its subcharts. Use them with include, not template: include returns a string you can pipe (include "shop-api.labels" . | nindent 4), while the template action writes output directly and cannot be piped. Pass the right context as the second argument, usually . or $. The tpl function renders a string from values as a template, letting users put {{ .Release.Name }} inside a value. lookup reads existing objects from the cluster (for example, to reuse a generated password), but returns an empty result during helm template and client-side dry runs, so templates must handle that case.
Labels helper and a checksum annotation
The checksum makes pods restart when the ConfigMap content changes.
{{/* templates/_helpers.tpl */}}
{{- define "shop-api.selectorLabels" -}}
app.kubernetes.io/name: {{ .Chart.Name }}
app.kubernetes.io/instance: {{ .Release.Name }}
{{- end }}
{{- define "shop-api.labels" -}}
{{ include "shop-api.selectorLabels" . }}
helm.sh/chart: {{ printf "%s-%s" .Chart.Name .Chart.Version | replace "+" "_" }}
app.kubernetes.io/version: {{ .Chart.AppVersion | quote }}
app.kubernetes.io/managed-by: {{ .Release.Service }}
{{- end }}
{{/* in deployment.yaml, under spec.template.metadata */}}
annotations:
checksum/config: {{ include (print $.Template.BasePath "/configmap.yaml") . | sha256sum }}Never put changing labels in selectors
A Deployment's spec.selector is immutable. If it includes app.kubernetes.io/version or the chart version, the next upgrade fails with a "field is immutable" error. Keep selector labels to stable name and instance labels, as the helpers above do.
त्वरित जाँच: Why is `include` preferred over the `template` action in Helm charts?
- include returns a string that can be piped to functions such as nindent
- include is faster
- template is removed in Helm 3
- include works only in values.yaml
Answer
include returns a string that can be piped to functions such as nindent — include's output can be piped, which is needed to indent or transform snippets.