Helm: Include definitions on templates

2 min read

Sometimes we might need to add the same content twice on the same Helm chart. A tipical example would be the labels on the Pods that need to match the selectos on the Service. For this when you create a helm chart there are already some default definitions, for example:

{{/*
Common labels
*/}}
{{- define "pet2cattle.labels" -}}
helm.sh/chart: {{ include "pet2cattle.chart" . }}
{{ include "pet2cattle.selectorLabels" . }}
app.kubernetes.io/managed-by: {{ .Release.Service }}
{{- end }}

{{/*
Selector labels
*/}}
{{- define "pet2cattle.selectorLabels" -}}
app.kubernetes.io/name: {{ include "pet2cattle.name" . }}
app.kubernetes.io/instance: {{ .Release.Name }}
{{- end }}

By convention, any file that begins with an underscore (for example: _helpers.tpl) in the templates/ directory is not expected to output a Kubernetes manifest but contain partial definitions that will be used elsewhere. We can create a new file that begins with underscore and place any definitions we want, for example:

{{- define "exampleconfig" }}
redis:
  enabled: true
  connection: '{{ .Values.redis.connection }}'
  configuration:
    secure: true
  cache:
    enabled: false
  scheduler:
    enabled: true
{{- end }}

And then use it elsewhere as many times a we need using the include function, for example:

apiVersion: v1
kind: ConfigMap
metadata:
  name: example-config-map
data:
  demo-1.yml: |
{{ include "exampleconfig" . | indent 4 }}
  demo-2.yml: |
{{ include "exampleconfig" . | indent 4 }}

On this example we are including multiple times the same data without having to defined it twice


Posted on 16/11/2021