Learn to use named templates in Helm to reduce repetitive code in Kubernetes manifests and improve maintainability.
In this lesson, you’ll learn how to use named templates to eliminate repetitive code in your Helm charts. When creating Kubernetes manifests, you might notice that labels or other blocks often repeat across multiple objects. For instance, consider the following YAML snippets for a Service and a Deployment where identical label definitions appear in several sections:
To address this redundancy, you can transfer the shared lines to a helper file (commonly named _helpers.tpl). The underscore in the filename tells Helm to ignore this file when generating Kubernetes manifests. For example, if you start with a Service template like this:
Copy
Ask AI
# service.yamlapiVersion: v1kind: Servicemetadata: name: {{ .Release.Name }}-nginx labels: # common labels will be included herespec: ports: - port: 80 targetPort: http protocol: TCP name: http selector: app: hello-world
You can move the repeated labels into a named template using the define directive. In your _helpers.tpl, add:
Notice that appending a dot (.) to the template call passes the current context into the helper file. Without it, the helper template wouldn’t have access to critical values like .Release.Name.
The same approach works for Deployment manifests where the labels are used in multiple locations. Initially, you might attempt to reuse the helper template like this:
However, this method may result in unexpected indentation issues. When the helper template is inserted, it must respect the surrounding indentation. Although the first instance might work correctly if the helper template is properly formatted, additional instances may not be aligned as expected.
To resolve the indentation problem, use the include function instead of template. The include function allows the output to be piped to other functions like indent. Ensure your helper template in _helpers.tpl is defined as follows:
This practice ensures that the output from the named template “labels” remains correctly indented, preserving readability and consistency in your generated manifest.
This approach of moving repetitive code into named templates and using functions like include with proper indentation not only enhances code maintainability but also minimizes the risk of errors and inconsistencies in your Helm charts.For more details on managing Helm charts and Kubernetes manifests, visit the Helm Documentation and Kubernetes Concepts.