In this lesson, you will learn how to reduce duplication in your Helm charts by creating modular, reusable code blocks using define and template.
As your Helm charts grow, you’ll likely find yourself repeating the same boilerplate code across multiple files—such as standard labels, annotations, or complex environment variable blocks. Instead of copy-pasting, we use Template Partials (often stored in a _helpers.tpl file) to define a block of logic once and inject it wherever needed.
Creating a Partial
To create a partial, you use the define keyword. By convention, these are placed in a file prefixed with an underscore, like templates/_helpers.tpl.
{{- define "mychart.labels" -}}
app.kubernetes.io/name: {{ .Chart.Name }}
app.kubernetes.io/instance: {{ .Release.Name }}
{{- end -}}
Rendering a Partial
Once defined, you don't use the standard curly braces {{ }} to call it. Instead, you use the template action, which simply renders the output of your defined block into the file:
# templates/deployment.yaml
metadata:
labels:
{{- template "mychart.labels" . }}
The "Include" Advantage
While template is simple, it has a limitation: it cannot be used inside other template functions because it is an action, not a function. For more flexibility, use include. The include function allows you to pass the output of your partial through other Go template functions, such as indent.
# Correct way to apply indentation to a partial
labels:
{{ include "mychart.labels" . | indent 2 }}
By modularizing your configurations into partials, you ensure that if you need to update a label strategy or a common configuration block, you only have to change it in one location rather than hunting through every manifest in your chart. This keeps your deployment logic DRY (Don't Repeat Yourself) and significantly easier to maintain as your infrastructure scales.
Key Takeaway: Use the define keyword to encapsulate repetitive logic into partials and the include function to inject them into your manifests with proper formatting.