Lesson 3: Package & Configuration Management (Helm vs Kustomize)
๐ง The Concept (Explain Like Iโm 5)
Imagine you are furnishing 100 identical apartment units across 3 different cities (Dev, Staging, and Production):
- Raw Kubernetes Manifests (Handcrafting every nail): You manually cut and assemble 100 individual wooden desks. If someone decides the desks should be 2 inches wider, you must manually recut all 100 desks by hand.
- Helm (The Flat-Pack IKEA Furniture Kit):
You design a single modular furniture kit with a blueprint (Helm Chart Templates). It has pre-drilled holes and adjustable legs. When setting up an apartment in Dev, you pass a simple configuration note (
values.yaml) that sayscolor: blue, size: small. In Production, you passcolor: gold, size: extra-large. Helm handles all assembly automatically. - Kustomize (Surgical Customization without blueprints): You already have an existing, complete, fully assembled standard wooden desk (The Base Manifest). Kustomize lets you clamp an extra monitor arm to the desk in Production without sawing, disassembling, or rewriting the original wood (Overlays and Patches).
๐ข The Enterprise Context: Why Both Exist in Platform Engineering
In an enterprise platform engineering team, you will rarely choose only Helm or only Kustomize. They solve two fundamentally different problems:
flowchart TD
subgraph UseCases ["Enterprise Workload Separation"]
ThirdParty["<b>3rd-Party Off-The-Shelf Infrastructure</b><br/>โข Datadog Agent<br/>โข Cert-Manager<br/>โข Prometheus-Stack<br/>โข Ingress-NGINX"]
InternalApps["<b>Internal Proprietary Microservices</b><br/>โข Payment Service<br/>โข Order Service<br/>โข Auth Gateway"]
end
subgraph ToolingChoice ["Architectural Tooling Choice"]
Helm["<b>Helm Package Manager</b><br/>Parameter-driven abstraction<br/>Single packaged artifact (.tgz)<br/>Versioning & Rollbacks"]
Kustomize["<b>Kustomize Engine</b><br/>Template-free pure YAML<br/>Base + Overlays (Dev, Staging, Prod)<br/>ConfigMap hash rolling restarts"]
end
ThirdParty -->|"Industry Standard"| Helm
InternalApps -->|"GitOps Best Practice"| Kustomize
subgraph ModernHybrid ["The Enterprise Hybrid Model (ArgoCD)"]
Hybrid["ArgoCD renders 3rd-party Helm Chart<br/>+ Kustomize overlays Enterprise Security Patches (PDBs, IRSA)"]
end
Helm --> ModernHybrid
Kustomize --> ModernHybrid
โ Deep-Dive 1: Helm Architecture & Templating Engine
Helm is the official package manager for Kubernetes. A Helm Chart is a collection of files that describe a related set of Kubernetes resources.
my-service-chart/
โโโ Chart.yaml # Metadata: chart name, version (SemVer), API version
โโโ values.yaml # Default configuration values for templates
โโโ values.prod.yaml # Production-specific override values
โโโ charts/ # Subcharts and dependencies (e.g. redis, postgresql)
โโโ templates/ # Go template manifests rendered by Helm
โโโ _helpers.tpl # Reusable Go template helper functions and named snippets
โโโ deployment.yaml # Kubernetes Deployment manifest with {{ ... }} placeholders
โโโ service.yaml # Kubernetes Service
โโโ NOTES.txt # Post-installation instructions printed to terminal
Understanding Go Template Syntax
Helm uses the Go text/template engine enhanced with the Sprig utility library:
apiVersion: apps/v1
kind: Deployment
metadata:
# 1. Template Helper: Injects standard sanitized labels
name: {{ include "my-service.fullname" . }}
labels:
{{- include "my-service.labels" . | nindent 4 }}
spec:
# 2. Pipeline with Default fallback: If replicaCount not set, defaults to 2
replicas: {{ .Values.replicaCount | default 2 }}
selector:
matchLabels:
app: {{ include "my-service.name" . }}
template:
metadata:
labels:
app: {{ include "my-service.name" . }}
spec:
containers:
- name: {{ .Chart.Name }}
# 3. String formatting and pipelines
image: "{{ .Values.image.repository }}:{{ .Values.image.tag | default .Chart.AppVersion }}"
imagePullPolicy: {{ .Values.image.pullPolicy }}
# 4. Conditional logic: Only render ports if enabled in values.yaml
{{- if .Values.service.enabled }}
ports:
- name: http
containerPort: {{ .Values.service.port }}
protocol: TCP
{{- end }}
# 5. Serialization & Indentation: Dump complex dictionary into valid YAML
resources:
{{- toYaml .Values.resources | nindent 12 }}
How Helm Tracks Releases in the Cluster
When you run helm install my-app ./my-chart:
- Helm compiles templates + values into raw Kubernetes YAML.
- Helm sends the manifests to
kube-apiserver. - Where does Helm store release state? Helm stores the entire release manifest and revision history in a base64-encoded, gzip-compressed Kubernetes Secret in the target namespace (named
sh.helm.release.v1.my-app.v1). - This makes Helm completely serverlessโit does not require a background daemon running in your cluster!
๐งฉ Deep-Dive 2: Kustomize Architecture & The Overlay Pattern
Kustomize is built directly into kubectl (via kubectl apply -k). It rejects text-templating in favor of Pure Declarative Overlays.
k8s/
โโโ base/ # The Single Source of Truth for the workload
โ โโโ deployment.yaml # Generic deployment (e.g. 1 replica, baseline CPU)
โ โโโ service.yaml # Baseline ClusterIP service
โ โโโ kustomization.yaml # Declares resources in the base
โโโ overlays/ # Environment-specific customizations
โโโ dev/
โ โโโ kustomization.yaml # Points to base, adds dev labels & small resources
โ โโโ dev-config.env
โโโ prod/
โโโ kustomization.yaml # Points to base, scales replicas, adds HPA & PDB
โโโ patch-replicas.yaml # Strategic Merge Patch
โโโ prod-config.env
flowchart TD
Base["<b>base/</b><br/>โข deployment.yaml<br/>โข service.yaml"]
DevOverlay["<b>overlays/dev/</b><br/>โข namePrefix: dev-<br/>โข replicas: 1<br/>โข cpu: 100m"]
ProdOverlay["<b>overlays/prod/</b><br/>โข namePrefix: prod-<br/>โข replicas: 10<br/>โข cpu: 2000m<br/>โข commonLabels: compliance=pci"]
Base --> DevOverlay
Base --> ProdOverlay
DevOverlay --> DevOutput["<b>Rendered Dev Manifests</b><br/>(Lightweight sandbox)"]
ProdOverlay --> ProdOutput["<b>Rendered Prod Manifests</b><br/>(Hardened HA production)"]
The Two Patching Strategies in Kustomize
1. Strategic Merge Patch (SMP)
You write a partial Kubernetes manifest containing only the specific keys you want to override. Kustomize merges your partial manifest with the base manifest using Kubernetes field semantics:
# overlays/prod/patch-resources.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
name: order-service
spec:
replicas: 10
template:
spec:
containers:
- name: app
resources:
requests:
cpu: "1000m"
memory: "2Gi"
2. JSON 6902 Patch (Surgical Precision)
When you need to modify an item inside a list (e.g. change an argument in an array or delete a specific sidecar), SMP can be ambiguous. JSON 6902 patches execute precise operations (add, remove, replace):
# In kustomization.yaml
patches:
- target:
kind: Deployment
name: order-service
patch: |-
- op: replace
path: /spec/template/spec/containers/0/imagePullPolicy
value: Always
- op: add
path: /spec/template/spec/nodeSelector
value:
karpenter.sh/capacity-type: spot
โก The Killer Feature: configMapGenerator & Zero-Downtime Rolling Restarts
In standard Kubernetes, if you edit a ConfigMap or Secret, running Pods do NOT automatically restart to pick up the new configuration. Engineers frequently had to run manual rollout restarts (kubectl rollout restart deployment/...).
Kustomize solves this with Automatic Content Hashing:
# overlays/prod/kustomization.yaml
apiVersion: kustomize.config.k8s.io/v1beta1
kind: Kustomization
resources:
- ../../base
configMapGenerator:
- name: app-config
literals:
- DB_HOST=prod-postgres.internal
- DB_PORT="5432"
- LOG_LEVEL=warn
When Kustomize renders this manifest, it calculates the SHA-256 hash of the configuration values and appends it to the ConfigMap name:
- Name becomes:
app-config-g7b8d4f82h - Kustomize automatically updates the
DeploymentmanifestโsconfigMapRefto matchapp-config-g7b8d4f82h! - The Result: When you change a configuration value in Git, the hash changes (
app-config-9k2m1a0x7c). Kubernetes sees a change in the Deploymentโs PodTemplate spec and automatically initiates a safe, zero-downtime rolling update!
โ๏ธ Architectural Decision Matrix: Helm vs Kustomize
| Feature | Helm | Kustomize |
|---|---|---|
| Philosophy | Parameterized templating engine | Pure declarative overlay patching |
| File Format | Go templates (.tpl, {{ ... }}) |
100% valid, lintable Kubernetes YAML |
| Dependency Management | Built-in (Chart.yaml dependencies) |
Manual or requires Git submodules |
| Packaging & Distribution | OCI Registries (push/pull .tgz charts) |
Git repositories only |
| Installation Tooling | Requires Helm CLI or Helm Controller | Built natively into kubectl (kubectl apply -k) |
| Risk of Syntax Errors | High (Whitespace indentation errors in Go templates) | Low (All files are statically validated by YAML linters) |
| Best Used For | 3rd-party vendor charts (Datadog, Kafka, Redis) | Enterprise internal microservice fleet across SDLC environments |
๐งญ Step-by-Step Operational Playbook: The โHelm Base + Kustomize Overlayโ Promotion Workflow
Follow this step-by-step operational procedure to package third-party and internal applications cleanly across dev, staging, and prod without copy-pasting YAML files:
Step 1: Scaffold the Base Kustomization & Hash-Generated ConfigMap
- Plain-English Goal: Use
configMapGeneratorinbase/kustomization.yamlso every config change appends a new SHA-256 suffix (e.g.,app-config-8f9d2b) and automatically triggers a zero-downtime Kubernetes rolling restart. - Action:
mkdir -p k8s/base k8s/overlays/dev k8s/overlays/prod kubectl kustomize k8s/base
Step 2: Create Environment Overlays Using Strategic Merge & JSON6902 Patches
- Plain-English Goal: Keep 95% of the YAML identical in
base/, and only patch replica counts, CPU/memory limits, and hostnames inoverlays/prod/kustomization.yaml. - Action:
# Render and diff Dev vs Prod manifests locally before committing to Git: diff -u <(kubectl kustomize k8s/overlays/dev) <(kubectl kustomize k8s/overlays/prod)
Step 3: Validate Rendered Manifests Against Kubernetes Schemas in CI
- Plain-English Goal: Catch indentation typos or invalid API versions before merging to
mainusingkubeconform. - Action:
kubectl kustomize k8s/overlays/prod | kubeconform -strict -summary
Step 4: Safe Helm Upgrade with Atomic Rollback Protection
- Plain-English Goal: When deploying third-party Helm charts, always run
helm difffirst and use--atomic --timeout 5m(or ArgoCD Sync Hooks) so failed readiness probes automatically roll back to the last known good revision. - Action:
helm history payments-api -n payments-prod helm upgrade payments-api ./charts/payments -n payments-prod -f values-prod.yaml --atomic --timeout 5m
๐ ๏ธ Real-World Troubleshooting & Failure Modes
1. Helm Release Stuck in pending-upgrade or pending-install
- Symptom: A CI/CD pipeline fails or gets canceled midway through
helm upgrade. Subsequent runs fail with:Error: another operation (install/upgrade/rollback) is in progress. - Root Cause: Helm places a lock record in the release Secret. If the CI job crashes before Helm finishes, the lock is never released.
- Fix: Inspect the Secrets in the namespace and remove the stuck revision:
# Find stuck secret kubectl get secrets -n workloads -l owner=helm # Roll back to previous clean revision helm rollback my-app <previous-clean-revision> -n workloads
2. Kustomize patch Target Name Mismatch
- Symptom: You add a patch in
overlays/prod/kustomization.yaml, but the production output never changes. - Root Cause: If
namePrefix: prod-was applied, the Deploymentโs effective name in the pipeline might have changed, causing the patch targetname: order-serviceto not match. - Fix: Ensure patches either run before transformers or target kinds with regex/wildcards:
patches: - target: kind: Deployment name: ".*order-service"
๐ Knowledge Check & Real-World Interview Scenarios
A junior engineer updates a database password in an existing Kubernetes Secret and applies it with kubectl apply -f secret.yaml. They notify the team that the password rotation is complete. Two hours later, the application database crashes because 50% of the pods were still using the old password, while new pods were using the new password.
Why did this desynchronization occur, and how does Kustomizeโs secretGenerator prevent this incident?
โ Answer & Explanation
The Mechanism:
- In standard Kubernetes, updating a Secret or ConfigMap in-place does not restart existing Pods. If containers read environment variables from
envFrom: secretRef, environment variables are injected only once at container startup. The running pods continued using the cached old password in memory. - When the Horizontal Pod Autoscaler (HPA) spun up new Pods, the new Pods booted with the new password. This created an active split-brain state where different pods connected using different credentials.
How Kustomize Solves It:
Kustomizeโs secretGenerator appends a unique content hash to the Secret name (e.g. db-creds-f8a92b). Updating the password in Git generates a brand-new Secret (db-creds-1b4e9c) and automatically updates the Deploymentโs secretRef. Kubernetes detects the PodTemplate change and triggers a standard zero-downtime rolling update, guaranteeing all pods transition synchronously and atomically without split-brain behavior!
Your security team mandates that every pod in the entire enterprise must have securityContext: runAsNonRoot: true and a PodDisruptionBudget. You want to deploy the open-source Cert-Manager Helm chart from Jetstack. However, the upstream chart does not expose a parameter for your companyโs proprietary audit annotations.
How do you solve this using the Helm + Kustomize Hybrid pattern in GitOps without maintaining a painful fork of the upstream chart?
โ Answer & Explanation
The Architectural Solution: Use the Helm + Kustomize Hybrid Pattern (supported natively by ArgoCD and Kustomize 5.0+):
- Rather than maintaining a separate forked Git copy of Cert-Managerโs chart (which creates huge maintenance overhead and blocks upstream security updates), consume the official upstream Helm chart directly.
- Use Kustomizeโs
helmChartsgenerator to render the upstream chart dynamically using the vendorโs standardvalues.yaml. - Write a Kustomize Strategic Merge Patch or JSON 6902 patch that surgically injects your enterprise-mandated
securityContextand audit annotations on top of the rendered output. - Result: You receive 100% of upstream vendor updates and bug fixes effortlessly while strictly enforcing 100% of internal enterprise security compliance.