Middle
How to use Helm templates?
sobes.tech AI
Answer from AI
Helm templates allow for dynamic generation of Kubernetes manifests based on provided values and functions.
Main components of templating:
- Templates: YAML manifest files with embedded Go template syntax.
- Values: YAML files or command-line parameters containing data to fill templates.
- Functions: Built-in or custom Go template functions for processing values and generating strings.
Example of a basic deployment.yaml template:
apiVersion: apps/v1
kind: Deployment
metadata:
name: {{ .Release.Name }}-{{ .Chart.Name }}
spec:
replicas: {{ .Values.replicaCount }}
selector:
matchLabels:
app: {{ .Chart.Name }}
template:
metadata:
labels:
app: {{ .Chart.Name }}
spec:
containers:
- name: {{ .Chart.Name }}
image: "{{ .Values.image.repository }}:{{ .Values.image.tag }}"
ports:
- containerPort: {{ .Values.service.port }}
Example of a values.yaml file:
replicaCount: 1
image:
repository: nginx
tag: latest
service:
port: 80
Using helpers for reusable code blocks, usually in _helpers.tpl:
{{/*
Common labels
*/}}
{{- define "mychart.labels" -}}
helm.sh/chart: {{ include "mychart.chart" . }}
{{ include "mychart.selectorLabels" . }}
{{- if .Chart.AppVersion }}
app.kubernetes.io/version: {{ .Chart.AppVersion | quote }}
{{- end }}
app.kubernetes.io/instance: {{ .Release.Name }}
app.kubernetes.io/managed-by: {{ .Release.Service }}
{{- end }}
{{/*
Selector labels
*/}}
{{- define "mychart.selectorLabels" -}}
app.kubernetes.io/name: {{ include "mychart.name" . }}
app.kubernetes.io/instance: {{ .Release.Name }}
{{- end }}
Calling a helper in a template:
labels:
{{ include "mychart.labels" . | nindent 4 }}
Main functions of the Go templating engine, often used in Helm:
| Function | Description | Example |
|---|---|---|
include |
Inserts the content of another template. | {{ include "my.helper" . }} |
nindent |
Indents multi-line output. | `{{ .Values.multiline |
quote |
Wraps a string in quotes. | `{{ .Values.someString |
default |
Sets a default value. | `{{ .Values.replicas |
required |
Fails if a value is missing. | {{ required "A database password is required!" .Values.database.password }} |
toJson |
Converts data to a JSON string. | `{{ .Values.config |
toYaml |
Converts data to a YAML string. | `{{ .Values.config |
Managing spaces: - after {{ and before }} trims whitespace.
{{- range .Values.items }}
- name: {{ .name }}
value: {{ .value | quote }}
{{- end -}}
Branching logic and loops:
{{- if .Values.ingress.enabled }}
apiVersion: networking.k8s.io/v1
kind: Ingress
...
{{- end }}
{{- range $key, $value := .Values.configMapData }}
{{ $key }}: {{ $value | quote }}
{{- end }}
Template testing:
helm lint mychart # Basic syntax check
helm template mychart --values mychart/values.yaml # Render template with values