Helm Chart Development: Templates, Values, Dependencies and Testing

Building a production-grade helm chart is where many teams discover that Kubernetes manifests don't scale gracefully on their own. A single Deployment and Service is trivial to manage by hand, but once you need to support multiple environments, share common patterns across services, and integrate with CI/CD, raw YAML becomes a liability. Over the last five years managing platform tooling for clusters ranging from 20 to 400 nodes, I've learned that a well-designed chart is less about templating tricks and more about creating a predictable, testable interface for your kubernetes deployment workflow. This article covers the patterns I rely on when creating maintainable charts, from directory structure and values design to dependency management and testing strategies that catch errors before they reach the cluster.

Structuring Your Chart Directory to Prevent Technical Debt

In my experience, the most common mistake teams make is treating a helm chart as a dumping ground for every manifest they have. The default scaffold from helm create is a useful starting point, but it encourages you to keep everything enabled by default and buries important configuration under generic values. For any service that will live longer than a few months, I restructure the chart around the principle of explicit intent.

A clean chart separates concerns between deployable resources, reusable partials, and configuration. I typically keep the root lean and isolate complex logic. Here is the layout I use for most internal services:

my-service/
├── Chart.yaml
├── values.yaml              # Sensible production defaults only
├── values.schema.json       # Enforced constraints
├── values-dev.yaml          # Minimal dev overrides
├── values-staging.yaml
├── templates/
│   ├── _helpers.tpl         # Named templates only, no resources
│   ├── _pod.tpl             # Shared pod spec partials
│   ├── deployment.yaml
│   ├── service.yaml
│   ├── ingress.yaml
│   ├── serviceaccount.yaml
│   ├── hpa.yaml
│   └── tests/               # helm test pods
│       └── test-connection.yaml
└── charts/                  # Vendored dependencies (gitignored if using OCI)

Keeping Chart.yaml Honest About Versioning and API

Your Chart.yaml is a contract. Set type: application unless you are genuinely building a library chart, and use SemVer strictly. I've found that teams that bump the chart version independently from the container appVersion have far fewer rollback confusions. The chart version should change whenever the templated Kubernetes objects change, even if the application image hasn't. This distinction matters immensely when you use GitOps tools like Argo CD or Flux that diff chart versions to decide when to sync.

Another detail that pays off: declare kubeVersion and dependencies constraints explicitly. If your chart uses autoscaling/v2 for HPA, require Kubernetes >= 1.23. This prevents a silent helm template render that later fails on an older cluster with a cryptic API error. The Kubernetes Documentation maintains a reliable reference for when APIs were deprecated and removed, which I check every time I add a new resource kind.

When to Extract a Library Chart

If you maintain more than four or five services with similar Deployment, Service, and PodDisruptionBudget patterns, stop copying templates and create a library chart. A library chart contains only named templates in templates/_*.tpl and is consumed as a dependency. In one platform I managed, we reduced 600 lines of duplicated deployment logic to a single include "platform.podSpec" call. The trade-off is that library charts add indirection, so I only recommend them once duplication becomes painful and you have testing in place. For guidance on packaging the underlying container images consistently before they are deployed via Helm, see Dockerfile Best Practices: Multi-Stage Builds, Layer Caching and Security.

Taming Helm Templating Logic: Functions, Pipelines and Named Templates

Helm's templating engine is Go templates plus the Sprig function library plus Helm-specific functions. It is powerful, but unreadable templates are a maintenance burden. The rule I follow is: keep logic in helpers and keep resources declarative.

The helm template command is your fastest feedback loop, and I run it constantly during development. Unlike helm install --dry-run, it renders locally without any cluster connection, which makes it ideal for rapid iteration. I've found that aliasing helm template . --debug --values values-dev.yaml saves hours over a week of chart work.

{{/* templates/_helpers.tpl */}}
{{- define "my-service.fullname" -}}
{{- if .Values.fullnameOverride }}
{{- .Values.fullnameOverride | trunc 63 | trimSuffix "-" }}
{{- else }}
{{- $name := default .Chart.Name .Values.nameOverride }}
{{- if contains $name .Release.Name }}
{{- .Release.Name | trunc 63 | trimSuffix "-" }}
{{- else }}
{{- printf "%s-%s" .Release.Name $name | trunc 63 | trimSuffix "-" }}
{{- end }}
{{- end }}
{{- end }}

{{- define "my-service.labels" -}}
helm.sh/chart: {{ include "my-service.chart" . }}
app.kubernetes.io/name: {{ include "my-service.name" . }}
app.kubernetes.io/instance: {{ .Release.Name }}
app.kubernetes.io/version: {{ .Chart.AppVersion | quote }}
app.kubernetes.io/managed-by: {{ .Release.Service }}
{{- end }}

Controlling Flow Without Creating Spaghetti

Avoid nesting three or four levels of if inside a Deployment. Instead, use with, required, and dictionary merging. For example, to conditionally inject sidecars or initContainers, I define the structure in values.yaml as a list and range over it, rather than writing an if-block for each possible sidecar. This keeps the helm chart extensible without editing the template for every new use case.

Another practical technique is using tpl sparingly. It allows you to evaluate a string value as a template, which is useful when you want users to provide annotations that contain templating expressions like {{ .Release.Name }}. Overusing tpl makes debugging difficult, so I restrict it to annotations, labels, and extra environment variables where dynamic interpolation is genuinely needed.

Finally, be deliberate about whitespace. The hyphen in {{- ... -}} trims whitespace, and inconsistent use leads to malformed YAML that is hard to trace. I always trim on the left for control structures ({{- if, {{- range) and keep values without trimming to preserve readability in the rendered output. Running the rendered output through yq or kubeval as a post-processing step catches indentation errors early.

Designing Values.yaml for Environment-Specific Overrides Without Duplication

If values.yaml has 400 lines, no one will understand what is actually configurable. A good values file acts as an API for your chart consumers. I design it with a small set of high-level knobs and a transparent escape hatch for advanced cases.

Start with flat, intuitive keys for the things operators change most often: replicaCount, image.repository, image.tag, resources, autoscaling.enabled. Group related settings under a common parent, but avoid deep nesting beyond three levels. Deep nesting makes --set overrides painful and increases the chance of typo-driven misconfigurations.

# values.yaml - production defaults with validation in mind
replicaCount: 3

image:
  repository: registry.example.com/my-service
  tag: "1.4.2"
  pullPolicy: IfNotPresent

resources:
  requests:
    cpu: 250m
    memory: 512Mi
  limits:
    cpu: 1000m
    memory: 1Gi

service:
  type: ClusterIP
  port: 80

ingress:
  enabled: false
  className: nginx
  hosts:
    - host: chart-example.local
      paths:
        - path: /
          pathType: Prefix

# Escape hatch for anything not explicitly modeled
extraEnv: []
# - name: LOG_LEVEL
#   value: debug
extraVolumes: []
extraVolumeMounts: []

Schema Enforcement and Type Safety

Since Helm 3, values.schema.json lets you enforce types, enums, and required fields using JSON Schema. In my experience this is the single most underused feature for preventing production incidents. I require a schema for every chart that is deployed by more than one team.

A schema can enforce that replicaCount is an integer between 1 and 20, that ingress.className is one of a known set, or that resources.limits.memory matches a regex like ^[0-9]+(Mi|Gi)$. When a developer misconfigures a value, helm lint and helm install will fail fast with a clear message instead of producing a Deployment that gets rejected by the API server. This is especially important when you expose autoscaling configuration that interacts with the cluster autoscaler; for a deeper look at scaling behavior, see Kubernetes Autoscaling: HPA, VPA and KEDA for Event-Driven Scaling.

Layering Values for Multiple Environments

Instead of maintaining completely separate values files per environment, I keep values.yaml as the production baseline and layer minimal overrides. For example, values-dev.yaml might only contain:

replicaCount: 1, resources.requests.cpu: 100m, and image.tag: pr-123. This approach means you review what is different, not what is repeated. Using helm template -f values.yaml -f values-dev.yaml makes the merge order explicit: later files override earlier ones. I've found that committing these override files alongside the chart and referencing them by name in CI eliminates the class of errors where a deploy script passes the wrong --set flag.

Managing Chart Dependencies with Helm's Dependency System and OCI Registries

Modern applications rarely consist of a single Deployment. You often need Redis, PostgreSQL, or a service mesh sidecar alongside your app. Helm's dependency system lets you compose charts without copy-pasting manifests, but it introduces version and lifecycle decisions you need to get right.

Dependencies are declared in Chart.yaml under the dependencies key. Helm 3 supports both classic chart repositories and OCI registries, and I've largely migrated to OCI because it simplifies authentication and integrates with existing container registry scanning. The workflow is consistent: define, update, and lock.

# Chart.yaml
apiVersion: v2
name: my-service
version: 0.8.0
appVersion: "1.4.2"
dependencies:
  - name: postgresql
    version: 12.1.x
    repository: oci://registry.example.com/charts/postgresql
    condition: postgresql.enabled
    tags:
      - database
  - name: redis
    version: 18.x.x
    repository: https://charts.bitnami.com/bitnami
    condition: redis.enabled

Note the use of condition and tags. The condition field ties directly to a value path, so setting postgresql.enabled: false disables the entire subchart. This is far cleaner than wrapping dependency resources in your own if-blocks. I use tags when I want to enable or disable a group of dependencies together, for example, enabling all persistence-related charts with tags.database=true.

Versioning Strategy and Lock Files

After defining dependencies, run helm dependency update to resolve and download them, which generates or updates Chart.lock. Commit Chart.lock to version control. I've been bitten by unpinned dependencies where a minor update to a Bitnami chart changed default securityContext settings and caused pods to fail with permission errors. Using a constraint like 12.1.x allows patch updates but prevents breaking minor changes, and the lock file guarantees reproducible builds in CI.

For private charts, authenticate with helm registry login before pulling OCI-based dependencies. If you are vendoring charts for air-gapped environments, run helm dependency build instead of update to strictly use the lock file without reaching out to registries.

When your dependency is another internal chart that owns networking primitives like Service or Ingress, coordinate carefully. I've seen teams struggle when both the parent and subchart try to create an Ingress with conflicting annotations. In those cases, expose the subchart's ingress values under a namespaced key and document which layer owns L7 routing. The patterns discussed in Kubernetes Networking: Services, Ingress Controllers and Network Policies are directly relevant here, especially around how Ingress classes and NetworkPolicies interact across chart boundaries.

Validating Rendered Manifests: Linting, Unit Testing and Dry-Run Strategies

A chart that renders is not the same as a chart that works. In my current pipeline, a chart passes through four validation stages before it can be promoted to staging. This layered approach catches different classes of errors and keeps feedback loops short.

Layered Validation Pipeline

First, helm lint checks for chart syntax and schema violations. It is fast and runs on every commit. Second, I use helm template piped to kubeconform or kubeval to validate against the Kubernetes OpenAPI schemas for the target cluster version. This catches deprecated APIs and type errors, such as passing a string where an integer is expected for replicas. Third, unit tests with helm-unittest assert specific template behaviors without needing a cluster. Fourth, helm install --dry-run --debug on a real cluster validates against server-side logic including admission webhooks.

This is where investing in tests pays for itself. The helm-unittest plugin lets you write YAML-based tests that assert conditions like "when ingress.enabled is false, no Ingress object is rendered" or "when autoscaling.enabled is true, Deployment replicas is absent". I've found that 10-15 well-chosen unit tests cover 80% of chart logic and prevent most regressions when refactoring helpers.

Validation Method Execution Context What It Catches Speed
helm lint Local, no cluster Chart syntax, values schema violations, missing required values ~1s
helm template | kubeconform Local, schema-based Invalid Kubernetes manifests, deprecated APIs, type mismatches ~2s
helm-unittest Local, no cluster Conditional logic errors, incorrect defaults, helper output regressions ~3s
helm install --dry-run --debug Requires cluster connection Server-side validation, webhook rejections, RBAC and quota issues ~5-10s

To make this practical in CI, I run the first three stages in parallel on every pull request, and only run the dry-run stage when targeting a long-lived environment branch. For a helm template example, I render with production values and pipe directly to a validator: helm template my-release . -f values.yaml | kubeconform -kubernetes-version 1.29 -strict. If your chart generates CustomResourceDefinitions, remember they need to be validated differently, since most schema validators do not know about CRDs by default. See the Kubernetes Documentation on custom resources for how to handle schema validation for operators.

Releasing and Versioning Charts for Reliable Kubernetes Deployment Pipelines

The final step is turning a validated chart into a releasable artifact that your deployment pipeline can consume deterministically. This is where many teams introduce fragility by deploying directly from a Git branch or by using --set for everything. I've shifted to treating charts as immutable artifacts published to a registry, with promotion handled by changing the chart version reference rather than re-rendering from source.

Start by packaging with helm package, which creates a versioned .tgz archive. For OCI registries, push with helm push my-service-0.8.0.tgz oci://registry.example.com/charts. The OCI flow is now the recommended path and avoids maintaining a separate index.yaml for a classic chart museum. Tag immutability is critical: never overwrite a published version. If you find a bug in 0.8.0, publish 0.8.1 even if the fix is a one-line template change.

Integrating with GitOps and Argo CD

When using GitOps, the deployment repository or ApplicationSet should reference a specific chart version, not latest. I keep a Chart.lock style approach at the application layer by pinning the chart version in the Argo CD Application manifest and updating it via a pull request from CI when a new chart is published. This provides an audit trail and makes rollbacks as simple as reverting a version bump.

Another lesson from production: separate chart releases from application image releases. Your CI for the application should build and push a new image, then trigger a chart release only if the Kubernetes deployment logic actually changed. If you only changed application code, a GitOps tool can update image.tag in the environment values without publishing a new chart version. This separation keeps your chart history meaningful and prevents churn where every commit creates a new chart artifact that is functionally identical to the last.

Finally, documentbreaking changes in chart release notes, especially when you change default values or remove a deprecated template. I maintain a CHANGELOG.md and enforce it in pull request templates. Operators upgrading a dependency need to know if ingress.enabled was renamed to ingress.create or if PodSecurityContext defaults became more restrictive. A clear changelog turns upgrades from detective work into routine maintenance.

Frequently Asked Questions

Should I use helm template or helm install --dry-run for validation?

Use both, but for different purposes. helm template renders manifests locally without a cluster, making it fast and ideal for unit testing and schema validation with tools like kubeconform. helm install --dry-run sends the rendered manifests to the Kubernetes API server for server-side dry-run validation, which catches errors from admission webhooks, CRD validation, and quota enforcement that local rendering cannot. In my pipelines, I run helm template on every commit and helm install --dry-run only when a cluster is available, such as on the staging branch.

How do I avoid duplicating values across multiple environments?

Keep values.yaml as your production baseline and create minimal overlay files like values-dev.yaml that only contain differences. Helm merges values files in order, so running helm install -f values.yaml -f values-dev.yaml will override only the keys you specify. I also recommend using values.schema.json to enforce constraints, so environment-specific overrides cannot accidentally set an invalid type or out-of-range value.

When should I create a library chart instead of copying templates?

Create a library chart when you have three or more application charts sharing identical helpers for labels, pod specs, or common resources like ServiceAccounts. Library charts trade duplication for indirection, so they are worth it once maintaining copies becomes error-prone. Start by extracting helpers for naming and labels, then graduate to shared Deployment or Job patterns. Keep library charts versioned separately and pin them with a strict version constraint in Chart.lock.

How do I handle chart dependencies that require their own CRDs?

Ensure CRDs are installed separately before the chart that consumes them is deployed. Helm only installs CRDs from the crds/ directory on initial install and does not upgrade them on subsequent releases. For dependencies that include CRDs, document the installation order or use a dedicated operator management tool. If you are building your own operator and chart pair, the patterns in Kubernetes Operators: Building Custom Resources and Controllers can help you decide whether the CRD belongs in the chart or in a separate lifecycle.

Related Articles

References & Standards: Kubernetes Documentation · Docker Documentation · Terraform Documentation