top of page
Untitled design (12).png
Search

Leveraging Helm Templates for Reusable Kubernetes Deployments

  • Writer: Miki Zirkiev
    Miki Zirkiev
  • Mar 16
  • 4 min read

Introduction

Kubernetes has revolutionized how we deploy applications, but managing complex deployments across multiple environments can quickly become complicated. Enter Helm – the package manager for Kubernetes that simplifies deployment through charts, which are collections of YAML templates defining Kubernetes resources.

One of Helm's most powerful features is its templating engine, which leverages the Go templating language to create reusable, parameterized configurations. This article explores how you can use template files (.tpl) to dramatically improve your Kubernetes deployments.


Why Use Helm Templates?

1. Embrace DRY Principles with Reusable Components

The "Don't Repeat Yourself" (DRY) principle is fundamental to clean, maintainable code. Helm templates allow you to define common components once and reuse them across your entire infrastructure.

Creating template partials (stored in the templates/ directory with a .tpl extension or defined inline using the define keyword) eliminates repetition and centralizes changes to a single location.


2. Build a Modular Kubernetes Infrastructure

Think of templates as building blocks that you can assemble in different ways. By separating resource definitions (Deployments, Services, ConfigMaps) into dedicated template snippets, you can mix and match components to build complex deployments while maintaining consistency.

For example, a createDeployments template can loop over services defined in your values file, generating properly configured Deployments for each enabled service without duplicating YAML code.


3. Parameterize Everything for Maximum Flexibility

Reusable .tpl files can adapt to different scenarios based on values provided in your values.yaml. Your template can dynamically set properties like:

  • Image names and tags

  • Replica counts

  • Resource limits

  • Port configurations

  • Environment variables

This flexibility means you can deploy the same chart across development, staging, and production environments by simply changing configuration values.


.tpl Example: A Reusable Deployment Template

This reusable template demonstrates how Helm’s templating engine can dynamically generate Kubernetes manifests based on your values file while keeping your charts flexible and DRY:

{{- define "createDeployments" -}}
{{- range $app, $details := .Values.applications }}
  {{- if and (hasKey $.Values.applicationsEnable $app) (eq (index $.Values.applicationsEnable $app) true) }}
apiVersion: apps/v1
kind: Deployment
metadata:
  name: "{{ $details.name }}"
  namespace: "{{ $.Values.global.namespace }}"
  labels:
    app: "{{ $details.name }}"
spec:
  replicas: {{ $details.replicas | default $.Values.global.replicas }}
  selector:
    matchLabels:
      app: "{{ $details.name }}"
  template:
    metadata:
      labels:
        app: "{{ $details.name }}"
    spec:
      containers:
        - name: "{{ $details.name }}"
          image: "{{ $details.image }}:{{ $details.tag }}"
          imagePullPolicy: Always
          ports:
            - containerPort: {{ $details.port | default $.Values.global.port }}
              protocol: TCP
          resources:
            {{- if $details.resources }}
            limits:
              memory: {{ $details.resources.limits.memory }}
              cpu: {{ $details.resources.limits.cpu }}
            requests:
              memory: {{ $details.resources.requests.memory }}
              cpu: {{ $details.resources.requests.cpu }}
            {{- else }}
            limits:
              memory: {{ $.Values.global.resources.limits.memory }}
              cpu: {{ $.Values.global.resources.limits.cpu }}
            requests:
              memory: {{ $.Values.global.resources.requests.memory }}
              cpu: {{ $.Values.global.resources.requests.cpu }}
            {{- end }}
          {{- if $details.healthCheck }}
          livenessProbe:
            httpGet:
              path: "{{ $details.healthCheck.path }}"
              port: {{ $details.healthCheck.port }}
            initialDelaySeconds: {{ $details.healthCheck.initialDelay | default 30 }}
            periodSeconds: {{ $details.healthCheck.period | default 10 }}
          {{- end }}
          {{- if $details.env }}
          env:
            {{- range $key, $value := $details.env }}
            - name: {{ $key }}
              value: {{ $value | quote }}
            {{- end }}
          {{- end }}
  {{- end }}
{{- end }}
{{- end }}

The template focuses on the core elements of a Kubernetes Deployment, making it easier to understand while still demonstrating the power of Helm templating.


Key Benefits of Using .tpl Files in Helm Charts

1. Maintainability Through Centralization

Using a templating approach dramatically reduces redundancy. Need to update how your Deployments handle health checks or resource limits? Change it once in your template, and every service inherits the improvement. No more hunting through dozens of YAML files for that one configuration block.


2. Powerful Templating Functions

Helm's templating engine includes functions that make your life easier:

  • toYaml: Converts arrays or maps to properly formatted YAML

  • nindent: Ensures correct indentation for nested elements

  • default: Provides fallback values when a parameter isn't specified

  • if/else: Conditionally includes configuration blocks

These functions allow precise control over your YAML output, enhancing readability and ensuring proper formatting.


3. Improved Readability Through Decomposition

Breaking your chart into smaller, reusable template files creates a more modular, comprehensible structure. Each component can be understood independently, then composed to create the final Kubernetes manifest.

This approach supports a better mental model of your infrastructure and makes onboarding new team members much easier.


Implementing Templates in Your Helm Charts

Step 1: Define Reusable Template Snippets

Create or update your chart's templates/_helpers.tpl file (or another template file) to include reusable blocks like our createDeployment example. These blocks encapsulate logic for common tasks.


Step 2: Reference the Template in Your Manifests

In your primary YAML files (like deployment.yaml), call the template using the include function:

{{- include "createDeployments" . }}

This renders the defined template for each application in your values file.


Step 3: Structure Your Values File

Organize your values.yaml to include both global settings and application-specific details:

global:
  namespace: production
  replicas: 3
  port: 8080
  resources:
    limits:
      memory: "256Mi"
      cpu: "500m"
    requests:
      memory: "128Mi"
      cpu: "250m"
applicationsEnable:
  api: true
  worker: false
applications:
  api:
    name: api
    image: myorg/api
    tag: v1.2.3
    port: 8080
    env:
      APP_ENV: production
      LOG_LEVEL: info
  worker:
    name: worker
    image: myorg/worker
    tag: v1.2.3
    replicas: 5
    env:
      WORKER_CONCURRENCY: "10"
      QUEUE_NAME: default

Step 4: Test and Iterate

Preview the generated YAML before deployment:

helm template my-release ./my-chart

This shows you exactly what Kubernetes manifests will be created, allowing you to verify your templates work as expected.


Conclusion

Using Helm templates with reusable .tpl files transforms how you manage Kubernetes deployments. The approach:

  • Enhances reusability by centralizing common configuration patterns

  • Improves maintainability by reducing duplication

  • Increases clarity through modular design

  • Promotes consistency across environments

The example provided demonstrates a streamlined deployment template that dynamically generates Kubernetes resources based on configuration values. With this approach, you can confidently update and extend your charts, ensuring your deployments remain consistent and manageable as your infrastructure grows.

By mastering Helm templates, you'll spend less time wrestling with YAML and more time delivering value through your Kubernetes applications.

Creating modular, effective Helm charts is just one aspect of modern DevOps. Ycon's experience offers the technical know-how and strategic insight required to boost innovation and success as your company can navigate between environments. With our help, you can swiftly advance your digital evolution and confidently approach challenging Kubernetes environments.

 
 
 

Comments


Contact Us

Thanks for submitting!

bottom of page