Helm Hour 6: Chart Architecture in Practice
- Choose chart granularity for a multi-service app and explain the trade-offs of umbrella chart versus “single-service chart + orchestration layer (Helmfile / Argo CD / Flux)”, version coupling and blast radius, and use library chart to eliminate duplicate templates.
- Design base → env → region multi-file values layering that masters the merge rules (deep merge for maps, whole replacement for lists,
nulland key deletion),globalthe scope of, knowing why “if prod” must not be written into templates, and why--setis only for temporary overrides. - Move secrets out of values: compare helm-secrets + SOPS (split into 3 plugins under Helm 4),External Secrets Operator (v2.15.0,
external-secrets.io/v1),Secrets Store CSI Driver (v1.6.2), and explain the leak risk of “a rendered Secret being written into the release Secret”. - Understand the real execution algorithm of Helm 4.3 hooks (sorted by weight → name, default
before-hook-creation, each hook waiting individually--timeout, failure deletion policy), and write a re-entrant database migration hook. - Per Helm 4 requirements, wrap Kustomize as a
postrenderer/v1plugin, and understand the new problems caused by Helm 4 handing hooks to the post-renderer by default (combined strategy). - Managing CRDs and Operators:
crds/The directory is created only on first install and never upgraded or deleted; split CRDs into their own chart, and design CRD upgrades and the “Operator before CR” order. - For zero-downtime upgrades, design for compatibility: selectors are immutable, renaming a resource equals delete and recreate,
helm.sh/resource-policy: keep, templating PDB and rolling parameters,.Capabilities.APIVersions, values backward compatibility and deprecation notices, and complete one architecture review using a review checklist.
1-hour time allocation table
| # | Time | Module | Core content | Animations / interaction | Lab (kind cluster lab) |
|---|---|---|---|---|---|
| 0 | Before class | Prep: multi-service sample project | Check the lab cluster, Helm 4.3, kubectl kustomize; set up ~/helm-lab/shop-platform directory skeleton | Architecture maturity self-assessment (10 items) | Directory and tooling self-check |
| 1 | 00–07 | Chart granularity: umbrella vs single-service | Umbrella's single-release atomicity and large blast radius; single-service chart + Helmfile/GitOps; library chart; version coupling | Granularity decision tool: change one service, how many releases are affected? | shop-lib + shop-api/web/db three charts |
| 2 | 07–15 | Values layering and multiple environments | base/env/region overlays, merge rules, global, structured vs flat, forbidding environment branches,--set boundary of | values overlay simulator (layer-by-layer merge) | dev/prod × canadacentral render comparison |
| 3 | 15–22 | Secrets: helm-secrets, SOPS and External Secrets | release Secret leakage surface, SOPS+age, splitting helm-secrets into Helm 4 plugins, ESO, Secrets Store CSI | Secret flow: who can see plaintext | ESO (fake provider) + inspect the release Secret |
| 4 | 22–30 | Hooks and Jobs: migration, backup and testing | 9 hook events, weight ordering, delete policies, output-log-policy, hooks not managed by the release, timeouts | Core animation: pre-upgrade −5 → 0 → 5 → main body → post-upgrade → failure branch | Migration hook + failure injection |
| 5 | 30–37 | post-renderer and Kustomize (Helm 4 plugin) | postrenderer/v1 plugin structure, stdin/stdout protocol, combined strategy, and trade-offs versus changing the chart | Rendering pipeline: templates → hooks split → plugin → apply | kustomize-pr plugin to patch third-party charts |
| 6 | 37–45 | CRD and Operator chart management | crds/ semantics, separate CRD chart, upgrade strategy, Operator → CR order, keep policy | crds/ vs templates/ CRD lifecycle comparison | CRD version upgrade demo |
| 7 | 45–53 | Zero-downtime upgrades and compatibility design | immutable fields, rename = delete and recreate, keep, PDB/rolling parameters, APIVersions, values deprecation | Upgrade change classifier: safe / recreate / fail | Upgrade drill + continuous request probing |
| 8 | 53–60 | Comprehensive architecture review | Review checklist, failure modes, troubleshooting tree | Interactive review scoring + troubleshooting tree | Review shop-platform |
| — | After class | Cheat sheet · Comprehensive lab | library chart + 3 service charts + values layering + ESO + migration hook + Kustomize plugin + zero-downtime upgrade | Final quiz (12 questions) | Comprehensive lab |
Knowledge Coverage Matrix
| Target skills | M1 | M2 | M3 | M4 | M5 | M6 | M7 | M8 | Key commands | Lab |
|---|---|---|---|---|---|---|---|---|---|---|
| Choose chart granularity and orchestration approach | ✓ | · | · | · | · | ✓ | · | ✓ | helm dependency,helmfile apply | shop-platform directory |
| library chart reuses templates | ✓ | · | · | · | · | · | ✓ | ✓ | include "shop-lib.*" | shop-lib |
| multi-environment values layering | · | ✓ | ✓ | · | · | · | ✓ | ✓ | -f base -f env -f region | render comparison |
| secrets not in values / release | · | ✓ | ✓ | ✓ | · | · | · | ✓ | helm get manifest, ESO | ExternalSecret |
| hooks: migration and testing | · | · | · | ✓ | ✓ | · | ✓ | ✓ | helm get hooks,helm test | db-migrate Job |
| post-renderer plugin | · | · | · | ✓ | ✓ | · | · | ✓ | helm plugin install,--post-renderer | kustomize-pr |
| CRD and Operator lifecycle | ✓ | · | ✓ | · | · | ✓ | ✓ | ✓ | --skip-crds,kubectl apply --server-side | CRD upgrade |
| zero-downtime upgrade and compatibility | · | ✓ | · | ✓ | · | ✓ | ✓ | ✓ | helm diff,--rollback-on-failure | upgrade drill |
| architecture review and troubleshooting | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | helm history,helm status | review checklist |
Topics excluded from this lesson (and where to learn them)
| Topic | Why it is not in this lesson | Where to learn |
|---|---|---|
| Template syntax, named templates, dependencies and basic library chart syntax | Covered in lesson 2; this lesson only covers its architectural use | Hour 2 |
| Installation and basic usage of Helmfile, Argo CD and Flux | Covered in lesson 5; this lesson only discusses its design trade-offs “as an orchestration layer” | Hour 5 |
| Identity configuration for Azure Key Vault / AWS Secrets Manager (Workload Identity, Pod Identity) | Cloud platform details are in lessons 3 and 4; this lesson's lab demonstrates with ESO's fake provider on kind | Lesson 3 · Lesson 4 |
| Deep troubleshooting of hook failures, pending-upgrade and SSA conflicts | This lesson covers only the design level; troubleshooting is covered systematically in lesson 7 | Hour 7 |
| Kubernetes Deployment rollouts, PDB and StatefulSet principles | Covered in the K8s course | Kubernetes 8 hours Lesson 2 |
| Writing Operators (Kubebuilder / Operator SDK) | Beyond the scope of Helm | Kubebuilder Book |
How to use these course materials
Principles · diagrams · animations · commands · labs · production cases · troubleshooting · quizzes · voice · video. For this architecture course, it is recommended to read the comparison table in “Principles” and the “Production cases” first, then do the labs.
A quiz score ≥ 70% or clicking “Mark this module complete” counts toward progress, saved in this browser (cleared on refresh when local storage is blocked).
The “Voice” page reads the narration script aloud using the browser's built-in Web Speech API (en-US); without a Chinese voice pack, the narration script can still be read or passed to a TTS tool.
type: postrenderer/v1 plugin (--post-renderer given a plugin name rather than an executable path); by default Helm 4 hands hooks and regular templates merged to the post-renderer (Helm 3 never passed hooks to the post-renderer); --atomic renamed to --rollback-on-failure,--force renamed to --force-replace (old names still work but are marked deprecated); --wait when omitted, it is hookOnly, and writing it alone --wait as watcher (kstatus); new installs default to server-side apply, and the upgrade --server-side default auto (keeps the previous setting). hook adds helm.sh/hook-output-log-policy annotation. When using Helm 3.22, follow the documentation for that version.Module 0 · Prep: multi-service sample project (complete before class)
- CompletedLesson 5: understand chart CI, OCI publishing, Helmfile and GitOps (this lesson's m1 uses them as the “orchestration layer” and does not repeat installation details).
- kind cluster
lab(same as Kubernetes course, 1 control-plane + 2 workers); Helm 4.3.x, kubectl 1.37 (bundledkubectl kustomize). - Sample application shop (K8s course):
api=ghcr.io/stefanprodan/podinfo:6.17.0(port 9898),web=nginx:1.29-alpine,db=postgres:17. This lesson splits them into 3 service charts + 1 library chart. - Labs run on a local kind cluster,with no cloud costs; m3 discusses Azure Key Vault / AWS Secrets Manager only in “Production cases”, and no cloud resources are needed.
Step 1: check tools and cluster
helm version --short kubectl version --client | head -1 kubectl kustomize --help | head -1 kind get clusters kubectl config use-context kind-lab kubectl get nodes
v4.3.2+g<commit> Client Version: v1.37.1 Build a set of KRM resources using a 'kustomization.yaml' file. lab Switched to context "kind-lab". NAME STATUS ROLES AGE VERSION lab-control-plane Ready control-plane 5d v1.37.0 lab-worker Ready <none> 5d v1.37.0 lab-worker2 Ready <none> 5d v1.37.0
If the cluster has been deleted, use the kind-lab.yaml to run kind create cluster --config kind-lab.yaml (kind v0.33.0 default image kindest/node:v1.37.0). If Helm is not installed or is still Helm 3: curl -fsSL https://raw.githubusercontent.com/helm/helm/main/scripts/get-helm-4 | bash.
Step 2: set up the shop-platform repo skeleton
Parallel to lesson 2's ~/helm-lab/myapp,common-lib create a new “platform repository”. The directory structure is this lesson's architecture answer; take a look at the full picture first:
~/helm-lab/shop-platform/ ├── charts/ │ ├── shop-lib/ # type: library —— labels, names, Deployment/Service/PDB skeleton │ ├── shop-api/ # podinfo; includes db-migrate pre-upgrade hook, ExternalSecret │ ├── shop-web/ # nginx frontend │ └── shop-db/ # postgres:17 StatefulSet (for labs; production should use a managed database) ├── envs/ │ ├── base/ # shared by all environments: common.yaml (global) + one file per service │ ├── dev/ prod/ # environment differences: only keys that differ from base │ └── region/canadacentral.yaml ├── secrets/ # only SOPS-encrypted files or ExternalSecret references; never plaintext ├── plugins/kustomize-pr/ # Helm 4 postrenderer/v1 plugin ├── overlays/prod/ # Kustomize patches handed to the post-renderer └── helmfile.yaml.gotmpl # orchestration layer: order of the 3 releases and values overlay (Helmfile v1 templated files need the .gotmpl suffix)
mkdir -p ~/helm-lab/shop-platform/{charts,envs/base,envs/dev,envs/prod,envs/region,secrets,plugins/kustomize-pr,overlays/prod}
cd ~/helm-lab/shop-platform
git init -q 2>/dev/null || true
helm create charts/shop-api >/dev/null && helm create charts/shop-web >/dev/null && helm create charts/shop-db >/dev/null
helm create charts/shop-lib >/dev/null
# library chart only keeps _helpers-type files
rm -rf charts/shop-lib/templates/* charts/shop-lib/values.yaml
sed -i 's/^type: application/type: library/' charts/shop-lib/Chart.yaml
# service charts first clear their templates; rewritten later in m1 using the library
for c in api web db; do rm -rf charts/shop-$c/templates/*; done
kubectl create namespace shop --dry-run=client -o yaml | kubectl apply -f -
tree -L 2 . 2>/dev/null || find . -maxdepth 2 -type d
kubectl apply kubectl. If the namespace shop still has kubectl-created api/web/db, a Helm install of a same-named resource will report invalid ownership metadata. Before the lab, delete them first (kubectl -n shop delete deploy,sts,svc --all), or use a new namespace shop other than shop-dev. This lesson by default works in shop from scratch.Warm-up: answer from memory (30 seconds)
Where does a release's state live? What is inside it?
By default it is stored in a Secret in the release namespace sh.helm.release.v1.<release>.v<N> (a gzip + base64-encoded release object) containing the chart, user-supplied values,the full rendered manifest, hooks and notes. This fact foreshadows m3 (secret leakage surface).
Can a child chart read the parent chart's values?
No. A parent chart can use <child-chart-name>: to pass values to a child chart; only global: values under global are visible to both parent and child. This rule is key for m1 to decide whether an umbrella is appropriate.
Architecture maturity self-assessment (10 items)
Tick the items that your team has currently achieved items (results are saved in this browser). Come back and tick again after finishing this lesson.
Module 1 · Chart granularity: umbrella vs single-service
- Clarify the real semantics of an umbrella chart: the parent chart and all child charts are rendered into one release, stored in one release Secret, and use one
--timeoutrelease unit for upgrades and rollbacks. - Compare three architectures: umbrella, single-service chart + orchestration layer (Helmfile / Argo CD ApplicationSet / Flux HelmRelease
dependsOn), hybrid (“platform umbrella + business single-service”). - Use a library chart (
type: library) to unify labels, names and the Deployment/Service/PDB skeleton, and understand the “coupling radius” of library version upgrades.
Chart.lock,global, library chart syntax; Helmfile and GitOps from lesson 5. Importance:★★★★★ (once architecture decisions are made, migration cost is very high)What: two basic forms
- Umbrella chart: a parent chart containing only
Chart.yamlofdependenciesand a few glue templates; child charts (shop-api, shop-web, shop-db) are placed incharts/below, or pulled from a repository.helm upgrade shop ./shop-umbrellaRenders all templates in one pass. - Single-service chart + orchestration layer: each service is one chart and one release (
shop-api,shop-web,shop-db), with Helmfile, Argo CD or Flux deciding “what to install, in what order, with which values”. - library chart:
type: library, and it cannot be installed (helm installreportslibrary charts are not installable), so it only providesdefinetemplates. It solves “duplication”, not “orchestration”.
Why: what granularity determines
Helm's guarantees are all built around release as the unit: one upgrade diffs, applies and waits on all resources together; after a failure --rollback-on-failure rolls back the entire release to the last successful revision; helm history and the release Secret is also one per release. So deciding “which things go into the same release” is essentially deciding:
| Dimension | Umbrella (one release) | Single-service chart (N releases) |
|---|---|---|
| Atomicity | Strong: either all upgrade successfully, or all roll back together | Weak: the orchestration layer must handle partial success (Helmfile one release at a time; Argo CD sync wave) |
| Blast radius | Changing one annotation on web also re-renders, diffs and waits on api and db | Only affects the modified service |
| Version coupling | Child chart versions are locked by the parent Chart.lock , so any child chart release requires “republishing the parent chart” | Each service has independent SemVer and independent rollback |
| Shared values | global Naturally shared; child charts cannot read each other's values | The orchestration layer passes the same envs/*.yaml to multiple releases |
| Release Secret size | All child chart templates + rendered manifests in one Secret; higher risk of approaching the 1 MiB limit | Spread across services, each one small |
| Team ownership | The platform team controls the parent chart; service teams submit PRs | Service teams own their own chart and release cadence |
| Execution order | Helm installs resources sorted by kind,no inter-service dependency order (only hook weights) | Helmfile needs, Argo CD sync waves, Flux dependsOn can express “db before api” |
How: the real process of umbrella rendering
When Helm loads the parent chart, it puts charts/ under (or the dependency-resolved) child charts, loading them as Chart.Dependencies(); condition/tags first decides which child charts are enabled; then values are merged as “child chart defaults ← the parent chart's <child-name>: section ← user values”, and global is copied into each child chart; all templates are put into the same template namespace rendered together (therefore define names must carry the chart prefix); finally all manifests are sorted by kind install order (Namespace → … → Deployment → …) and applied as one release.
When: how to choose
- Use umbrella: a set of components must be released at the same version and maintained by the same team, for example a “product distribution” (an on-prem installer delivered to customers), a service plus its dedicated cache/sidecar config, or a one-click full stack for a test environment.
- Use single-service chart + orchestration layer: multiple teams, independent release cadence, per-service rollback, and a growing number of services (the recommended answer for shop).
- Use library chart: worth doing once there are ≥2 in-house charts; keeps labels, probes, PDBs and securityContext consistent across all services.
- Hybrid: infrastructure (ingress, cert-manager, ESO, monitoring) each as one release (do not wrap third-party charts in another umbrella), business services as single-service charts, sharing a library.
Comparison with similar technologies
| Helm umbrella | Helmfile | Argo CD ApplicationSet / app-of-apps | Flux HelmRelease | |
|---|---|---|---|---|
| Unit | 1 release | N releases (executed one by one by the client) | N Applications (each renders one chart) | N HelmReleases (call the Helm SDK inside the controller) |
| Order | only kind order + hooks | needs form a DAG | sync waves / dependency health | dependsOn (wait for dependencies to be Ready) |
| State | release Secret | release Secret (Helmfile is stateless) | Argo CD uses helm template applies itself after rendering,no release Secret,helm list cannot see | release Secret (the real Helm release) |
global or by repeating values in the parent chart. ③ “Upgrading a library chart only changes templates and won't affect production” is wrong: once the library changes, every chart that depends on it shows a diff on its next release, and changing label or name rules leads to selector conflicts or resource recreation (see module 7).Architecture diagram: two shop architectures
Flowchart: the path of a “change web only” change under the two architectures
Interactive simulator: granularity decision tool, how many releases does one change affect?
Choose an architecture and a change type, then click “Run release”. The simulator steps through what Helm actually does: which charts must be repackaged,Chart.lock whether they changed, which releases produce new revisions, which resources to wait for, and the scope of rollback on failure. The terminal below shows the matching real commands and output.
Core commands and parameters
| Command | Purpose | Key parameters / notes |
|---|---|---|
helm dependency update CHART | By Chart.yaml resolves dependencies, downloads to charts/, writes Chart.lock | used by the library chart repository: file://../shop-lib; use in CI helm dependency build restores per lock |
helm dependency list CHART | View dependency status | STATUS is ok / missing / wrong version |
helm template REL CHART | Local render, check the library template expansion result | --show-only templates/deployment.yaml,-f |
helm install --dry-run=server | connects to the cluster for server-side validation (including lookup) | Helm 4 dry-run value client/server |
helmfile -e ENV apply | by needs diff + upgrade multiple releases in order | -l name=shop-web handles only one; requires the helm-diff plugin |
helm list -n shop -o table | Confirm the number of releases and revisions | -a Show failed/pending |
cd ~/helm-lab/shop-platform helm dependency update charts/shop-api helm dependency list charts/shop-api ls charts/shop-api/charts/
Saving 1 charts Deleting outdated charts NAME VERSION REPOSITORY STATUS shop-lib 0.1.0 file://../shop-lib ok shop-lib-0.1.0.tgz
How to verify:Chart.lock contains digest; modify shop-lib without bumping the version and run again dependency update will repackage the same version. In CI, please bump the version on every library change, otherwise different machines produce tgz files with different contents. Common mistakes: forgetting to add charts/*.tgz to .gitignore or forgetting to run in CI dependency build, resulting in found in Chart.yaml, but missing in charts/ directory.
# render only one file, to confirm the library template expands correctly helm template shop-api charts/shop-api --show-only templates/deployment.yaml | head -30 # view 3 releases at once helm list -n shop
---
# Source: shop-api/templates/deployment.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
name: shop-api
labels:
helm.sh/chart: shop-api-0.1.0
app.kubernetes.io/name: shop-api
app.kubernetes.io/instance: shop-api
...
NAME NAMESPACE REVISION UPDATED STATUS CHART APP VERSION
shop-api shop 1 ... deployed shop-api-0.1.0 6.17.0
shop-db shop 1 ... deployed shop-db-0.1.0 17
shop-web shop 1 ... deployed shop-web-0.1.0 1.29
Production use: treat helm list the release count as a “release unit list”, aligned with the service catalog (Backstage, etc.); one release maps to one owner.
Lab 1: shop-lib + three service charts (about 8 minutes)
~/helm-lab/shop-platform under):
apiVersion: v2 name: shop-lib description: shared templates for the shop platform (not installable) type: library version: 0.1.0
{{- define "shop-lib.name" -}}
{{- default .Chart.Name .Values.nameOverride | trunc 63 | trimSuffix "-" -}}
{{- end -}}
{{/* Resource names take only the chart name, not the release name: changing the release name will not rename resources (module 7) */}}
{{- define "shop-lib.fullname" -}}
{{- default (include "shop-lib.name" .) .Values.fullnameOverride | trunc 63 | trimSuffix "-" -}}
{{- end -}}
{{/* Selector labels: never changed once released */}}
{{- define "shop-lib.selectorLabels" -}}
app.kubernetes.io/name: {{ include "shop-lib.name" . }}
app.kubernetes.io/instance: {{ .Release.Name }}
{{- end -}}
{{- define "shop-lib.labels" -}}
helm.sh/chart: {{ printf "%s-%s" .Chart.Name .Chart.Version | replace "+" "_" | trunc 63 | trimSuffix "-" }}
{{ include "shop-lib.selectorLabels" . }}
app.kubernetes.io/version: {{ .Chart.AppVersion | quote }}
app.kubernetes.io/managed-by: {{ .Release.Service }}
app.kubernetes.io/part-of: shop
{{- with dig "environment" "" (.Values.global | default dict) }}
shop.example.com/env: {{ . }}
{{- end }}
{{- end -}}
{{- define "shop-lib.deployment" -}}
apiVersion: apps/v1
kind: Deployment
metadata:
name: {{ include "shop-lib.fullname" . }}
labels:
{{- include "shop-lib.labels" . | nindent 4 }}
spec:
replicas: {{ .Values.replicaCount }}
revisionHistoryLimit: 5
minReadySeconds: {{ .Values.rollout.minReadySeconds }}
strategy:
type: RollingUpdate
rollingUpdate:
maxSurge: {{ .Values.rollout.maxSurge }}
maxUnavailable: {{ .Values.rollout.maxUnavailable }}
selector:
matchLabels:
{{- include "shop-lib.selectorLabels" . | nindent 6 }}
template:
metadata:
labels:
{{- include "shop-lib.labels" . | nindent 8 }}
{{- with .Values.podAnnotations }}
annotations:
{{- toYaml . | nindent 8 }}
{{- end }}
spec:
terminationGracePeriodSeconds: 30
securityContext:
runAsNonRoot: {{ .Values.securityContext.runAsNonRoot }}
seccompProfile: { type: RuntimeDefault }
containers:
- name: {{ .Values.containerName | default (include "shop-lib.name" .) }}
image: "{{ .Values.image.repository }}:{{ .Values.image.tag | default .Chart.AppVersion }}"
imagePullPolicy: {{ .Values.image.pullPolicy | default "IfNotPresent" }}
{{- with .Values.args }}
args:
{{- toYaml . | nindent 12 }}
{{- end }}
ports:
- name: http
containerPort: {{ .Values.containerPort }}
{{- with .Values.env }}
env:
{{- toYaml . | nindent 12 }}
{{- end }}
{{- with .Values.envFrom }}
envFrom:
{{- toYaml . | nindent 12 }}
{{- end }}
readinessProbe:
httpGet: { path: {{ .Values.probes.readinessPath }}, port: http }
periodSeconds: 5
livenessProbe:
httpGet: { path: {{ .Values.probes.livenessPath }}, port: http }
periodSeconds: 10
lifecycle:
preStop:
sleep: { seconds: 5 }
resources:
{{- toYaml .Values.resources | nindent 12 }}
{{- end -}}
{{- define "shop-lib.service" -}}
apiVersion: v1
kind: Service
metadata:
name: {{ include "shop-lib.fullname" . }}
labels:
{{- include "shop-lib.labels" . | nindent 4 }}
spec:
type: ClusterIP
selector:
{{- include "shop-lib.selectorLabels" . | nindent 4 }}
ports:
- name: http
port: {{ .Values.service.port }}
targetPort: http
{{- end -}}
{{- define "shop-lib.pdb" -}}
{{- if .Values.pdb.enabled }}
apiVersion: policy/v1
kind: PodDisruptionBudget
metadata:
name: {{ include "shop-lib.fullname" . }}
labels:
{{- include "shop-lib.labels" . | nindent 4 }}
spec:
maxUnavailable: {{ .Values.pdb.maxUnavailable }}
selector:
matchLabels:
{{- include "shop-lib.selectorLabels" . | nindent 6 }}
{{- end }}
{{- end -}}apiVersion: v2
name: shop-api
description: shop API (podinfo)
type: application
version: 0.1.0
appVersion: "6.17.0"
dependencies:
- name: shop-lib
version: 0.1.0
repository: file://../shop-lib
replicaCount: 2
image:
repository: ghcr.io/stefanprodan/podinfo
tag: "" # when empty, use appVersion
containerName: podinfo
containerPort: 9898
args: ["./podinfo", "--port=9898", "--level=info"]
service: { port: 9898 }
probes: { readinessPath: /readyz, livenessPath: /healthz }
rollout: { maxSurge: 1, maxUnavailable: 0, minReadySeconds: 5 }
pdb: { enabled: true, maxUnavailable: 1 }
securityContext: { runAsNonRoot: true }
resources:
requests: { cpu: 50m, memory: 64Mi }
limits: { memory: 128Mi }
env: []
envFrom: []
podAnnotations: {}
cat > charts/shop-api/templates/deployment.yaml <<'EOF'
{{ include "shop-lib.deployment" . }}
EOF
cat > charts/shop-api/templates/service.yaml <<'EOF'
{{ include "shop-lib.service" . }}
EOF
cat > charts/shop-api/templates/pdb.yaml <<'EOF'
{{ include "shop-lib.pdb" . }}
EOF
helm dependency update charts/shop-api
helm lint charts/shop-api
Saving 1 charts Deleting outdated charts ==> Linting charts/shop-api [INFO] Chart.yaml: icon is recommended 1 chart(s) linted, 0 chart(s) failed
The podinfo image runs as a non-root user (UID 100), satisfying runAsNonRoot.
sed 's/shop-api/shop-web/; s/shop API (podinfo)/shop frontend (nginx)/; s/6.17.0/1.29-alpine/' charts/shop-api/Chart.yaml > charts/shop-web/Chart.yaml
cp charts/shop-api/templates/*.yaml charts/shop-web/templates/
cat > charts/shop-web/values.yaml <<'EOF'
replicaCount: 2
image: { repository: nginx, tag: "" }
containerName: nginx
containerPort: 80
args: []
service: { port: 80 }
probes: { readinessPath: /, livenessPath: / }
rollout: { maxSurge: 1, maxUnavailable: 0, minReadySeconds: 5 }
pdb: { enabled: true, maxUnavailable: 1 }
securityContext: { runAsNonRoot: false } # the official nginx image starts the master process as root; for production you can switch to nginxinc/nginx-unprivileged
resources:
requests: { cpu: 20m, memory: 32Mi }
limits: { memory: 64Mi }
env: []
envFrom: []
podAnnotations: {}
EOF
helm dependency update charts/shop-web >/dev/null && helm lint charts/shop-web | tail -1apiVersion: v1
kind: Service
metadata:
name: shop-db
labels: { app.kubernetes.io/name: shop-db, app.kubernetes.io/instance: {{ .Release.Name }} }
spec:
clusterIP: None
selector: { app.kubernetes.io/name: shop-db, app.kubernetes.io/instance: {{ .Release.Name }} }
ports: [{ name: pg, port: 5432 }]
---
apiVersion: apps/v1
kind: StatefulSet
metadata:
name: shop-db
labels: { app.kubernetes.io/name: shop-db, app.kubernetes.io/instance: {{ .Release.Name }} }
spec:
serviceName: shop-db
replicas: 1
selector:
matchLabels: { app.kubernetes.io/name: shop-db, app.kubernetes.io/instance: {{ .Release.Name }} }
template:
metadata:
labels: { app.kubernetes.io/name: shop-db, app.kubernetes.io/instance: {{ .Release.Name }} }
spec:
containers:
- name: postgres
image: "postgres:{{ .Values.image.tag }}"
ports: [{ name: pg, containerPort: 5432 }]
env:
- { name: POSTGRES_DB, value: shop }
- { name: POSTGRES_USER, value: shop }
- name: POSTGRES_PASSWORD
valueFrom: { secretKeyRef: { name: {{ .Values.credentialsSecret }}, key: password } }
- { name: PGDATA, value: /var/lib/postgresql/data/pgdata }
readinessProbe:
exec: { command: ["pg_isready", "-U", "shop", "-d", "shop"] }
periodSeconds: 5
volumeMounts: [{ name: data, mountPath: /var/lib/postgresql/data }]
volumeClaimTemplates:
- metadata: { name: data }
spec:
accessModes: ["ReadWriteOnce"]
resources: { requests: { storage: {{ .Values.storage }} } }
cat > charts/shop-db/Chart.yaml <<'EOF'
apiVersion: v2
name: shop-db
type: application
version: 0.1.0
appVersion: "17"
EOF
cat > charts/shop-db/values.yaml <<'EOF'
image: { tag: "17" }
credentialsSecret: shop-db-credentials # generated by the module 3 ExternalSecret; create manually here for now
storage: 1Gi
EOF
# only for this lab: create the password Secret manually first (module 3 changes this to ESO generation)
kubectl -n shop create secret generic shop-db-credentials --from-literal=password="$(openssl rand -hex 16)"helm upgrade --install shop-db charts/shop-db -n shop --wait --timeout 5m helm upgrade --install shop-api charts/shop-api -n shop --wait helm upgrade --install shop-web charts/shop-web -n shop --wait helm list -n shop kubectl -n shop get deploy,sts,svc,pdb
NAME NAMESPACE REVISION STATUS CHART APP VERSION shop-api shop 1 deployed shop-api-0.1.0 6.17.0 shop-db shop 1 deployed shop-db-0.1.0 17 shop-web shop 1 deployed shop-web-0.1.0 1.29-alpine NAME READY UP-TO-DATE AVAILABLE deployment.apps/shop-api 2/2 2 2 deployment.apps/shop-web 2/2 2 2 NAME READY statefulset.apps/shop-db 1/1 ... NAME MIN AVAILABLE MAX UNAVAILABLE ALLOWED DISRUPTIONS poddisruptionbudget.policy/shop-api N/A 1 1 poddisruptionbudget.policy/shop-web N/A 1 1
mkdir -p /tmp/shop-umbrella/templates
cat > /tmp/shop-umbrella/Chart.yaml <<EOF
apiVersion: v2
name: shop
version: 0.1.0
dependencies:
- { name: shop-api, version: 0.1.0, repository: "file://$HOME/helm-lab/shop-platform/charts/shop-api" }
- { name: shop-web, version: 0.1.0, repository: "file://$HOME/helm-lab/shop-platform/charts/shop-web" }
- { name: shop-db, version: 0.1.0, repository: "file://$HOME/helm-lab/shop-platform/charts/shop-db", condition: shop-db.enabled }
EOF
helm dependency update /tmp/shop-umbrella >/dev/null
helm template shop /tmp/shop-umbrella | grep -E '^kind:|^# Source' | paste - - | head
# Source: shop/charts/shop-api/templates/pdb.yaml kind: PodDisruptionBudget # Source: shop/charts/shop-web/templates/pdb.yaml kind: PodDisruptionBudget # Source: shop/charts/shop-api/templates/service.yaml kind: Service ...
Note app.kubernetes.io/instance becomes shop (parent release name); the three child charts share one release. Delete the temporary directory: rm -rf /tmp/shop-umbrella.
helm -n shop uninstall shop-web shop-api shop-db; kubectl -n shop delete pvc -l app.kubernetes.io/name=shop-db.Case 1: umbrella causes a “site-wide rollback”
Problem: An e-commerce team put 14 microservices into one umbrella chart, using --rollback-on-failure --timeout 10m to release. One change touched only the recommendation service's config, but the new Pods of the order service were Pending due to insufficient node resources. After 10 minutes the entire release was rolled back, and the recommendation fix was reverted along with it. Approach: Split into 14 single-service charts sharing a library; use an Argo CD ApplicationSet to generate Applications from directories, ordered by sync wave. Configuration: each Application points to charts/<svc> and envs/<env>.yaml. Limitations: The guarantee of “all succeed together” is lost; cross-service contract changes must be released in stages in a backward-compatible way (module 7).
Case 2: a scenario suited to umbrella, the on-prem delivery package
Problem: An ISV needs to deliver the product for installation in the customer's cluster; the customer only wants to run one helm install. Approach: umbrella chart pins all component versions (Chart.lock committed to the repo), and the parent chart uses global.imageRegistry to support a private image registry, and uses condition to let the customer turn off the bundled database in favour of a managed database. Limitations: The release Secret grows with the number of components; the product team must manage the parent chart's version as the “product version”.
Case 3: library chart version upgrade causes a selector conflict
Problem: The platform team, in shop-lib 0.2.0's selectorLabels added a new label to app.kubernetes.io/component, and after service teams upgraded the dependency, helm upgrade reports field is immutable. Approach: Roll back selectorLabels; put the new labels only in labels; note in the library CHANGELOG that “selectorLabels never change”, and use helm template in CI to compare old and new selectors (the review checklist of module 8). Limitations: When the selector truly must change, you can only create a new Deployment name or do a blue-green migration.
Common errors and fixes
Error: library charts are not installable
Cause: on type: library chart, ran helm install.
Fix: install the application chart that depends on it. A library chart can only be used as a dependency.
Error: found in Chart.yaml, but missing in charts/ directory: shop-lib
Cause: CI or a freshly cloned repo did not run the dependency download (charts/*.tgz usually not committed).
helm dependency build charts/shop-api # restore per Chart.lock helm dependency list charts/shop-api
Fix: run before lint/package in CI dependency build; or add when installing --dependency-update.
Error: template: shop-api/templates/deployment.yaml:1:3: executing ... error calling include: template: no template "shop-lib.deployment" associated with template "gotpl"
Cause: no such define in the library (typo, file name not starting with _ is treated as an ordinary template, or charts/ in the charts directory is an old tgz version).
tar -tzf charts/shop-api/charts/shop-lib-0.1.0.tgz grep -rn 'define "shop-lib' charts/shop-lib/templates/
Fix: correct the name, bump the library version, and then re- dependency update.
Error: INSTALLATION FAILED: Unable to continue with install: Deployment "shop-api" in namespace "shop" exists and cannot be imported into the current release: invalid ownership metadata
Cause: a resource with the same name was created by kubectl or another release (for example, when migrating from umbrella to single-service charts, the old release shop still owns it).
kubectl -n shop get deploy shop-api -o jsonpath='{.metadata.annotations}{"\n"}'
Fix: when migrating, first add to the old resource helm.sh/resource-policy: keep before uninstalling the old release, then use --take-ownership (Helm 3.17+/4) to let the new release take over; or edit the meta.helm.sh/release-name annotation manually. See module 7 for details.
1. In CI, restore the dependencies of shop-api exactly per Chart.lock and package them.
helm dependency build charts/shop-api helm package charts/shop-api -d dist/
2. Use Helmfile to upgrade only the shop-web release (prod environment).
helmfile -e prod -l name=shop-web apply
A team has 6 services. auth and auth-cache are always changed and released together, while the rest are maintained by different teams. How would you split the charts?
One chart for auth (cache either as its child chart or written in the same chart, because they share a version and owner); each of the other services gets one chart; all depend on the same library chart; use Helmfile/Argo CD as the orchestration layer to express dependencies (for example, auth before the gateway). Do not build a global umbrella, to avoid one service's failure rolling back other teams' releases.
Verified teaching videos
No verified video specifically covering “umbrella vs single-service chart architecture trade-offs” was found; a storyboard script is provided below.
Official documentation
- Charts (dependencies, library charts, global values)
- Library Charts
- Chart Development Tips and Tricks (Complex Charts with Many Dependencies)
- Helmfile documentation
Video storyboard script (about 90 seconds)
This course material cannot directly generate a video or MP3; a storyboard and narration script are provided, which can be given to a video tool.
Visual: a large umbrella covers three boxes, api, web and db, with “1 release” written on the handle.
Narration: the umbrella chart installs multiple services into one release: rendered together, waited on together, rolled back together.
Visual: only the web box changes colour, but the db box shows a red timeout, and the whole umbrella flips back to the old version.
Narration: only web was changed, yet because of a database timeout the entire release is rolled back. This is the blast radius.
Visual: three small umbrellas each cover one of the three services, with an arrow chain db → api → web above, labelled Helmfile / Argo CD.
Narration: each single-service chart is its own release; ordering is handed to the orchestration layer, and a failure rolls back only itself.
Visual: a shared shop-lib block at the bottom, with three lines connecting to the three charts.
Narration: repeated templates go into the library chart. Remember: once released, selector labels must never be changed in the library.
Module 2 · Values layering and multiple environments
- Design chart defaults → base → env → region → temporary overrides layering, and be able to predict the merged result (deep merge for maps, whole replacement for lists,
nullkey deletion). - Use correctly
global: it is shared between parent and child charts; in a single-service architecture it is just a “conventional shared section”. - Trade off between “structured config (nested maps)” and “flattened (env lists, long keys)”, and understand the problem that a list cannot be partially overridden.
- Refuse to write
if eq .Values.env "prod"; use--setlimited to a few auditable temporary overrides.
What: sources and precedence of values
A single helm upgrade final values are merged from the following sources (later ones override earlier ones):
- chart's
values.yaml(for umbrella also includes the child charts' values.yaml and the<child-name>:section in the parent chart); - multiple
-f/--valuesfiles,in command-line order, rightmost takes precedence; --set,--set-string,--set-file,--set-json,--set-literal(applied last);- During upgrade, the
--reuse-values/--reset-then-reuse-valuesuses the user values from the previous revision as its base (not recommended in production: the source of truth for values should be in Git).
Merge rules (must memorise)
| Type | Rule | Example: base → prod | Result |
|---|---|---|---|
| map | Deep merge, key-by-key override | resources: {requests: {cpu: 50m}} → resources: {limits: {memory: 256Mi}} | Both are kept |
| list | Whole replacement, elements are not merged | env: [A, B] → env: [C] | only C |
| Scalar | override | replicaCount: 2 → 4 | 4 |
null | In the result, set the key to null to delete this key (including chart defaults) | podAnnotations: null | key does not exist; templates treat it as “unset” |
Why: why layering
Without layering, a common practice is one full values file per environment (dev.yaml and prod.yaml each 300 lines), and after a few months they quietly diverge: prod has a security setting that staging lacks, so “tested in staging” loses its meaning. Layering makes differences explicit: git diff envs/base envs/prod is all the difference between production and the baseline.
How: shop's layering design
| Layer | File | What goes in | What does not go in |
|---|---|---|---|
| 0 chart defaults | charts/shop-api/values.yaml | safe defaults that run standalone, all keys in the schema | any environment names, domains, accounts |
| 1 base | envs/base/common.yaml + envs/base/shop-api.yaml | Organisation-level conventions: global.imageRegistry, public annotations, and business config that is consistent across all environments | replica count, resource sizing |
| 2 env | envs/prod/common.yaml + envs/prod/shop-api.yaml | global.environment, replica count, resources, PDB, log level | secrets (module 3) |
| 3 region | envs/region/canadacentral.yaml | regions, storage classes, topology spread, regional endpoints | business config |
| 4 temporary overrides | --set image.tag=$GIT_SHA | CI-injected image tags, emergency switches | any value that needs to be kept long term |
global the true scope of
- In an umbrella, Helm copies the parent chart's
globalinto each child chart's.Values.global, and a child chart can also have its ownglobaldefaults (the parent chart overrides the child chart). - In a single-service architecture there is no parent-child relationship,
globalis just an ordinary key. It is still worth using: it gives “organisation-wide shared values” a fixed place, and if a service is later merged into an umbrella, no template changes are needed. globalIt is not a “global variable”: it cannot be shared across releases, nor read by another release.
Structured vs flattened
| Structured (nested map) | Flattened (list / long key) | |
|---|---|---|
| Example | config: {log: {level: info}, cache: {ttl: 60}} | env: [{name: LOG_LEVEL, value: info}] |
| Overridability | ✓ prod only writes config.log.level: warn | ✗ list replaced wholesale; prod must repeat all env entries |
| Schema validation | ✓ every field can declare a type and enum | can only validate “is a name/value list” |
| Flexibility | chart author must design fields in advance | ✓ users can pass any env (escape hatch) |
Recommended: use a structured map for business config and convert it to env in the template (range $k, $v := .Values.config.env, map-form env can be overridden key by key); keep one extraEnv: [] as an escape hatch.
When: when to use it --set
- ✓ CI-injected unpredictable values (image tag / digest), and temporary switches during incidents (written back to Git afterwards).
- ✗ long-term config, complex structures (escaping commas, dots and list indexes is error-prone), secrets (they enter shell history, CI logs and the release Secret).
{{ if eq .Values.global.environment "prod" }}replicas: 4{{ end }} in the template is convenient” is wrong: it makes the chart aware of environment names, so adding staging means changing the template and publishing a new version. The correct approach is to write replicaCount: 4 in prod.yaml. ② “-f prod.yaml -f base.yaml is equivalent” is wrong: the right-most file takes precedence, so base overrides prod. ③ “writing env: [{name: X}] in prod appends to base's env” is wrong: lists are replaced wholesale, so all of base's env is lost.Architecture diagram: values layering and Helmfile overlay
Flowchart: the order in which Helm merges values (a single release)
Interactive simulator: values merging layer by layer
Choose an environment and region, and step through the merge. Each step highlights keys that are added (green), overridden (yellow) or deleted (red); note the whole-list replacement and null deletion. The terminal below shows the corresponding helm template commands and helm get values --all result excerpts.
Core commands and parameters
| Command | Purpose | Key parameters / notes |
|---|---|---|
helm template -f a -f b | Preview the layered result | rightmost takes precedence; used with --show-only |
helm get values REL -n NS | View user-supplied values | --all including chart defaults; --revision N |
helm show values CHART | View chart defaults | For third-party charts, look at this first before deciding which keys to override |
helm upgrade --reset-then-reuse-values | Use the chart's new defaults as the base, then overlay the last user values | compared to --reuse-values is safer (defaults newly added by the new chart are not lost); under GitOps it is generally not used |
--set-json / --set-literal | passes JSON structures / strings without parsing commas and dots | When temporarily overriding complex values, compared with --set is safer |
helmfile -e prod template | Render all releases with the values overlay defined by Helmfile | and helm template compare results to verify |
cd ~/helm-lab/shop-platform # layered render: base → prod → canadacentral → CI injection helm template shop-api charts/shop-api \ -f envs/base/common.yaml -f envs/base/shop-api.yaml \ -f envs/prod/common.yaml -f envs/prod/shop-api.yaml \ -f envs/region/canadacentral.yaml \ --set image.tag=6.17.0 \ --show-only templates/deployment.yaml | grep -E 'replicas|image:|shop.example.com/env|cpu|memory|LOG_LEVEL'
replicas: 4
shop.example.com/env: prod
image: "ghcr.io/stefanprodan/podinfo:6.17.0"
- name: LOG_LEVEL
cpu: 200m
memory: 256Mi
# the difference between the two environments is a single diff
diff <(helm template shop-api charts/shop-api -f envs/base/common.yaml -f envs/base/shop-api.yaml -f envs/dev/common.yaml -f envs/dev/shop-api.yaml) \
<(helm template shop-api charts/shop-api -f envs/base/common.yaml -f envs/base/shop-api.yaml -f envs/prod/common.yaml -f envs/prod/shop-api.yaml)
How to verify: The diff should only show keys you wrote in the prod layer; any other difference means some layer wrongly wrote a key it should not have. Common errors: files in the wrong order; in YAML, tag: 1.10 is parsed as the float 1.1 (always quote version numbers). Production use: automatically post the rendered dev vs prod diff in the PR (the CI from lesson 5).
# view the source of values for an installed release helm get values shop-api -n shop # only the user-supplied helm get values shop-api -n shop --all | head -20 # all merged values
Lab 2: base / env / region layering + Helmfile orchestration (about 8 minutes)
charts/shop-api/values.yaml , and let the library convert the map to env.
cat >> charts/shop-api/values.yaml <<'EOF'
global:
environment: ""
region: ""
config:
env: # map: each key can be overridden separately by upper layers
PODINFO_UI_MESSAGE: "shop api"
LOG_LEVEL: info
EOF
{{- /* convert the structured config.env into an env list, then hand it to the library */ -}}
{{- $env := list -}}
{{- range $k, $v := .Values.config.env -}}
{{- $env = append $env (dict "name" $k "value" ($v | toString)) -}}
{{- end -}}
{{- $_ := set .Values "env" (concat $env (.Values.env | default list)) -}}
{{ include "shop-lib.deployment" . }}
range Sort the map by key name, so the rendered result is stable (no meaningless diffs from order changes). .Values.env Keep as an escape hatch (appended after config.env). Here directly set .Values only affects the in-memory object for this render; it does not change the user values or the config stored in the release.
cat > envs/base/common.yaml <<'EOF'
global:
imageRegistry: "" # fill in for a private registry, e.g. myacr.azurecr.io
podAnnotations:
shop.example.com/owner: team-shop
EOF
cat > envs/base/shop-api.yaml <<'EOF'
config:
env:
PODINFO_UI_MESSAGE: "shop api (base)"
EOF
cat > envs/dev/common.yaml <<'EOF'
global: { environment: dev }
replicaCount: 1
pdb: { enabled: false }
EOF
cat > envs/dev/shop-api.yaml <<'EOF'
config: { env: { LOG_LEVEL: debug } }
EOF
cat > envs/prod/common.yaml <<'EOF'
global: { environment: prod }
replicaCount: 4
pdb: { enabled: true, maxUnavailable: 1 }
EOF
cat > envs/prod/shop-api.yaml <<'EOF'
config: { env: { LOG_LEVEL: warn } }
resources:
requests: { cpu: 200m, memory: 128Mi }
limits: { memory: 256Mi }
EOF
cat > envs/region/canadacentral.yaml <<'EOF'
global: { region: canadacentral }
podAnnotations:
shop.example.com/region: canadacentral
EOF
touch envs/base/shop-web.yaml envs/base/shop-db.yaml envs/dev/shop-web.yaml envs/dev/shop-db.yaml envs/prod/shop-web.yaml envs/prod/shop-db.yaml
Note podAnnotations is a map: annotations appended by the region layer and the owner annotation from the base layer will both be kept.
helm template shop-api charts/shop-api \ -f envs/base/common.yaml -f envs/base/shop-api.yaml \ -f envs/prod/common.yaml -f envs/prod/shop-api.yaml \ -f envs/region/canadacentral.yaml --show-only templates/deployment.yaml \ | grep -A12 'annotations:' | head -14; \ helm template shop-api charts/shop-api -f envs/base/shop-api.yaml -f envs/prod/shop-api.yaml --show-only templates/deployment.yaml | grep -A1 -E 'name: (LOG_LEVEL|PODINFO_UI_MESSAGE)'
annotations:
shop.example.com/owner: team-shop
shop.example.com/region: canadacentral
...
- name: LOG_LEVEL
value: warn
- name: PODINFO_UI_MESSAGE
value: shop api (base)environments:
dev: {}
prod: {}
---
helmDefaults:
wait: true
timeout: 300
historyMax: 10
releases:
- name: shop-db
namespace: shop
chart: ./charts/shop-db
values:
- envs/base/common.yaml
- envs/base/shop-db.yaml
- envs/{{ .Environment.Name }}/common.yaml
- envs/{{ .Environment.Name }}/shop-db.yaml
- name: shop-api
namespace: shop
chart: ./charts/shop-api
needs: [shop/shop-db]
values:
- envs/base/common.yaml
- envs/base/shop-api.yaml
- envs/{{ .Environment.Name }}/common.yaml
- envs/{{ .Environment.Name }}/shop-api.yaml
- envs/region/canadacentral.yaml
- name: shop-web
namespace: shop
chart: ./charts/shop-web
needs: [shop/shop-api]
values:
- envs/base/common.yaml
- envs/base/shop-web.yaml
- envs/{{ .Environment.Name }}/common.yaml
- envs/{{ .Environment.Name }}/shop-web.yaml
helmfile -e dev diff helmfile -e dev apply helm get values shop-api -n shop
UPDATED RELEASES:
NAME NAMESPACE CHART VERSION DURATION
shop-db shop ./charts/shop-db 0.1.0 3s
shop-api shop ./charts/shop-api 0.1.0 12s
shop-web shop ./charts/shop-web 0.1.0 9s
USER-SUPPLIED VALUES:
config:
env:
LOG_LEVEL: debug
PODINFO_UI_MESSAGE: shop api (base)
global:
environment: dev
imageRegistry: ""
region: canadacentral
...
Without Helmfile, use the equivalent 3 helm upgrade --install … -f … -f … run in order db → api → web. needs Write as namespace/name. Note that the shop-db chart does not use replicaCount/pdb, so passed-in common keys are ignored. This is exactly why “the common layer should only hold keys that are truly common”.
replicas: {{ if eq .Values.global.environment "prod" }}4{{ else }}1{{ end }}
When staging is added, it will get 1 replica, and no values can override this behaviour. Correct: the template should only write replicas: {{ .Values.replicaCount }}, and environment differences go into envs/*/common.yaml.
Case 1: list replacement wiped out production environment variables
Problem: base's env list has 8 items (including OTEL_EXPORTER_OTLP_ENDPOINT), and an engineer added env: [{name: FEATURE_X, value: "on"}] in prod.yaml; after release, all tracing data for the production service disappeared. Approach: Change env to a map structure (config.env), and convert it to a list in the template; extraEnv use lists only for a few special cases, and forbid the schema from using env keys at the env layer (CI uses yq to check). Limitations: A map cannot express valueFrom, which needs a separate secretEnv structure.
Case 2: region layer for multi-region deployment
Problem: The same service is deployed in canadacentral and canadaeast; storage classes, egress IP allowlists and regional endpoints differ between the two, but business config must be identical. Approach: The region layer holds only infrastructure-related keys (global.region,storageClass,egressAllowList); code review rule: reject any region file in which keys starting with config. appear. Argo CD ApplicationSet uses a matrix generator (environment × region). Limitations: No more than 4 layers, otherwise tracing cost outweighs the benefit.
Case 3: --set database password leaked
Problem: The pipeline used --set db.password=$DB_PASS to deploy; the password appeared in CI logs (commands printed in debug mode),helm get values in the output and in the release Secret, where anyone able to read the Secret can decode it. Approach: Move the secret out of values and switch to an ExternalSecret (module 3). Limitations: Old revisions still contain the password, so you need to rotate the password and clean up old revisions (--history-max).
Common errors and fixes
Some environment variables in prod “disappeared”, even though they are written in the values file
Cause: a list was replaced wholesale by a higher layer.
helm get values shop-api -n shop --all -o yaml | yq '.env, .config'
Fix: change it to a map structure, or fully repeat the list in the higher layer.
Error: values don't meet the specifications of the schema(s) in the following chart(s): shop-api: - replicaCount: Invalid type. Expected: integer, given: string
Cause:--set-string replicaCount=4 or the YAML was written as "4".
Fix: use --set replicaCount=4 (it will be inferred as an integer), or fix the YAML. The value of the schema is precisely that it catches this kind of error before rendering.
template: ... nil pointer evaluating interface {}.environment
Cause: The template accesses .Values.global.environment, but the current values have no global key (for example, a layer wrote global: null).
helm template shop-api charts/shop-api -f envs/... --debug 2>&1 | head -20
Fix: use dig "environment" "" (.Values.global | default dict) this kind of nil-safe pattern, and provide in the chart's values.yaml global the default structure.
image tag shows 1.1 instead of 1.10
Cause: YAML parses tag: 1.10 as a floating-point number.
Fix: always quote version numbers: tag: "1.10"; in templates, use {{ .Values.image.tag | toString }}; in the schema, declare "type": "string".
1. Without installing, render shop-api in prod and look only at the Deployment.
helm template shop-api charts/shop-api -f envs/base/common.yaml -f envs/base/shop-api.yaml -f envs/prod/common.yaml -f envs/prod/shop-api.yaml --show-only templates/deployment.yaml
2. View the user values of the second revision of shop-api.
helm get values shop-api -n shop --revision 2
The platform team wants “all production services to enable PDB by force”; someone proposes writing if eq .Values.global.environment "prod" in the library template. Your plan?
Do not introduce environment branches in templates. Plan: in the library, the PDB is controlled by pdb.enabled a values switch, and envs/prod/common.yaml set pdb.enabled: true it in prod values; then use a policy engine (Kyverno / ValidatingAdmissionPolicy) or CI to check that every Deployment in the prod render output has a matching PDB. “Enforcement” should be guaranteed by the policy layer, not by implicit logic in templates.
Verified teaching videos
No verified video specifically covering multi-environment values layering design was found; a storyboard script is provided.
Official documentation
Video storyboard script (about 80 seconds)
This course material cannot directly generate a video or MP3; a storyboard and narration script are provided.
Visual: five semi-transparent cards stacked from bottom to top: defaults, base, prod, region, --set.
Narration: values are stacked layer by layer, and the higher up, the higher the priority. Each layer writes only what differs from the layers below.
Visual: two map keys merge together; a list card completely covers the list below it.
Narration: maps deep-merge, lists are replaced wholesale, and writing null deletes a key. These three rules decide whether your config “disappears”.
Visual: the if prod in the template is crossed out in red, and beside it appears replicaCount 4 from prod.yaml.
Narration: don't let the template know environment names. Environment differences belong in values files.
Visual: the text --set password flows into a safe-shaped release Secret; the safe is transparent.
Narration: values passed with set are stored verbatim in the release. Secrets do not belong in values.
Module 3 · Secrets: helm-secrets, SOPS and External Secrets
- Explain Helm's secret leakage surface: user values (
.config) and the rendered manifest (.manifest) are both stored in the release Secret, with gzip + base64 which is not encryption. - Use SOPS + age to encrypt values files, and install helm-secrets following Helm 4's plugin model (
secrets,secrets-getter,secrets-post-rendererthree plugins). - In the chart, keep only
ExternalSecret(references); External Secrets Operator generates the Kubernetes Secret inside the cluster, and understand the mount model of Secrets Store CSI Driver.
What: what Helm stores in the release
On every install, upgrade and rollback, Helm serialises a release object to JSON → gzip → base64 and stores it in a Secret in the release namespace sh.helm.release.v1.<name>.v<N> (type helm.sh/release.v1). The release object contains:
chart: chart metadata, templates, default values;config: the user-supplied values (all-fand--setmerged result) —helm get valuesis what helm get values reads;manifest: the full rendered manifest, includingkind: Secretthe chart'sdata——helm get manifestas well; helm get manifest reads it;hooks: the rendered hook manifests (including any secrets in them).
So: as soon as a secret enters values in plaintext, or a template renders it into a Secret, it will appear in every historical revision in the Secret (by default 10 are kept, controlled by --history-max ), and any person or tool with get secrets permission on that namespace can decode it.
Why: three approaches protect different locations
| Approach | Git | CI logs / client | release Secret | cluster Secret object | Applicable to |
|---|---|---|---|---|---|
plaintext values / --set | ✗ | ✗ | ✗ | ✗ (base64) | only for experiments |
| helm-secrets + SOPS | ✓ encrypted storage | △ decrypted in memory on the client | ✗ decrypted values still go into config/manifest | ✗ | scenarios where “values are the secret”, and teams without an external secret store |
| External Secrets Operator | ✓ stores references only | ✓ | ✓ contains only ExternalSecret | △ ESO generates the Secret (can be combined with etcd encryption) | Preferred: Key Vault / Secrets Manager / Vault as the source of truth |
| Secrets Store CSI Driver | ✓ | ✓ | ✓ contains only SecretProviderClass | ✓ mounted as files by default (optionally synced to a Secret) | for when secrets should not appear in etcd and the app can read files |
How: how each approach works
SOPS + age
SOPS (v3.13.3) encrypts only the values, so key names are kept, which keeps diffs and code reviews readable; the data key is encrypted with the age public key (or Azure Key Vault / AWS KMS) and written into the file's sops: metadata section. .sops.yaml Use path_regex to define which files are encrypted with which keys.
helm-secrets and the Helm 4 plugin system (verified)
- Helm 4 requires each plugin to have only one type (
cli/v1,getter/v1,postrenderer/v1), so helm-secrets is split into 3 plugin packages:secrets(helm secrets …commands),secrets-getter(secrets://protocol),secrets-post-renderer. - Helm 4's
helm plugin installdoes not support--version, so use a versioned tgz URL or an OCI reference (oci://ghcr.io/jkroepke/helm-secrets/secrets:4.7.11). - Helm 4 verifies plugin signatures by default (
--verifydefault true; installing from a local directory is treated as development mode and is not verified); when the source does not support verification, you must explicitly--verify=false, which prints a warning. - Recommended usage:
helm upgrade … -f secrets://secrets/prod.enc.yaml(the getter calls sops to decrypt values files when they are read), compared with thehelm secrets upgradewrapper command, it is faster and also works with Argo CD.
External Secrets Operator (v2.15.0)
In the chart, only template the ExternalSecret (API external-secrets.io/v1): it references a SecretStore/ClusterSecretStore and a remote key. The ESO controller watches it, calls the external API to fetch the value, creates or updates the target Kubernetes Secret, and refreshInterval re-syncs at that interval. The Helm release contains only the “reference”, with no plaintext.
Secrets Store CSI Driver (v1.6.2)
Pod mounts csi a volume (driver secrets-store.csi.k8s.io), the kubelet calls the CSI driver, which fetches the value through a provider (Azure Key Vault provider, AWS ASCP, etc.) and writes it to the Pod's tmpfs. Optionally secretObjects sync the content to a Kubernetes Secret (only after the Pod mounts it).
When: how to choose
- Existing Key Vault / Secrets Manager / Vault: ESO (GitOps-friendly, rotation syncs automatically).
- Compliance requires that secrets do not land in etcd: CSI Driver (mount files only).
- Small team, no external secret store, needs to keep a few config secrets in Git: SOPS (plus restricting Secret read access in the release namespace).
- In all cases, do not include
password: {{ .Values.db.password }}this kind of template in the chart.
lookup a generated random password will not leak”: the generated value is rendered into the Secret manifest and stored in the release just the same. ③ “--hide-secret can hide Secrets in the release”: it only --dry-run hides Secrets in output and does not affect storage.Architecture diagram: three secret paths
Flowchart: one ESO sync
Interactive simulator: the journey of a database password, where does plaintext appear?
After choosing an approach, play step by step: the password starts on the “author's laptop” and passes through Git, CI, the Helm client, the release Secret, the Kubernetes Secret, and the Pod. Each location is labeled “plaintext / ciphertext / absent”, and the terminal below shows real commands you can use to verify.
Core commands and flags
| Command | Purpose | Notes |
|---|---|---|
helm get manifest REL | View the rendered manifest stored in the release | Includes the Secret's data (base64) |
kubectl get secret sh.helm.release.v1.REL.vN -o jsonpath='{.data.release}' | Read the release object directly | base64 -d twice (once for Kubernetes, once for Helm), then gunzip |
age-keygen -o key.txt | Generate an age key pair | Store the private key in CI secrets / locally ~/.config/sops/age/keys.txt |
sops -e -i FILE / sops -d FILE | Encrypt / decrypt | Per .sops.yaml entry for creation_rules |
helm plugin install oci://ghcr.io/jkroepke/helm-secrets/secrets:4.7.11 | Install helm-secrets on Helm 4 (install the getter and post-renderer packages separately) | None --version; see signature verification below |
helm upgrade … -f secrets://FILE | Use encrypted values | getter calls sops to decrypt |
kubectl get externalsecret | Check ESO sync status | STATUS SecretSynced, READY True |
# 1) Prove the release Secret contains plaintext (control experiment using the manual Secret from module 1)
REV=$(helm history shop-api -n shop -o json | jq '.[-1].revision')
kubectl -n shop get secret sh.helm.release.v1.shop-api.v$REV -o jsonpath='{.data.release}' \
| base64 -d | base64 -d | gunzip | jq -r '.config, (.manifest | length)'
{
"config": { "env": { "LOG_LEVEL": "debug", ... } },
"global": { "environment": "dev", ... }
}
5634
How to verify: If any values contain password, it will appear in the first block of output. Common mistake: Decoding base64 only once yields gibberish; the release field is itself gzip data that Helm base64-encodes once more. Production use: During security audits, use this command to scan all releases (pipe the output to gitleaks or trufflehog for scanning).
# 2) Install the 3 helm-secrets plugins on Helm 4 (OCI method) for p in secrets secrets-getter secrets-post-renderer; do helm plugin install oci://ghcr.io/jkroepke/helm-secrets/$p:4.7.11 done helm plugin list
NAME VERSION TYPE APIVERSION PROVENANCE SOURCE secrets 4.7.11 cli/v1 v1 ... ... secrets-getter 4.7.11 getter/v1 v1 ... ... secrets-post-renderer 4.7.11 postrenderer/v1 v1 ... ...
If verification fails (for example, the maintainer's public key has not been imported on this machine https://github.com/jkroepke.gpg), import the public key into the keyring following the helm-secrets docs (--keyring) and then install; only in a lab environment may you add --verify=false. helm plugin list columns depend on your Helm 4.3 output.
Lab 3: Replace the manual Secret with External Secrets and inspect the release (about 8 minutes)
helm repo add external-secrets https://charts.external-secrets.io helm repo update external-secrets helm upgrade --install external-secrets external-secrets/external-secrets \ -n external-secrets --create-namespace --version 2.15.0 --wait kubectl get crd | grep external-secrets.io | head -5
clustersecretstores.external-secrets.io ... externalsecrets.external-secrets.io ... secretstores.external-secrets.io ...
ESO is an Operator: its chart must be installed before the application chart that references ExternalSecret is installed (the ordering issue from module 6).
apiVersion: external-secrets.io/v1
kind: ClusterSecretStore
metadata:
name: lab-fake
spec:
provider:
fake:
data:
- key: "/shop/db"
value: '{"password":"S3cure-Lab-Only"}'
version: "v1"
kubectl apply -f cluster-secret-store-fake.yaml kubectl get clustersecretstore lab-fake
NAME AGE STATUS CAPABILITIES READY lab-fake 5s Valid ReadWrite True
In production, provider replace it with azurekv (lesson 3, Workload Identity), or aws (lesson 4, Pod Identity/IRSA); the chart needs no changes. This is “decoupling references from storage”.
{{- if .Values.externalSecret.enabled }}
apiVersion: external-secrets.io/v1
kind: ExternalSecret
metadata:
name: {{ .Values.credentialsSecret }}
spec:
refreshInterval: {{ .Values.externalSecret.refreshInterval }}
secretStoreRef:
kind: {{ .Values.externalSecret.storeKind }}
name: {{ .Values.externalSecret.storeName }}
target:
name: {{ .Values.credentialsSecret }}
creationPolicy: Owner
data:
- secretKey: password
remoteRef:
key: {{ .Values.externalSecret.remoteKey }}
property: password
{{- end }}
cat >> charts/shop-db/values.yaml <<'EOF' externalSecret: enabled: true refreshInterval: 1h storeKind: ClusterSecretStore storeName: lab-fake remoteKey: /shop/db EOF # Delete the Secret created manually in module 1 and let ESO take over kubectl -n shop delete secret shop-db-credentials sed -i 's/^version: 0.1.0/version: 0.2.0/' charts/shop-db/Chart.yaml helm upgrade shop-db charts/shop-db -n shop --wait kubectl -n shop get externalsecret,secret shop-db-credentials
NAME STORETYPE STORE REFRESH INTERVAL STATUS READY externalsecret.external-secrets.io/shop-db-credentials ClusterSecretStore lab-fake 1h SecretSynced True NAME TYPE DATA AGE secret/shop-db-credentials Opaque 1 4s
Note: postgres' POSTGRES_PASSWORD only takes effect when the data directory is first initialized. If a PVC already exists, changing the password does not change the database user's password (you need ALTER USER). In the lab, if the passwords do not match, delete the StatefulSet and PVC, then reinstall shop-db.
helm get manifest shop-db -n shop | grep -n -i -E 'password|S3cure' ; echo "exit=$?"
kubectl -n shop get secret shop-db-credentials -o jsonpath='{.data.password}' | base64 -d; echo
35: - secretKey: password 37: property: password exit=0 S3cure-Lab-Only
The release manifest contains only key names password (references), no values S3cure-Lab-Only; values exist only in the Secret generated by ESO.
age-keygen -o ~/.config/sops/age/keys.txt 2>&1 | tail -1 # outputs Public key: age1...
AGE_PUB=$(grep -o 'age1[0-9a-z]*' ~/.config/sops/age/keys.txt | head -1)
cat > .sops.yaml <<EOF
creation_rules:
- path_regex: secrets/.*\.enc\.yaml$
age: $AGE_PUB
EOF
printf 'demoToken: "not-for-prod"\n' > secrets/dev.enc.yaml
sops -e -i secrets/dev.enc.yaml && head -3 secrets/dev.enc.yaml
helm template shop-api charts/shop-api -f secrets://secrets/dev.enc.yaml >/dev/null && echo "getter OK"
demoToken: ENC[AES256_GCM,data:3m0u…,iv:…,tag:…,type:str]
sops:
age:
getter OK
If you run helm upgrade … -f secrets://…,demoToken will put plaintext into the release's config—this is exactly SOPS's limit. Delete secrets/dev.enc.yaml when the lab ends; do not commit the private key file.
Case 1: audit finds 300 release Secrets containing database passwords
Problem: The security team scanned the cluster with a read-only service account and found many sh.helm.release.v1.* containing plaintext passwords; this account was originally only for “viewing deployment status” but had get secrets permissions. Approach:① switch all charts to ExternalSecret; ② rotate all exposed passwords; ③ set --history-max to 5 and upgrade once so old revisions are cleaned up; ④ remove Secret read access from the read-only role and use helm list for a minimum-permission audit (note: Helm reading a release itself requires Secret read permission, so read-only operators should view state through the GitOps UI). Limitation: Old data remains in etcd backups and must be assessed against backup retention.
Case 2: Argo CD + helm-secrets
Problem: The team uses Argo CD to render Helm charts and needs to read SOPS-encrypted values. Approach: Install sops and helm-secrets in the repo-server, and use secrets:// prefixed valueFiles in the Application (the helm-secrets docs have an Argo CD integration section). Limitation: Argo CD uses helm template for rendering, then applies manifests itself, so there is no release Secret; however, the rendered Secret appears in Argo CD's cache and UI diff (requires hiding and RBAC configuration); ESO is recommended.
Case 3: CSI Driver satisfies “secrets not stored in etcd”
Problem: A financial customer requires that TLS private keys and API keys must not exist as Kubernetes Secrets. Approach: Enable the Key Vault Secrets Provider add-on on AKS and template in the chart SecretProviderClass and the Pod's csi volume; the application reads from /mnt/secrets-store . Limitation: Pod startup depends on Key Vault availability; rotation requires enabling the driver's rotation feature and the application must reread the file; it cannot be used directly as an Ingress TLS Secret (unless syncing to a Secret is enabled).
Common errors and fixes
no matches for kind "ExternalSecret" in version "external-secrets.io/v1" ensure CRDs are installed first
Cause: ESO is not installed or is too old (v1 the API has been available since ESO 0.17; older versions only have v1beta1).
kubectl api-resources --api-group=external-secrets.io helm list -n external-secrets
Fix: install or upgrade ESO first (module 6: the Operator before CRs); in the chart, you can use .Capabilities.APIVersions.Has "external-secrets.io/v1/ExternalSecret" to give a clear fail message.
ExternalSecret STATUS SecretSyncedError: could not get secret data from provider
Cause: The remote key/property does not exist, or provider authentication failed (for example, the Workload Identity federated credential subject does not match).
kubectl -n shop describe externalsecret shop-db-credentials | tail -15 kubectl -n external-secrets logs deploy/external-secrets --tail=50
Fix: Verify remoteRef.key/property; check the SecretStore's READY status and identity configuration (lessons 3 and 4).
Error: failed to install plugin: plugin source does not support verification. Use --verify=false to skip verification
Cause: Helm 4 verifies plugin signatures by default, but this source (for example, a Git repository URL) does not provide .prov.
Fix: Use a signed release package (tgz or OCI) and configure the keyring; only use --verify=false after you confirm the source is trusted.
Error: unknown flag: --version (helm plugin install … --version v4.7.11)
Cause: Plugin installation in Helm 4 does not support --version (Helm 3 supports it).
Fix: Put the version in the URL or OCI tag: oci://ghcr.io/jkroepke/helm-secrets/secrets:4.7.11.
sops: Error getting data key: 0 successful groups required, got 0
Cause: This machine does not have a private key that can decrypt the file (the age private key path, or Key Vault/KMS permissions).
echo $SOPS_AGE_KEY_FILE; ls ~/.config/sops/age/ sops filestatus secrets/dev.enc.yaml
Fix: Inject SOPS_AGE_KEY in CI, or configure a cloud KMS identity; confirm .sops.yaml includes the recipient for this environment.
1. Find all release Secrets in the shop namespace, and check whether the manifest of the latest shop-api revision contains “kind: Secret”.
kubectl -n shop get secret -l owner=helm helm get manifest shop-api -n shop | grep -c '^kind: Secret'
2. Force ESO to resync shop-db-credentials immediately.
kubectl -n shop annotate externalsecret shop-db-credentials force-sync=$(date +%s) --overwrite
The team says, “We have encrypted all values with SOPS, so we meet the secrets management requirements.” What should the auditor ask?
① Are the decrypted values rendered into a Secret and stored in the release Secret's config/manifest? Who has Secret read permission in that namespace? ② How many historical revisions are kept? ③ Who holds the private key (age/KMS), and how is it rotated? ④ Does CI logging print the rendered output (--debug,helm template)? Conclusion: SOPS solves plaintext in Git, but protecting runtime requires ESO/CSI or strict RBAC.
Verified teaching videos
No verified helm-secrets / SOPS dedicated video was found; a storyboard script is provided instead.
Official docs
- External Secrets Operator(Fake provider)
- helm-secrets installation (three Helm 4 plugins)
- SOPS docs
- Secrets Store CSI Driver
- Helm storage backends
Video storyboard script (about 90 seconds)
This courseware cannot directly generate a video or MP3, so a storyboard and narration script are provided.
Visual: a transparent safe labeled sh.helm.release.v1.shop.v7, with two sheets of paper inside, config and manifest, both showing the word password.
Narration: Helm stores user values and the rendered manifest in the release Secret. gzip and base64 are not encryption.
Visual: the file in Git shows ENC[...]; after passing through the secrets protocol it becomes plaintext and falls back into the transparent safe.
Narration: SOPS keeps ciphertext in Git, but Helm receives plaintext, and the release still contains plaintext.
Visual: the safe holds only one sticky note reading “remoteRef: /shop/db”; the ESO robot fetches the value from Key Vault and generates the Secret in the cluster.
Narration: External Secrets makes the release store only a reference; the actual value is fetched from the secret store by the in-cluster controller.
Visual: a tmpfs folder appears in the Pod, and the etcd icon gets a checkmark.
Narration: if secrets must not land in etcd, use the Secrets Store CSI Driver to mount them directly as files.
Module 4 · Hooks and Jobs: migrations, backups, and tests
- List the 9 hook events and draw the full upgrade timeline: pre-upgrade hooks → update main resources → wait → post-upgrade hooks → mark deployed.
- Master the Helm 4.3 hook execution algorithm: hooks for the same event are first pre-sorted by kind, then by ascending weight → ascending name stable sort; create and wait one at a time (Jobs and Pods wait until complete; other kinds are ready once created); each hook independently uses waits at most
--timeout. - Use delete policies correctly (
before-hook-creationdefault,hook-succeeded,hook-failed) andhelm.sh/hook-output-log-policywrite a re-entrant, timeout-bounded database migration Job. - Understand the consequences of “hook resources are not managed by the release”: they do not appear in
helm get manifest, do not take part in diff,helm uninstallare not deleted, and rollback will not undo migrations that have already run.
helm test. Importance:★★★★★What: hook events
| Annotation value | When it runs | Typical use |
|---|---|---|
pre-install | After template rendering, before creating any resource | Create external dependencies, pre-checks |
post-install | After all resources are created (and become ready at --wait time) | Initialize data, register services |
pre-upgrade | After rendering, before updating any resource | Database migrations, pre-upgrade backups |
post-upgrade | After resource updates (and once ready) | Smoke tests, cache warm-up, notifications |
pre-rollback / post-rollback | Before / after rollback | Block incompatible rollbacks, restore data |
pre-delete / post-delete | Before / after uninstall | Export data, clean up external resources |
test | Run helm test time | Connectivity / contract tests |
One resource can declare multiple events: helm.sh/hook: pre-install,pre-upgrade (migrations usually need both).
How: Helm 4.3 hook execution algorithm (from pkg/action/hooks.go)
- From the release's
Hooksselect the hooks for this event (already pre-sorted by kind install order at render time); sort.Stablebyhelm.sh/hook-weightascending (integer as a string, may be negative; treated as 0 if unset), with equal weights sorted by resource name ascending;- For each hook: if no delete policy is set,it defaults to
before-hook-creation; delete any leftover resource with the same name from the last run according to that policy → create the resource (applied via SSA in Helm 4) → useWatchUntilReadyto wait: Jobs wait until Complete, Pods wait until Succeeded, and other kinds are considered ready once created; each hook separately uses--timeout(default 5m); - If a hook fails: record
LastRun.Phase=Failed; perhook-output-log-policy: hook-failedprint its Pod logs; perhook-faileddelete policy delete it; previously succeeded hooks are cleaned up perhook-succeededdelete policy; subsequent hooks and the main resources are not executed, and the release is markedfailed; - All succeeded: per in reverse order output logs for each hook (
hook-succeededlog policy) and perhook-succeededdelete policy, delete. CustomResourceDefinitionCRD-type hooks are never deleted by delete policies (to prevent cascading deletion of CRs).
Full upgrade timeline
Render → record revision N as pending-upgrade → pre-upgrade hooks → KubeClient.Update (update main resources, SSA) → if --wait wait for readiness (--wait-for-jobs also waits for regular Jobs) → post-upgrade hooks → revision N-1 marked superseded, N marked deployed. If any step fails → N marked failed; if set --rollback-on-failure, roll back to the most recent deployed/superseded revision (running the rollback hooks defined in the rollback target).
Why: why hooks suit migrations, and why they are dangerous
| Property | Benefit | Risk |
|---|---|---|
| Runs before the main resource update (ordered) | The schema is ready before the new code starts | If the main update fails after a successful migration,the schema has already changed, so old code must be compatible with the new schema |
| Not managed by the release | Recreated on every upgrade, so the “Job spec is immutable” problem does not occur | Not part of diff; helm uninstall not deleted (leftover Jobs/ConfigMaps); rollback does not undo |
| Failure blocks | If the migration fails, the new version does not go live | A stuck hook leaves the release in pending-upgrade until timeout (lesson 7) |
When: choosing a hook or another approach
- ✓ Backward-compatible “expand” migrations (add columns, add tables, add indexes CONCURRENTLY): the expand phase of the expand/contract pattern.
- ✗ Long-running data backfills (they will saturate
--timeout) → use a separate Job or workflow, and have the application support both old and new data shapes. - ✗ In GitOps, note that Argo CD maps Helm hooks to its own sync hooks (for example, pre-upgrade → PreSync), so the semantics are not identical; Flux uses the Helm SDK, so its semantics match Helm.
- Alternatives: self-migration at application startup (with a distributed lock), initContainer (runs in every Pod, must be idempotent), or a dedicated migration pipeline step.
Related annotations cheat sheet
| Annotation | Values | Notes |
|---|---|---|
helm.sh/hook | Event list, comma-separated | Required |
helm.sh/hook-weight | Integer as a string, e.g. "-5" | Ordering within the same event; lower runs first |
helm.sh/hook-delete-policy | before-hook-creation (default),hook-succeeded,hook-failed | Can be combined, comma-separated |
helm.sh/hook-output-log-policy | hook-succeeded,hook-failed | Job/Pod container logs are printed by the Helm client (new in Helm 4) |
--timeout 5m is the overall upper bound for the upgrade”: each hook waits up to 5m on its own, plus main resource waiting, so total time can far exceed 5m. ③ “--rollback-on-failure will undo database migrations”: rollback only restores Kubernetes resources to the old revision; the database does not change. ④ “When a Job fails, backoffLimit makes Helm fail immediately”: Helm waits for the Job's Failed condition; backoffLimit: 6 and with exponential backoff it may take much longer than you expect; migration Jobs should set a small backoffLimit and activeDeadlineSeconds (less than --timeout).Sequence diagram: hooks in one shop-api upgrade
State diagram: combined effects of delete policies
Core animation: hook execution order and weights (pre-upgrade −5 → 0 → 5 → main resources → post-upgrade → failure branch)
This is helm upgrade shop-api the real execution order of the Helm 4.3 client. Check “migration fails” to observe the failure branch; switch delete policies and --rollback-on-failure observe leftover resources in the cluster and release history. The terminal below shows the API calls and helm/kubectl output for each step.
Core commands and flags
| Command | Purpose | Key flags / notes |
|---|---|---|
helm get hooks REL | View the hook manifest stored in the release | --revision N |
helm upgrade --timeout 10m | Limit per hook / per wait | Not total duration |
helm upgrade --no-hooks | Skip hooks (emergencies) | Migrations will not run; use only after confirming the schema is ready |
helm upgrade --wait-for-jobs | also waits for regular Jobs in the main resources | must be used with --wait together |
helm test REL --logs | Run test hook and print its logs | --filter name=…,--timeout |
helm history REL | View each revision's status and description | The failure description contains “pre-upgrade hooks failed” |
helm get hooks shop-api -n shop | grep -E '^# Source|helm.sh/hook'
---
# Source: shop-api/templates/hooks/migrations-cm.yaml
helm.sh/hook: pre-install,pre-upgrade
helm.sh/hook-weight: "-5"
helm.sh/hook-delete-policy: before-hook-creation
---
# Source: shop-api/templates/hooks/migrate-job.yaml
helm.sh/hook: pre-install,pre-upgrade
helm.sh/hook-weight: "0"
helm.sh/hook-delete-policy: before-hook-creation,hook-succeeded
helm.sh/hook-output-log-policy: hook-failed
...
# Watch hook execution (in another terminal) kubectl -n shop get jobs,pods -w -l app.kubernetes.io/component=hook # On failure, view the release description helm history shop-api -n shop --max 3
REVISION UPDATED STATUS CHART APP VERSION DESCRIPTION 3 ... superseded shop-api-0.3.0 6.17.0 Upgrade complete 4 ... failed shop-api-0.4.0 6.17.0 Upgrade "shop-api" failed: pre-upgrade hooks failed: ... 5 ... deployed shop-api-0.3.0 6.17.0 Rollback to 3
How to verify: The main resources of the failed revision were never applied (the Deployment image is still the old one). Common mistake: Assuming rev 4 partially took effect. Production use: Pipeline parsing helm history -o json description to determine the failure stage (hook or wait).
Lab 4: Add a database migration hook to shop-api and inject a failure (about 9 minutes)
{{- if .Values.migrations.enabled }}
apiVersion: v1
kind: ConfigMap
metadata:
name: {{ include "shop-lib.fullname" . }}-migrations
labels:
{{- include "shop-lib.labels" . | nindent 4 }}
app.kubernetes.io/component: hook
annotations:
helm.sh/hook: pre-install,pre-upgrade
helm.sh/hook-weight: "-5"
helm.sh/hook-delete-policy: before-hook-creation
data:
{{- range $path, $_ := .Files.Glob "migrations/*.sql" }}
{{ base $path }}: |-
{{ $.Files.Get $path | indent 4 }}
{{- end }}
{{- end }}
mkdir -p charts/shop-api/migrations charts/shop-api/templates/hooks cat > charts/shop-api/migrations/001_init.sql <<'EOF' CREATE TABLE IF NOT EXISTS schema_version (version int PRIMARY KEY, applied_at timestamptz DEFAULT now()); CREATE TABLE IF NOT EXISTS orders (id bigserial PRIMARY KEY, sku text NOT NULL, created_at timestamptz DEFAULT now()); INSERT INTO schema_version(version) VALUES (1) ON CONFLICT DO NOTHING; EOF cat > charts/shop-api/migrations/002_add_qty.sql <<'EOF' -- expand: add only nullable columns, so old code is unaffected ALTER TABLE orders ADD COLUMN IF NOT EXISTS qty int; INSERT INTO schema_version(version) VALUES (2) ON CONFLICT DO NOTHING; EOF
Every SQL file is idempotent (IF NOT EXISTS,ON CONFLICT DO NOTHING): a hook may be retried after a timeout or run more than once. In production, use a tool with a version table and locking, such as Flyway, Liquibase, or golang-migrate; the principle is the same.
{{- if .Values.migrations.enabled }}
apiVersion: batch/v1
kind: Job
metadata:
name: {{ include "shop-lib.fullname" . }}-db-migrate
labels:
{{- include "shop-lib.labels" . | nindent 4 }}
app.kubernetes.io/component: hook
annotations:
helm.sh/hook: pre-install,pre-upgrade
helm.sh/hook-weight: "0"
helm.sh/hook-delete-policy: before-hook-creation,hook-succeeded
helm.sh/hook-output-log-policy: hook-failed
spec:
backoffLimit: {{ .Values.migrations.backoffLimit }}
activeDeadlineSeconds: {{ .Values.migrations.activeDeadlineSeconds }} # must be less than helm --timeout
ttlSecondsAfterFinished: 3600
template:
metadata:
labels:
app.kubernetes.io/component: hook
spec:
restartPolicy: Never
containers:
- name: migrate
image: postgres:17
env:
- { name: PGHOST, value: {{ .Values.migrations.dbHost }} }
- { name: PGUSER, value: shop }
- { name: PGDATABASE, value: shop }
- name: PGPASSWORD
valueFrom: { secretKeyRef: { name: {{ .Values.migrations.credentialsSecret }}, key: password } }
command: ["sh", "-ec"]
args:
- |
until pg_isready -t 2; do echo "waiting for db"; sleep 2; done
for f in $(ls /migrations/*.sql | sort); do
echo "applying $f"; psql -v ON_ERROR_STOP=1 -f "$f"
done
{{- if .Values.migrations.injectFailure }}
echo "injected failure"; exit 1
{{- end }}
volumeMounts: [{ name: sql, mountPath: /migrations }]
volumes:
- name: sql
configMap: { name: {{ include "shop-lib.fullname" . }}-migrations }
{{- end }}
{{- if .Values.migrations.enabled }}
apiVersion: batch/v1
kind: Job
metadata:
name: {{ include "shop-lib.fullname" . }}-schema-verify
labels:
app.kubernetes.io/component: hook
annotations:
helm.sh/hook: pre-install,pre-upgrade
helm.sh/hook-weight: "5"
helm.sh/hook-delete-policy: before-hook-creation,hook-succeeded
spec:
backoffLimit: 0
activeDeadlineSeconds: 60
template:
spec:
restartPolicy: Never
containers:
- name: verify
image: postgres:17
env:
- { name: PGHOST, value: {{ .Values.migrations.dbHost }} }
- { name: PGUSER, value: shop }
- { name: PGDATABASE, value: shop }
- name: PGPASSWORD
valueFrom: { secretKeyRef: { name: {{ .Values.migrations.credentialsSecret }}, key: password } }
command: ["sh", "-ec"]
args:
- test "$(psql -tAc 'select max(version) from schema_version')" -ge {{ .Values.migrations.requiredVersion }}
{{- end }}
cat >> charts/shop-api/values.yaml <<'EOF' migrations: enabled: true dbHost: shop-db credentialsSecret: shop-db-credentials requiredVersion: 2 backoffLimit: 1 activeDeadlineSeconds: 240 injectFailure: false EOF sed -i 's/^version: .*/version: 0.3.0/' charts/shop-api/Chart.yaml helm upgrade shop-api charts/shop-api -n shop -f envs/base/common.yaml -f envs/base/shop-api.yaml \ -f envs/dev/common.yaml -f envs/dev/shop-api.yaml --wait --timeout 5m helm history shop-api -n shop --max 2
Release "shop-api" has been upgraded. Happy Helming! ... REVISION STATUS CHART DESCRIPTION 2 superseded shop-api-0.1.0 Upgrade complete 3 deployed shop-api-0.3.0 Upgrade complete
kubectl -n shop get job,cm -l app.kubernetes.io/component=hook kubectl -n shop exec shop-db-0 -- psql -U shop -d shop -c 'select * from schema_version'
NAME DATA AGE
configmap/shop-api-migrations 2 40s
version | applied_at
---------+-------------------------------
1 | 2026-11-16 ...
2 | 2026-11-16 ...
Both Jobs were deleted per hook-succeeded ; the ConfigMap has only before-hook-creation, so it is kept until the next upgrade. Note that it is not in helm get manifest , and helm uninstall it is not deleted either.
kubectl -n shop get deploy shop-api -o jsonpath='{.spec.template.spec.containers[0].env}' | head -c 200; echo
helm upgrade shop-api charts/shop-api -n shop -f envs/base/common.yaml -f envs/base/shop-api.yaml \
-f envs/dev/common.yaml -f envs/dev/shop-api.yaml \
--set migrations.injectFailure=true --set config.env.LOG_LEVEL=error \
--rollback-on-failure --timeout 3m
helm history shop-api -n shop --max 3
kubectl -n shop get job -l app.kubernetes.io/component=hook
... applying /migrations/001_init.sql ... applying /migrations/002_add_qty.sql injected failure Error: UPGRADE FAILED: release shop-api failed, and has been rolled back due to rollback-on-failure being set: pre-upgrade hooks failed: 1 error occurred: * job shop-api-db-migrate failed: BackoffLimitExceeded REVISION STATUS CHART DESCRIPTION 3 superseded shop-api-0.3.0 Upgrade complete 4 failed shop-api-0.3.0 Upgrade "shop-api" failed: pre-upgrade hooks failed: ... 5 deployed shop-api-0.3.0 Rollback to 3 NAME STATUS COMPLETIONS AGE shop-api-db-migrate Failed 0/1 70s
Observe: ① logs are printed by hook-output-log-policy: hook-failed to the terminal; ② LOG_LEVEL=error never took effect (main resources were not updated); ③ the failed Job stays in the cluster for debugging (without a hook-failed delete policy); at the next upgrade before-hook-creation will delete it first; ④ rollback created a new revision 5. Error text follows the actual Helm output.
apiVersion: v1
kind: Pod
metadata:
name: {{ include "shop-lib.fullname" . }}-test-version
annotations:
helm.sh/hook: test
helm.sh/hook-delete-policy: before-hook-creation,hook-succeeded
spec:
restartPolicy: Never
containers:
- name: curl
image: curlimages/curl:8.17.0
args: ["-fsS", "http://{{ include "shop-lib.fullname" . }}:{{ .Values.service.port }}/version"]
helm upgrade shop-api charts/shop-api -n shop -f envs/base/common.yaml -f envs/base/shop-api.yaml -f envs/dev/common.yaml -f envs/dev/shop-api.yaml --wait helm test shop-api -n shop --logs
TEST SUITE: shop-api-test-version
Last Started: ...
Phase: Succeeded
POD LOGS: shop-api-test-version
{"commit":"…","version":"6.17.0"}
The curl image tag is an example; change it to a pinned version available in your environment.
kubectl -n shop delete job -l app.kubernetes.io/component=hook --ignore-not-found (keep the ConfigMap and release).Case 1: migration succeeds, main update fails, old code crashes after rollback
Problem: A pre-upgrade migration renamed the orders.status column to state; the new Deployment then timed out because the image pull failed,--rollback-on-failure and the application was rolled back to the old version, but the old code reads status column and fails; the whole site returns 500s. Approach: Use expand/contract: version N only adds the state column and dual-writes; version N+1 switches reads to state; version N+2 is the first to delete status. The migration hook runs only “expand” changes. Limitation: Requires three releases; breaking changes must be manually approved.
Case 2: a stuck hook leaves the release in pending-upgrade
Problem: The migration Job waits for a database lock,backoffLimit: 6, with no activeDeadlineSeconds, and the Helm client (CI runner) was force-killed by the pipeline after 30 minutes, leaving the release stuck at pending-upgrade, and all later deployments reported another operation (install/upgrade/rollback) is in progress. Approach: Set the Job's activeDeadlineSeconds < --timeout < the pipeline timeout; set the migration script's lock_timeout. See lesson 7 for recovery. Limitation: A timeout that is too short prevents large-table migrations from finishing. Do not put large migrations in a hook.
Case 3: automatic backup before upgrade
Problem: Each upgrade needs a rollback-capable database snapshot beforehand. Approach: A pre-upgrade Job with weight -10 calls pg_dump to write to object storage (or call the cloud database snapshot API); the migration runs only at weight 0; the backup Job uses before-hook-creation,hook-succeeded. Limitation: Backing up large databases takes a long time; periodic snapshots by the database platform are a better fit, and the hook only checks that the latest snapshot is within N minutes.
Common errors and fixes
Error: UPGRADE FAILED: pre-upgrade hooks failed: warning: Hook pre-upgrade shop-api/templates/hooks/migrate-job.yaml failed: jobs.batch "shop-api-db-migrate" already exists
Cause: The delete policy only had hook-succeeded, and the Job that failed last time remains in the cluster; once the policy is written explicitly, Helm no longer adds the default before-hook-creation.
kubectl -n shop get job shop-api-db-migrate -o jsonpath='{.metadata.annotations}'
Fix: Delete the leftover Job; change the policy to before-hook-creation,hook-succeeded.
Error: UPGRADE FAILED: pre-upgrade hooks failed: timed out waiting for the condition (or context deadline exceeded)
Cause: The Job did not finish within --timeout the time limit: waiting for the database, slow image pulls, lock waits, and backoff retries.
kubectl -n shop describe job shop-api-db-migrate | tail -20 kubectl -n shop logs job/shop-api-db-migrate --all-containers
Fix: Set activeDeadlineSeconds and a small backoffLimit; make the orchestration layer deploy db first when the database is not ready; increase --timeout.
The upgrade “succeeded”, but the new code reports column "qty" does not exist
Cause: Used --no-hooks, or the migration Job template was migrations.enabled=false disabled, or the hook was mapped or skipped in Argo CD.
helm get hooks shop-api -n shop | grep -c 'kind: Job' helm history shop-api -n shop -o json | jq '.[-1].description'
Fix: Run the migration manually (kubectl create job --from cannot be used for deleted hooks, but you can helm template --show-only after apply); check the schema version at application startup and refuse to become ready.
After helm uninstall, the namespace still has the shop-api-migrations ConfigMap and Job
Cause: Hook resources do not belong to the release, so uninstall does not delete them (it only runs pre/post-delete hooks).
kubectl -n shop get all,cm -l app.kubernetes.io/component=hook
Fix: Add a common label to hooks and clean up by label in the uninstall process; set on the Job ttlSecondsAfterFinished.
1. List the name, event, and weight of all hooks in the current shop-api revision.
helm get hooks shop-api -n shop | grep -E '^ name:|helm.sh/hook(-weight)?:'
2. Urgently roll back to revision 3 without running hooks.
helm rollback shop-api 3 -n shop --no-hooks --wait
The team wants “the database to roll back automatically when a migration fails” and proposes a pre-rollback hook that runs reverse SQL. What do you think?
A pre-rollback hook runs only when a rollback is performed, and what it runs is the hooks defined in the rollback target revision —the old chart version does not know what migrations the new version made, so reverse SQL is hard to place correctly. A more reliable approach: only do backward-compatible expand migrations so old code also runs on the new schema, and rollback needs no database changes; ship breaking changes separately with backups or snapshots. A pre-rollback hook is better suited as a guard that “checks whether the current schema allows rollback” (failing when incompatible, to block the rollback).
Verified teaching videos
No Helm hooks video verified via YouTube oEmbed was found (most results were text tutorials). You can review first:
Official docs and source
Video storyboard script (about 100 seconds)
This courseware cannot directly generate a video or MP3, so a storyboard and narration script are provided.
Visual: on a timeline, the blocks -5, 0, and 5 appear in order, then a large block “main resources”, and finally post-upgrade.
Narration: pre-upgrade hooks run in ascending weight order; equal weights are sorted by name; main resources are updated only after all of them complete.
Visual: a progress bar appears next to the weight-0 Job block, until a green check mark shows Complete.
Narration: Jobs and Pods must wait until complete; other resources count as ready once created. Each hook has its own timeout.
Visual: the Job block turns red, and the blocks after it turn gray; Job logs scroll in the terminal; the release history shows failed and Rollback to 3.
Narration: if one hook fails, the later hooks and main resources do not run. Rollback only restores Kubernetes resources and does not undo database migrations.
Visual: three delete-policy cards, with before-hook-creation highlighted.
Narration: the default policy deletes the old resource before creation. Once a policy is written, the default is no longer added, so migration Jobs should write before-hook-creation plus hook-succeeded.
Module 5 · post-renderer and Kustomize (Helm 4 plugin)
- Describe the post-renderer changes in Helm 4:
--post-renderervalue is a plugin name (type: postrenderer/v1) no longer accept arbitrary executable file paths; extra arguments go through--post-renderer-args(can be given multiple times) to the plugin command. - Write a post-renderer plugin with the subprocess runtime:
plugin.yaml(apiVersion: v1,type,runtime,version,runtimeConfig.platformCommand) + a script that reads stdin and writes stdout. - Understand that Helm 4 by default passes hooks merged with regular templates to the post-renderer (Helm 3 never passes hooks), and how this affects Kustomize patches.
- Decide when to use a post-renderer, when to change the chart (add values), and when to fork.
helm template. Importance:★★★★What: at which step the post-renderer runs
After Helm renders templates into a manifest stream, before splitting hooks, sorting, and sending to Kubernetes, it writes the manifests to the post-renderer's stdin and reads its stdout as the new manifests. Empty output is an error post-renderer "x" produced empty output. The transformed manifests are what gets applied and written into the release manifest —so helm get manifest shows the post-patch result.
The Helm 4 plugin model (from Helm 4.3.2 source)
| Field | Value | Description |
|---|---|---|
apiVersion | v1 | Helm 4 plugin metadata v1; the old format without apiVersion is treated as legacy (supports only older capabilities such as CLI/getter) |
name | kustomize-pr | --post-renderer kustomize-pr uses exactly this |
type | postrenderer/v1 | one type per plugin (others include cli/v1,getter/v1) |
runtime | subprocess | Another runtime is Wasm (extism v1) |
version | SemVer | Required |
runtimeConfig.platformCommand | - command: "${HELM_PLUGIN_DIR}/run.sh" | can be by os/arch ; environment variables are expanded; --post-renderer-args appended as arguments |
The plugin process inherits Helm's environment variables and additionally gets HELM_PLUGIN_NAME,HELM_PLUGIN_DIR; the working directory is the current directory where helm runs. stderr is collected and shown in the error message on failure.
Hooks also go to the post-renderer (Helm 4 default: combined)
The Helm 4.3 SDK defines three strategies: combined (default: hooks and templates together as one stream),separate (two separate calls, to avoid Kustomize reporting duplicate IDs when the same resource appears in both hooks and templates),nohooks (templates only, i.e. Helm 3 behavior). As of 4.3.2, the CLI does not expose a switch (you can only set it via the SDK's PostRenderStrategy field), so when using the CLI, assume your patches will see hook resources: target precisely by kind/name, to avoid “patch all Deployments” accidentally hitting same-named resources in hooks.
Why: why you need it
- A third-party chart does not expose a field (tolerations, an extra sidecar, a certain annotation,
priorityClassName), and you do not want to fork. - Organization-wide enforced changes: add compliance labels to all manifests, replace the image registry (image proxy), inject securityContext.
- Temporary fix: a stopgap patch until the upstream bug is fixed.
How: choosing an approach
| Approach | Pros | Cons | When to use |
|---|---|---|---|
| Change the chart / add values (send a PR upstream) | Clearest; all users benefit; schema can be validated | Must wait for an upstream release | Preferred; always do this for in-house charts |
| post-renderer + Kustomize | No fork; patches are declarative and reviewable | Patches depend on the upstream manifest structure and may break when the chart is upgraded; plugin distribution is required | A few missing fields in a third-party chart |
| fork chart | Full control | Upstream changes must be merged continuously; highest long-term cost | Upstream is unmaintained or large changes are needed |
| Admission control mutation (Kyverno mutate, MutatingAdmissionPolicy) | Applies to all deployment methods | Implicit cluster-side changes that Helm's diff cannot see; may conflict with SSA field ownership | Platform-level policy |
When: post-renderer in GitOps
Flux HelmRelease supports it natively spec.postRenderers (built-in Kustomize patches, no plugin needed); Argo CD's Helm source does not support Helm post-renderers, and a common alternative is Kustomize's helmCharts field or a Config Management Plugin. So if the team uses Flux, this module's patches can be migrated directly to a HelmRelease.
--post-renderer ./kustomize.sh”—no, it must first be installed as a plugin. ② “The post-renderer can read values”: it only sees the rendered YAML; when parameters are needed, use --post-renderer-args or environment variables. ③ “Helm doesn't know about patched resources”: Helm applies and stores the patched manifests, and both diff and rollback are based on them; however helm template without --post-renderer shows the pre-patch result, so CI previews must pass the same arguments.Architecture diagram: the post-renderer plugin in the rendering pipeline
Decision diagram: what to do when a field is missing?
Interactive demo: each document in the post-renderer pipeline
simulation helm upgrade shop-web --post-renderer kustomize-pr --post-renderer-args overlays/prod. Choose a patch style and a failure, and step through to observe: which documents are in the stream Helm generates (including hooks), what the plugin receives, what Kustomize outputs, and what Helm finally applies and stores.
Core commands and flags
| Command | Purpose | Key flags / notes |
|---|---|---|
helm plugin install DIR|URL|oci://… | Install a plugin | Local directory = development mode (signature not verified); remote default --verify |
helm plugin list | List plugins and types | Confirm TYPE is postrenderer/v1 |
helm plugin package DIR | Package the plugin as tgz | --sign default true,--key,--keyring |
helm plugin verify PATH | Verify plugin signatures | Run before publishing to the team |
--post-renderer NAME | Specify the post-renderer plugin | install/upgrade/template all support it; can only be specified once |
--post-renderer-args ARG | Pass arguments to the plugin command | Can be repeated; appended in order |
helm plugin install ./plugins/kustomize-pr helm plugin list | grep kustomize-pr helm template shop-web charts/shop-web --post-renderer kustomize-pr --post-renderer-args overlays/prod \ | grep -E 'allowPrivilegeEscalation|patched-by'
Installing plugin from local directory (development mode)
Installed plugin: kustomize-pr
kustomize-pr 0.1.0 postrenderer/v1 ...
shop.example.com/patched-by: kustomize-pr
allowPrivilegeEscalation: false
How to verify:helm get manifest shop-web should show the patched field. Common mistakes: The script lacks execute permission (permission denied); on Windows .sh cannot run. Use platformCommand 's os: windows branch pointing to a PowerShell script. Production use: Package and sign the plugin, publish it to an internal OCI registry, and pre-install it in the CI runner image.
Lab 5: write the kustomize-pr plugin and patch shop-web (about 7 minutes)
apiVersion: v1
name: kustomize-pr
type: postrenderer/v1
runtime: subprocess
version: 0.1.0
sourceURL: https://example.com/platform/helm-plugins
runtimeConfig:
platformCommand:
- os: linux
command: "${HELM_PLUGIN_DIR}/run.sh"
- os: darwin
command: "${HELM_PLUGIN_DIR}/run.sh"#!/bin/sh
# Usage: --post-renderer kustomize-pr --post-renderer-args <overlay dir>
set -eu
OVERLAY="${1:?overlay dir argument required (--post-renderer-args)}"
[ -f "$OVERLAY/kustomization.yaml" ] || { echo "kustomize-pr: $OVERLAY/kustomization.yaml does not exist" >&2; exit 2; }
WORK="$(mktemp -d)"
trap 'rm -rf "$WORK"' EXIT
cp -R "$OVERLAY"/. "$WORK/"
cat > "$WORK/helm-output.yaml" # Helm rendered output (Helm 4 includes hooks by default)
kubectl kustomize "$WORK" # output to stdout, read by Helm
chmod +x plugins/kustomize-pr/run.sh
apiVersion: kustomize.config.k8s.io/v1beta1
kind: Kustomization
resources:
- helm-output.yaml
patches:
- target: { group: apps, version: v1, kind: Deployment, name: shop-web }
patch: |-
- op: add
path: /spec/template/spec/containers/0/securityContext
value: { allowPrivilegeEscalation: false }
- op: add
path: /spec/template/metadata/annotations
value: { shop.example.com/patched-by: kustomize-pr }
Note that the second operation will replace the entire annotations map (JSON Patch add replaces an existing path); to keep the existing annotations, use the path /spec/template/metadata/annotations/shop.example.com~1patched-by (requires annotations to already exist) or use a strategic merge patch. This is a typical example of post-renderer patches “depending on the upstream manifest structure”.
helm plugin install ./plugins/kustomize-pr helm template shop-web charts/shop-web -f envs/base/common.yaml \ --post-renderer kustomize-pr --post-renderer-args overlays/prod --show-only templates/deployment.yaml 2>/dev/null | head -1 # --show-only applies to template file names; after post-rendering, it is better to view the full output directly: helm template shop-web charts/shop-web -f envs/base/common.yaml \ --post-renderer kustomize-pr --post-renderer-args overlays/prod | grep -B2 -A2 allowPrivilegeEscalation helm upgrade shop-web charts/shop-web -n shop -f envs/base/common.yaml -f envs/base/shop-web.yaml \ -f envs/dev/common.yaml -f envs/dev/shop-web.yaml \ --post-renderer kustomize-pr --post-renderer-args overlays/prod --wait helm get manifest shop-web -n shop | grep -c 'patched-by'
securityContext:
allowPrivilegeEscalation: false
...
Release "shop-web" has been upgraded. Happy Helming!
1# ① Helm 3 syntax helm template shop-web charts/shop-web --post-renderer ./plugins/kustomize-pr/run.sh 2>&1 | head -2 # ② overlay does not exist helm template shop-web charts/shop-web --post-renderer kustomize-pr --post-renderer-args overlays/nope 2>&1 | tail -2
Error: ... plugin "./plugins/kustomize-pr/run.sh" ... not found Error: failed to invoke post-renderer plugin "kustomize-pr": ... kustomize-pr: overlays/nope/kustomization.yaml does not exist
Job patches,helm get hooks shop-api and the Jobs in it are also modified. This is the result of the Helm 4 combined strategy.Cleanup: keep the plugin until the combined lab; to uninstall,
helm plugin uninstall kustomize-pr.Case 1: add tolerations to a third-party chart
Problem: A monitoring agent's chart does not expose tolerations for its Job, so it cannot run on a dedicated node pool with only tainted nodes. Approach: Patch that Job precisely in the post-renderer overlay and send an upstream PR at the same time; in the patch file header, comment the upstream issue link and the condition “delete after upstream merge”. Limitation: If the Job is a hook, the patch does not take effect under Helm 3 but does under Helm 4. The behavior changes when migrating to Helm 4, so regression testing is needed.
Case 2: image registry rewrite
Problem: Production clusters may only pull images through the internal image proxy, and some charts do not have global.imageRegistry. Approach: Kustomize images: Rewrite newName by image name in the images field; all releases use the same plugin via Helmfile's postRenderer/postRendererArgs setting to use the same plugin. Limitation: Only image fields that Kustomize recognizes (standard paths such as containers and initContainers) can be rewritten; images inside CRDs (such as an Operator's CR) require configurations custom field specifications.
Case 3: no longer need the plugin after migrating to Flux
Problem: The team moved from a helm upgrade script in CI to Flux. Approach: Migrate the patches from the overlay unchanged to the HelmRelease's spec.postRenderers[].kustomize.patches, applied by helm-controller. Limitation: Flux's postRenderers is a Kustomize subset built into the controller; complex generators (such as configMapGenerator) may not apply, so follow the Flux docs.
Common errors and fixes
Error: post-renderer "kustomize-pr" produced empty output
Cause: The script did not write the result to stdout (it wrote to a file, or the kustomize output was redirected).
helm template x charts/shop-web > /tmp/in.yaml sh -x ~/.local/share/helm/plugins/kustomize-pr/run.sh overlays/prod < /tmp/in.yaml | head
Fix: Make sure the last command writes to stdout; write debug info to stderr. Use helm env HELM_PLUGINS to check.
plugin "./run.sh" not found / post-renderer plugin not found
Cause: In Helm 4, --post-renderer accepts only the name of an installed plugin (looked up by postrenderer/v1 type).
Fix: Package it as a plugin following this module's structure and helm plugin install; pre-install the plugin in CI.
failed to invoke post-renderer plugin "kustomize-pr": … no matches for Id Deployment.v1.apps/shop-web.[noNs]; failed to find unique target for patch
Cause: The patch target is not in the input stream: the resource name changed (chart upgrade or different fullname rules), the namespace does not match, or a strategic merge patch points to an object that does not exist.
helm template shop-web charts/shop-web | grep -E '^kind:|^ name:' | paste - -
Fix: Use a target selector for the JSON6902/patch (it does not error when nothing matches, but it also has no effect, so assert the patch result in CI); regression-test the overlay on each chart upgrade.
may not add resource with an already registered id
Cause: The same resource (same GVK/namespace/name) appears twice in the input. Under the Helm 4 combined strategy, a resource is rendered both as a hook and as a regular template (for example, a same-named ConfigMap).
Fix: Give the hook resource a different name, or use the SDK's separate strategy (not yet exposed by the CLI); or inside the plugin, by helm.sh/hook annotation, split and process them separately.
1. Check the local plugin directory and confirm the kustomize-pr metadata.
helm env HELM_PLUGINS cat "$(helm env HELM_PLUGINS)/kustomize-pr/plugin.yaml"
2. Package and sign the plugin as a tgz (using the key “platform”).
helm plugin package plugins/kustomize-pr --key platform --keyring ~/.gnupg/secring.gpg -d dist/
A team uses a post-renderer to add resources, probes, and an HPA to their in-house shop-api, while the chart itself barely exposes any values. What is wrong with this design?
A post-renderer suits small patches to third-party charts. An in-house chart should expose these settings through values + schema; otherwise helm template (without the plugin) differs from the real deployment, the chart cannot be used independently, the patches break as the chart structure changes, and tools that do not support Helm post-renderers, such as Argo CD, cannot reuse it. These settings should move back into the chart, and the post-renderer should keep only organization-wide cross-cutting patches (or switch to admission policies).
Verified teaching videos
No video verified via YouTube oEmbed that explains the Helm 4 post-renderer plugin was found (the Helm 4 plugin model is new; existing videos mostly show the Helm 3 executable-file approach, which no longer applies).
Official docs and source
- Advanced Helm Techniques: Post Rendering
- The Helm Plugins Guide
- helm/helm pkg/postrenderer
- Kustomize patches
- Flux HelmRelease post-renderers
Video storyboard script (about 80 seconds)
This courseware cannot directly generate a video or MP3, so a storyboard and narration script are provided.
Visual: a conveyor belt; on the left, “Render templates” outputs YAML cards, and in the middle is a machine labeled kustomize-pr.
Narration: the post-renderer runs after rendering and before applying. It reads manifests from stdin and writes manifests to stdout.
Visual: the plugin.yaml card zooms in, highlighting type postrenderer/v1 and platformCommand.
Narration: in Helm 4, the post-renderer must be a plugin. The command line takes the plugin name, and arguments use post-renderer-args.
Visual: cards labeled hook are mixed onto the conveyor belt and also enter the machine.
Narration: Helm 4 also passes hooks to the post-renderer by default. Patch targets must be precise to avoid collateral damage.
Visual: three paths (change the chart, post-renderer, fork), labeled preferred, small patch, and last resort, respectively.
Narration: add values for in-house charts; keep the post-renderer for small patches to third-party charts.
Module 6 · Managing CRDs and Operators in charts
- Explain precisely
crds/the behavior of the directory: install (andupgrade --installthe first install) creates those that do not yet exist CRDs and waits for them to be Established; skips them if they already exist; upgrade does not update them, uninstall does not delete them; no template rendering;--skip-crdscan be skipped. - Compare three CRD management approaches:
crds/the directory,templates/(usually with a toggle andhelm.sh/resource-policy: keep),a separate CRD chart (or a separate GitOps application). - Design a CRD upgrade strategy (only compatible schema changes, upgrade the CRD before the Operator, storage version migration) and the deployment order “Operator before CR”.
What: the three places where Helm handles CRDs
crds/ directory | templates/ in | Separate CRD chart / separate application | |
|---|---|---|---|
| Template rendering | ✗ Raw YAML, cannot use {{ }} | ✓ | ✓ (templates in the chart) or plain YAML |
| First install | ✓ Created before other resources and waits for Established | ✓ Created in kind order (CRDs first) | ✓ Separate release, before the Operator |
| Upgrade | ✗ Never updated | ✓ Updated with the release | ✓ Has independent versioning and approval |
| Uninstall | ✗ Never deleted | ⚠ Gets deleted → all CRs cascade-deleted (unless resource-policy: keep) | protected by the keep policy |
| Shared by multiple releases | The second release skips the already existing CRD | ⚠ Two releases fight over ownership (invalid ownership metadata) | ✓ One owner |
| appears in the manifest | ✗ | ✓ | ✓ (in the CRD release) |
Why: why Helm does not upgrade crds/
CRDs are cluster-scoped resources, shared by all namespaces and all releases. Upgrading a CRD may make other teams' CRs no longer match the schema; deleting a CRD makes the API server delete all instances of that type all CRs (data loss). The Helm maintainers chose the most conservative semantics: they only help you “install it the first time”, and afterwards leave management to you explicitly. In the Helm 4.3 source, the hook deletion logic also deliberately skips CustomResourceDefinition.
How: recommended architecture (shop platform)
- CRD layer:
external-secrets's CRDs are managed by its official chart (the ESO chart installs CRDs via templates by default, which can be turned off via values; check the chart README for the exact key names); in-house CRDs go into a separate chartshop-crds, with the CRDs written intemplates/and addhelm.sh/resource-policy: keep. - Operator layer: Operator releases (ESO, cert-manager, etc.), after the CRDs.
- CR layer: CRs such as ExternalSecret and Certificate in application charts, deployed Ready after the Operator (orchestration layer
needs/dependsOn/sync wave). - Application charts use
.Capabilities.APIVersions.Has "external-secrets.io/v1/ExternalSecret"to guard: when the CRD does not existfailgive a clear error instead of letting users seeno matches for kind.
CRD upgrade strategy
- Compatible changes (adding optional fields, adding a new version while keeping the old one
served: true): upgrade the CRD directly, then upgrade the Operator. - Adding an API version: the CRD lists both v1alpha1 and v1, but only one can be
storage: true; a conversion webhook (provided by the Operator) is needed, or both must have the same schema; after switching the storage version, use Storage Version Migrator (v1.37 GA,storagemigration.k8s.io/v1) to rewrite existing objects; only then can the old version be setserved: falseand removed fromstatus.storedVersions. - Breaking changes (removing fields, tightening validation): first confirm no CR uses them, then proceed step by step with expand/contract.
- For large CRDs, use
kubectl apply --server-sidefor updates, to avoid the client-side applylast-applied-configurationannotation exceeding the 256 KiB limit.
When: choosing which approach
- Third-party Operator: follow its official recommendation (some charts use templates with a toggle; others require installing the
kubectl applyCRDs first). - In-house Operator / CRDs: a separate CRD chart, owned by the platform team.
crds/crds/ directory: only suitable for CRDs that are “installed once and almost never change”, or demo charts.
helm uninstall retains the CRD, so CRDs in templates/ are also safe”: CRDs in templates/ are deleted, along with all CRs. ③ “A hook can be used to install CRDs”: hook resources are unmanaged, and older docs no longer recommend it; use a separate chart.Layer diagram: CRD → Operator → CR
Lifecycle comparison: the same CRD placed in different locations
Interactive simulator: where should the CRD go? — install / upgrade / uninstall
Choose where the CRD goes, run the 4 operations in sequence, and observe the CRD schema version in the cluster, whether the CR survives, and Helm's actual behavior and output.
Core commands and flags
| Command | Purpose | Key flags / notes |
|---|---|---|
helm install --skip-crds | Do not install the CRDs in the crds/ directory | Use when CRDs are managed by another process; for upgrade, --skip-crds it is only --install meaningful on first install. |
helm template --include-crds | Rendered output includes the CRDs in crds/ | Use for GitOps pre-rendering or when applying CRDs separately |
helm show crds CHART | Outputs only the chart's crds/ content | Used with kubectl apply --server-side manual CRD upgrades |
kubectl apply --server-side -f crds.yaml | Upgrade large CRDs | avoids exceeding the last-applied annotation size limit; --force-conflicts takes over fields |
kubectl get crd X -o jsonpath='{.status.storedVersions}' | Check previously used storage versions | Migrate before removing old versions |
kubectl wait --for=condition=Established crd/X | Wait for the CRD to be available | Run before creating CRs in scripted deployments |
# Manually upgrade the CRDs in the crds/ directory of a third-party chart (Helm does not do this) helm show crds external-secrets/external-secrets --version 2.15.0 | kubectl apply --server-side -f - --dry-run=server | head -3 # Guard against API existence in the chart helm template shop-db charts/shop-db --api-versions external-secrets.io/v1/ExternalSecret | grep -c 'kind: ExternalSecret'
(If this chart's CRDs are in templates/, the show crds output is empty — follow the chart's actual structure) 1
How to verify:helm template Without connecting to a cluster,.Capabilities.APIVersions covers only built-in APIs; use --api-versions to simulate; helm install --dry-run=server otherwise read the real cluster. Common errors: Rendered results in CI do not match the cluster. Production use: The Operator upgrade runbook lists "apply the CRDs first" as a separate step.
Lab 6: verify hands-on that crds/ is not upgraded, then switch to a standalone CRD chart (about 8 minutes)
mkdir -p /tmp/crd-demo/crds /tmp/crd-demo/templates
cat > /tmp/crd-demo/Chart.yaml <<'EOF'
apiVersion: v2
name: crd-demo
version: 0.1.0
EOF
cat > /tmp/crd-demo/crds/promotions.yaml <<'EOF'
apiVersion: apiextensions.k8s.io/v1
kind: CustomResourceDefinition
metadata:
name: promotions.shop.example.com
spec:
group: shop.example.com
scope: Namespaced
names: { plural: promotions, singular: promotion, kind: Promotion }
versions:
- name: v1alpha1
served: true
storage: true
schema:
openAPIV3Schema:
type: object
properties:
spec:
type: object
properties:
name: { type: string }
EOF
helm install crd-demo /tmp/crd-demo -n shop
kubectl get crd promotions.shop.example.com -o jsonpath='{.spec.versions[0].schema.openAPIV3Schema.properties.spec.properties}'; echo
NAME: crd-demo ... STATUS: deployed
{"name":{"type":"string"}}sed -i 's/ name: { type: string }/ name: { type: string }\n discount: { type: integer }/' /tmp/crd-demo/crds/promotions.yaml
sed -i 's/^version: 0.1.0/version: 0.2.0/' /tmp/crd-demo/Chart.yaml
helm upgrade crd-demo /tmp/crd-demo -n shop
kubectl get crd promotions.shop.example.com -o jsonpath='{.spec.versions[0].schema.openAPIV3Schema.properties.spec.properties}'; echo
cat > /tmp/promo.yaml <<'EOF'
apiVersion: shop.example.com/v1alpha1
kind: Promotion
metadata: { name: black-friday, namespace: shop }
spec: { name: "Black Friday", discount: 30 }
EOF
kubectl apply -f /tmp/promo.yaml # default: strict field validation
kubectl apply -f /tmp/promo.yaml --validate=warn # simulates a client that skips strict validation (such as some Operators/scripts)
kubectl -n shop get promotion black-friday -o jsonpath='{.spec}'; echo
Release "crd-demo" has been upgraded. Happy Helming!
{"name":{"type":"string"}}
Error from server (BadRequest): ... strict decoding error: unknown field "spec.discount"
Warning: unknown field "spec.discount"
promotion.shop.example.com/black-friday created
{"name":"Black Friday"}
The CRD still has the old schema: strict validation rejects the object outright; without strict validation, the field is discount silently pruned by the API server's structural schema (pruning) away. This is the typical root cause of "the Operator's new features do not take effect after an upgrade". Error/warning wording depends on the actual version.
helm uninstall crd-demo -n shop kubectl get crd promotions.shop.example.com; kubectl -n shop get promotion
NAME CREATED AT promotions.shop.example.com 2026-11-16T... NAME AGE black-friday 1m
mkdir -p charts/shop-crds/templates
cat > charts/shop-crds/Chart.yaml <<'EOF'
apiVersion: v2
name: shop-crds
description: in-house shop platform CRD (cluster-scoped, maintained by the platform team)
version: 0.2.0
EOF
# Reuse the CRD from the previous step (already includes discount), and add the keep annotation
sed 's/^ name: promotions.shop.example.com/ name: promotions.shop.example.com\n annotations:\n helm.sh\/resource-policy: keep/' /tmp/crd-demo/crds/promotions.yaml > charts/shop-crds/templates/promotions.yaml
helm upgrade --install shop-crds charts/shop-crds -n shop --take-ownership
kubectl get crd promotions.shop.example.com -o jsonpath='{.spec.versions[0].schema.openAPIV3Schema.properties.spec.properties}'; echo
kubectl -n shop patch promotion black-friday --type merge -p '{"spec":{"discount":30}}'
kubectl -n shop get promotion black-friday -o jsonpath='{.spec}'; echo
Release "shop-crds" does not exist. Installing it now.
{"discount":{"type":"integer"},"name":{"type":"string"}}
promotion.shop.example.com/black-friday patched
{"discount":30,"name":"Black Friday"}
--take-ownership Lets the new release skip the check that "the resource does not belong to this release" and writes Helm's ownership annotations. In production, first confirm that no other release owns this CRD before running it.
helm uninstall shop-crds -n shop kubectl get crd promotions.shop.example.com && kubectl -n shop get promotion black-friday
These resources were kept due to the resource policy: [CustomResourceDefinition] promotions.shop.example.com release "shop-crds" uninstalled NAME CREATED AT promotions.shop.example.com ... NAME AGE black-friday 3m
kubectl -n shop delete promotion black-friday kubectl delete crd promotions.shop.example.com rm -rf /tmp/crd-demo /tmp/promo.yaml # If you keep the charts/shop-crds directory for reference, remember its CRDs will be recreated on the next install
Case 1: after an Operator upgrade, the new features "do nothing"
Problem: A team upgraded an Operator chart from 1.x to 2.x; new CR fields disappeared right after being written. Approach: Investigation showed the CRD lives in the chart's crds/ directory, which Helm never upgrades; following the Operator's upgrade docs, first helm show crds … | kubectl apply --server-side -f - then helm upgrade, and added this step to the pipeline. Limitation: CRDs applied manually are no longer in sync with Helm; the long-term fix is a standalone CRD chart or managing CRDs separately through GitOps.
Case 2: accidentally deleting a CRD caused loss of certificates across the cluster
Problem: Someone uninstalled an Operator release that put its CRD in templates/ without keep; the API server cascade-deleted all CRs of that type, and hundreds of certificate objects disappeared. Approach: Restore CRs from a Velero backup; change the chart to add helm.sh/resource-policy: keep; add a ValidatingAdmissionPolicy to the CRD that blocks deletion by non-platform accounts. Limitation: With keep, uninstall leaves an orphaned CRD behind; reinstalling requires --take-ownership.
Case 3: CRD ordering in GitOps
Problem: During Argo CD sync, the ExternalSecret was created before the ESO CRD, and reported no matches for kind. Approach: On the CRD Application, set sync-wave argocd.argoproj.io/sync-wave: "-2", Operator -1, app 0; the app Application adds SkipDryRunOnMissingResource=true sync option as a fallback. In Flux, use HelmRelease dependsOn and install.crds/upgrade.crds policy (such as CreateReplace) to control CRDs. Limitation: Waves only guarantee order, not that the webhook is ready; health checks are still needed.
Common errors and fixes
resource mapping not found for name: "x" namespace: "shop" from "": no matches for kind "Promotion" in version "shop.example.com/v1alpha1" ensure CRDs are installed first
Cause: The CR was submitted before its CRD (ordering problem), or the CRD was --skip-crds not installed under the
kubectl get crd | grep shop.example.com kubectl api-resources --api-group=shop.example.com
Fix: Install the CRD chart first; the app chart uses a Capabilities guard and fail fails with a readable message.
New CRD fields disappear after being written (unknown field / field pruned)
Cause: The CRD in the cluster still has the old schema (crds/ is not upgraded).
kubectl get crd promotions.shop.example.com -o yaml | yq '.spec.versions[].schema' helm show crds CHART --version NEW | diff - <(kubectl get crd promotions.shop.example.com -o yaml)
Fix: Use kubectl apply --server-side to upgrade the CRD, or migrate to a standalone CRD chart.
The CustomResourceDefinition "x" is invalid: status.storedVersions[0]: Invalid value: "v1alpha1": must appear in spec.versions
Cause: The new CRD dropped an old version that is still storedVersions listed in the stored versions.
kubectl get crd X -o jsonpath='{.status.storedVersions}'
Fix: First keep the old version (served: false is also acceptable). Use Storage Version Migrator to migrate stored objects to the new storage version, then remove the old version from status.storedVersions (via a status subresource patch); the deletion comes last.
Internal error occurred: failed calling webhook "validate.externalsecret.external-secrets.io": … connect: connection refused
Cause: The Operator's admission webhook is not ready yet (just installed or upgraded), so CR creation is rejected.
kubectl -n external-secrets get deploy,endpoints kubectl get validatingwebhookconfiguration | grep external
Fix: Have the Operator release use --wait; the orchestration layer waits for the Operator to be Ready before deploying the app; retry.
1. Install a chart without installing the CRDs in its crds/ directory, and separately apply its CRDs using SSA.
helm show crds REPO/CHART --version X | kubectl apply --server-side -f - helm install NAME REPO/CHART --version X --skip-crds
2. In CI, render the chart, simulating a cluster where the ESO v1 API already exists.
helm template shop-db charts/shop-db --api-versions external-secrets.io/v1/ExternalSecret
Two teams' charts each include the same CRD in templates/ (for "out-of-the-box" use). What happens? How do you govern it?
When the second release is installed, it fails with invalid ownership metadata because another release already owns the CRD; if someone uses --take-ownership to force-adopt it, the two releases overwrite the CRD schema in turn, and uninstalling either release (without keep) deletes the CRD and all CRs of both teams. Governance: move the CRD into a standalone chart maintained by a single owner; business charts contain only CRs and declare their dependency on the CRD version (docs + Capabilities check).
Verified instructional videos
No dedicated video on "Helm managing CRD lifecycle" could be verified via the YouTube oEmbed API.
Official documentation
- Best Practices: Custom Resource Definitions
- Charts: Limitations on CRDs
- Versions in CustomResourceDefinitions
- Storage Version Migration
Video storyboard (about 80 seconds)
This courseware cannot directly generate a video/MP3, so a storyboard and narration script are provided instead.
Visual: the crds/ directory in the chart folder glows; on the first install, the CRD appears in the cluster.
Narration: CRDs in the crds directory are created only on the first install.
Visual: the chart upgrades to a new version; crds now has a discount field, but the CRD in the cluster is unchanged; the discount in the CR is snipped off by scissors.
Narration: during an upgrade Helm does not update it, and the API server prunes the new field. Uninstall does not delete it either.
Visual: when the CRD in templates is uninstalled, all CRs fall like dominoes; with the keep annotation, the dominoes stay standing.
Narration: a CRD placed in templates is deleted on uninstall, along with all CRs. For a standalone CRD chart, add resource-policy: keep.
Visual: a three-step staircase: CRD → Operator → app.
Narration: the order is always: CRD first, then the Operator, and finally the app that uses the CRs.
Module 7 · Zero-downtime upgrades and compatibility design
- Classify a chart change as one of: in-place update (safe rolling update),delete and recreate (rename, kind change),upgrade failure (immutable field), and explain Helm 4.3's execution order: first create/update the resources in the new manifest,immediately followed by deleting resources from the old manifest that no longer exist,then only then wait for readiness.
- Use
helm.sh/resource-policy: keepto protect non-disposable resources such as PVCs, Secrets, and CRDs; understand that it applies during both upgrade and uninstall, and that the resources it leaves behind become "orphans". - Templatize the PDB,
maxSurge/maxUnavailable/minReadySeconds/progressDeadlineSeconds, preStop; when HPA is enabled, do not renderreplicas. - Use
.Capabilities.APIVersions,.Capabilities.KubeVersionandkubeVersionconstraints to handle API deprecation; evolve values by keeping old and new keys side by side, with a NOTES deprecation notice, and removal in the next major version.
What: how Helm turns the old manifest into the new manifest
During an upgrade, Helm gets two resource lists: current (the manifest of the previous revision) and target (the new rendering). Resource identity = GVK + namespace + name. Helm 4.3's KubeClient.Update:
- For each resource in target: create it if it does not exist; if it exists, update it using SSA (default) or a three-way merge patch;
- For resources that are in current but not in target (
originals.Difference(targets)): if it carrieshelm.sh/resource-policy: keepit is skipped; otherwise it is deleted immediately (background cascade); - Only after returning does it enter
--waitthe wait phase.
Step 2 happens before waiting, so a "rename" deletes the old Deployment while the new Deployment has no Ready Pods yet,causing an outage; renaming a Service breaks DNS for all clients.
Change classification
| Change | Helm/K8s behavior | Consequence | Safe approach |
|---|---|---|---|
| Pod template (image, env, annotations, resources) | In-place update → Deployment rolls | ✓ Zero downtime (if probes, PDB, and preStop are correct) | — |
| Resource Rename (fullname rule changes, release rename, nameOverride) | Create new + delete old immediately | ✗ Outage; renaming a PVC = a new empty volume | Decouple names from the release (Module 1); if necessary, run old and new side by side before switching |
| Change kind (Deployment → StatefulSet) | Same as above | ✗ Outage | Two steps: create the new one and shift traffic → delete the old one in the next version |
Deployment/StatefulSet spec.selector | API server rejects | ✗ field is immutable, upgrade fails | Selectors never change; if they really must change, rename and migrate |
StatefulSet volumeClaimTemplates,serviceName | Rejected (fields that cannot be modified) | ✗ Upgrade fails | Create a new StatefulSet or kubectl delete sts --cascade=orphan ; Helm rebuilds afterwards. |
Service clusterIP, Job spec.template | Rejected | ✗ Upgrade fails | Do not templatize clusterIP; use a hook for one-off tasks (rebuilt each time) |
| Delete a template file / turn off a switch | Immediately delete the corresponding resource | ⚠ If it is a PVC/Secret, data is lost | Add keep to stateful resources |
--force-replace (previously --force) | Delete and recreate conflicting resources | ✗ Outage | Use only in incidents |
Why: two additional points to note for Helm 4
- SSA and field ownership: on new installs, Helm 4 defaults to server-side apply (field manager is Helm); upgrade
--server-side=autokeeps the previous method. If someone useskubectl scale/editchanges a Helm-managed field, the next upgrade may conflict (--force-conflictsforce takeover); the HPA-managedreplicasshould not be rendered by the chart. See Lesson 7 for details. - Strict field validation: when updating resources, Helm 4.3 uses by default
Strictfield validation: if the manifest contains a field the cluster API does not recognize (for example, a field written for a newer K8s version and deployed to an older cluster), the deployment fails outright instead of silently discarding it. Use.Capabilitiesto render based on cluster capabilities.
How: compatibility design toolbox
helm.sh/resource-policy: keep: skipped on both upgrade deletion and uninstall; resources keep their original Helm annotations, and reinstalling requires--take-ownership.Chart.yamlkubeVersion: ">=1.33.0-0": reject incompatible clusters before rendering (-0so that pre-release versions such asv1.35.0-eks-xxxalso match)..Capabilities.APIVersions.Has "policy/v1/PodDisruptionBudget": choose a version or skip a resource based on API availability.- values evolution: new keys get default values; when renaming
coalesce .Values.new .Values.oldsupport the old key, and inNOTES.txtprint a deprecation warning; in the next major version remove the old key and forbid it in the schema ("not": {"required": ["old"]}). - SemVer: any change that causes delete-and-recreate or requires users to change values should bump the chart's major version, and the steps should be spelled out in the README upgrade notes.
When: ask three questions before each chart release
- Rendered resources set of names has it changed? (
helm templatecompare old and new kind/name) - Does it touch immutable fields? (selector, volumeClaimTemplates, clusterIP)
- Does the old values file still work? (using the previous version's
envs/*to render the new chart)
--rollback-on-failure " can rescue a rename-caused outage" — rollback recreates the old resources, but the outage has already happened, and when a PVC is renamed its data volume has also been deleted. ③ "Upgrading only changed a label, so the selector is unaffected" — but if the library's selectorLabels includes this label, it triggers field is immutable.Sequence diagram: rename causes outage (Helm 4.3 Update order)
Decision diagram: what happens for a chart change?
Interactive simulator: upgrade change classifier + availability curve
Choose a chart change and click "Upgrade". The simulator advances in Helm 4.3's real order (create/update → delete the difference → wait), and plots the number of Ready Pods behind the Service; the terminal below shows the responses from Helm and the API server.
Core commands and flags
| Command | Purpose | Notes |
|---|---|---|
helm diff upgrade REL CHART (helm-diff plugin) | Preview changes, including added/removed resources | If you see - Deployment shop-api be wary |
helm template … | yq 'select(.kind) | .kind + "/" + .metadata.name' | Extract the set of resource identities | Compare old and new charts |
helm upgrade --dry-run=server | Server-side validation (including immutable fields and strict field validation) | Does not persist anything |
helm upgrade --take-ownership | Adopt existing resources (orphaned / created with kubectl) | Migration; reinstall after keep |
--rollback-on-failure | Automatic rollback on failure (implies --wait=watcher) | formerly --atomic |
kubectl delete sts X --cascade=orphan | Delete a StatefulSet but keep Pods/PVCs | Standard technique for changing immutable fields |
# Before release: compare the set of resource identities of the old and new charts
ids() { helm template shop-api "$1" -f envs/base/common.yaml -f envs/base/shop-api.yaml | yq -N 'select(.kind) | .kind + "/" + .metadata.name' | sort; }
git stash -q && ids charts/shop-api > /tmp/old.txt; git stash pop -q
ids charts/shop-api > /tmp/new.txt
diff /tmp/old.txt /tmp/new.txt && echo "resource identities unchanged ✓"
resource identities unchanged ✓
# Server-side dry run: can catch "field is immutable" and strict field validation errors early helm upgrade shop-api charts/shop-api -n shop -f envs/base/common.yaml -f envs/base/shop-api.yaml \ -f envs/dev/common.yaml -f envs/dev/shop-api.yaml --dry-run=server > /dev/null && echo "server dry-run OK"
How to verify: An empty diff + a successful server dry-run ≈ no delete-and-recreate and no immutable fields touched. Common mistakes: Only doing helm template (client-side) validation, which misses server-side rejections. Production use: Put these two steps into PR checks (Lesson 5 CI). Note that --dry-run=server also renders hooks but does not run them.
values deprecation notice (NOTES.txt)
{{- if hasKey .Values "replicas" }}
⚠ DEPRECATED: values key "replicas" has been renamed to "replicaCount" and will be removed in chart 1.0.0.
It still reads replicas={{ .Values.replicas }} for now; please update your values file as soon as possible.
{{- end }}
shop-api {{ .Chart.AppVersion }} deployed to {{ .Release.Namespace }} (environment: {{ dig "environment" "not set" (.Values.global | default dict) }})
replicas: {{ coalesce .Values.replicas .Values.replicaCount }}
Lab 7: zero-downtime upgrade drill + two counterexamples (about 9 minutes)
kubectl -n shop run probe --image=curlimages/curl:8.17.0 --restart=Never --command -- sh -c \
'while true; do c=$(curl -s -o /dev/null -m 1 -w "%{http_code}" http://shop-api:9898/readyz); echo "$(date +%T) $c"; sleep 0.2; done'
kubectl -n shop logs -f probe | grep -v ' 200$'
Prints only non-200 lines; silence = zero downtime.
helm upgrade shop-api charts/shop-api -n shop -f envs/base/common.yaml -f envs/base/shop-api.yaml \ -f envs/prod/common.yaml -f envs/prod/shop-api.yaml \ --set config.env.PODINFO_UI_MESSAGE="v2 rolling" --wait --timeout 5m kubectl -n shop rollout history deploy/shop-api | tail -3
The probe terminal should stay quiet. Prerequisites: maxUnavailable: 0, readinessProbe,preStop sleep 5, PDB (enabled in the prod layer, 4 replicas).
cp charts/shop-lib/templates/_names.tpl /tmp/_names.bak
sed -i 's|^app.kubernetes.io/instance: {{ .Release.Name }}|&\napp.kubernetes.io/component: server|' charts/shop-lib/templates/_names.tpl
helm dependency update charts/shop-api >/dev/null
helm upgrade shop-api charts/shop-api -n shop -f envs/base/common.yaml -f envs/base/shop-api.yaml \
-f envs/prod/common.yaml -f envs/prod/shop-api.yaml --dry-run=server 2>&1 | grep -o 'field is immutable' | head -1
cp /tmp/_names.bak charts/shop-lib/templates/_names.tpl && helm dependency update charts/shop-api >/dev/null
field is immutable
The server dry-run exposes the problem early; production is unaffected. The real error is Deployment.apps "shop-api" is invalid: spec.selector: Invalid value: …: field is immutable.
helm upgrade shop-api charts/shop-api -n shop -f envs/base/common.yaml -f envs/base/shop-api.yaml \ -f envs/prod/common.yaml -f envs/prod/shop-api.yaml --set fullnameOverride=shop-api-v2 --wait --timeout 5m kubectl -n shop get deploy,svc | grep shop-api
10:42:05 000 10:42:05 000 ... (Service shop-api has been deleted, DNS resolution fails; continues until recovery)
The Service was also renamed to shop-api-v2, so clients connecting to shop-api will keep failing — this is more serious than a brief Deployment outage. Restore immediately:
helm rollback shop-api -n shop --wait kubectl -n shop get deploy,svc | grep shop-api
volumeClaimTemplates PVCs are not in the release to begin with (the StatefulSet controller creates them); if your chart uses a standalone PVC template, add:
metadata:
annotations:
helm.sh/resource-policy: keep
StatefulSet also has persistentVolumeClaimRetentionPolicy (default Retain) controls whether PVCs are deleted on deletion or scale-down.
kubectl -n shop delete pod probe; confirm with helm history shop-api -n shop that the latest revision is deployed.Case 1: a 20-minute outage caused by renaming a release
Problem: A team renamed the release from api to shop-api (new install + uninstall of the old one), and the chart's fullname became {{ .Release.Name }}-{{ .Chart.Name }}, so all resource names, Service DNS, and PVCs changed, and the Ingress pointed at the old Service name. Approach: In the library, resource names are decoupled from the release name (Module 1's shop-lib.fullname uses only the chart name); during migration, first add keep to the old resources,helm uninstall After the old release is removed, use --take-ownership to let the new release adopt resources with the same names. Limitation: The selector includes app.kubernetes.io/instance (= release name), so renaming the release still changes the selector; this trade-off must be decided at design time (the library can allow overriding the instance label).
Case 2: after a K8s upgrade, helm upgrade reports that the API does not exist
Problem: When the cluster was upgraded around 1.24, the old release's manifest still contained the removed policy/v1beta1 PDB API,helm upgrade reported unable to build kubernetes objects from current release manifest. Approach: The chart uses .Capabilities.APIVersions.Has "policy/v1/PodDisruptionBudget" to choose the API; for existing releases, use the helm-mapkubeapis plugin to rewrite the stored manifest (see the plugin docs for its Helm 4 support), or before the cluster upgrade, upgrade the chart first. Limitation: Rewriting release storage is risky; back up the release Secret first.
Case 3: HPA and replicas fight each other
Problem: The chart renders replicas: 2 and an HPA, and every helm upgrade resets the replica count to 2, and during peak hours many requests time out. Approach: In the library, {{- if not .Values.autoscaling.enabled }}replicas: …{{- end }}; when switching from "has replicas" to "no replicas", SSA releases Helm's ownership of that field, and the HPA takes over. Limitation: During the switching upgrade, if the old manifest has replicas and the new one does not, the exact behavior depends on how it is applied; switch during low-traffic periods and observe closely.
Common errors and fixes
Error: UPGRADE FAILED: cannot patch "shop-api" with kind Deployment: Deployment.apps "shop-api" is invalid: spec.selector: Invalid value: …: field is immutable
Cause: Selector labels changed (library upgrade, or release rename changed the instance label).
kubectl -n shop get deploy shop-api -o jsonpath='{.spec.selector}'; echo
helm template shop-api charts/shop-api | yq 'select(.kind=="Deployment") | .spec.selector'
Fix: Restore the original selector; if a change is unavoidable: run new names alongside old → shift traffic → delete the old ones, or kubectl delete deploy shop-api --cascade=orphan then upgrade (briefly keeps Pods running via the old ReplicaSet; proceed with caution).
Error: UPGRADE FAILED: … StatefulSet.apps "shop-db" is invalid: spec: Forbidden: updates to statefulset spec for fields other than 'replicas', 'ordinals', 'template', 'updateStrategy', 'persistentVolumeClaimRetentionPolicy' and 'minReadySeconds' are forbidden
Cause: A field that cannot be changed was modified, such as volumeClaimTemplates, serviceName, or podManagementPolicy.
kubectl -n shop delete sts shop-db --cascade=orphan helm upgrade shop-db charts/shop-db -n shop --wait
Fix: Delete the StatefulSet with orphan mode (Pods and PVCs are kept), then have Helm recreate it with the new spec and adopt the Pods; PVC capacity changes must go through the storage expansion process. The list of fields allowed to change in the error text depends on your K8s version.
Error: UPGRADE FAILED: unable to build kubernetes objects from current release manifest: resource mapping not found for name: "shop-api" … kind "PodDisruptionBudget" in version "policy/v1beta1"
Cause: The manifest of the previous revision references an API version that has been removed from the cluster.
Fix: Use a mapkubeapis-style tool to rewrite the API versions in release storage (back up the release Secret first), then upgrade with the corrected chart.
After upgrade, PVC deleted / database became empty
Cause: A standalone PVC template was turned off or renamed, and Helm deleted the PVC from the difference during Update.
helm get manifest shop-db -n shop --revision N-1 | yq 'select(.kind=="PersistentVolumeClaim") | .metadata.name' kubectl get pv | grep Released
Fix: If the PV reclaim policy is Retain, you can recover from the Released PV (clear claimRef, then rebind); prevention: add keep to PVCs and use Retain in the StorageClass.
1. List the resources deleted between shop-api's previous revision and its current revision.
N=$(helm history shop-api -n shop -o json | jq '.[-1].revision')
diff <(helm get manifest shop-api -n shop --revision $((N-1)) | yq -N 'select(.kind) | .kind+"/"+.metadata.name' | sort) \
<(helm get manifest shop-api -n shop --revision $N | yq -N 'select(.kind) | .kind+"/"+.metadata.name' | sort)2. In the chart, render the HPA only when the cluster supports autoscaling/v2.
{{- if and .Values.autoscaling.enabled (.Capabilities.APIVersions.Has "autoscaling/v2/HorizontalPodAutoscaler") }}
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
...
{{- end }}You need to migrate shop-db from the chart's built-in StatefulSet to managed PostgreSQL (Azure Database for PostgreSQL), with zero data loss and zero downtime. How do you release this in steps at the chart level?
① Add keep to shop-db's StatefulSet/PVC/Service (or confirm the PVC is not in the release), and release a minor chart version; ② create the managed database and set up data replication (logical replication/DMS), and add the new connection string to the ExternalSecret; ③ release shop-api and switch via values db.host to the managed database (rolling update; the read/write cutover window is designed per the application); ④ after an observation period, release a major version of the shop-db chart that removes the StatefulSet (keep resources are retained as orphans to allow rollback), and finally delete the old PVC manually. Each step can be rolled back on its own; the deletion is always the last step.
Verified instructional videos
No verified dedicated video on "Helm zero-downtime upgrades and compatibility design" was found; a storyboard is provided instead.
Official documentation
- Tell Helm Not To Uninstall a Resource (resource-policy)
- Built-in Objects (Capabilities)
- Deprecated Kubernetes APIs
- Kubernetes Deprecated API Migration Guide
- Deployment Rolling Update
Video storyboard (about 90 seconds)
This courseware cannot directly generate a video/MP3, so a storyboard and narration script are provided instead.
Visual: the resource card shows a three-part ID number: "kind + namespace + name".
Narration: Helm identifies resources by kind, namespace, and name. If the name changes, to Helm it is a different resource.
Visual: the new Deployment appears (grey), the old Deployment is deleted immediately, and the availability curve below drops to zero.
Narration: during an upgrade, Helm first creates the new resources, immediately deletes the old ones, and only then starts waiting. Renaming means an outage.
Visual: the selector field has a lock; trying to change it pops up "field is immutable".
Narration: selectors cannot be changed. Once selector labels in the library chart are published, never touch them.
Visual: the PVC carries a keep label, and the deletion arrow goes around it.
Narration: add resource-policy keep to data volumes, secrets, and CRDs. Before release, use template comparison and server-side dry runs to catch problems early.
Module 8 · Comprehensive architecture review
- Review a chart architecture across 7 dimensions (granularity, values, secrets, hooks, post-renderer, CRD/Operator, upgrade compatibility) and produce actionable fixes.
- Turn the "automatically checkable items" in the review checklist into scripts and put them in CI.
- Use the interactive troubleshooting tree to quickly locate: a stuck hook, a CRD that was not updated, secrets leaking into the release, a post-renderer failure, or an upgrade that deleted resources.
What: architecture review checklist (shop-platform edition)
| Dimension | Check item | Corresponding failure mode | Automatable? |
|---|---|---|---|
| Granularity (M1) | A release contains only components with a single owner; third-party components are not bundled into the umbrella | Unrelated changes cause a full rollback | Manual |
| Shared templates live in the library, with versioning and a CHANGELOG | Drift across multiple charts | ✓ helm dependency list | |
| Orchestration layer expresses order (db → api → web; CRD → Operator → CR) | First deployment fails | ✓ Check needs/dependsOn | |
| Values (M2) | No environment-name branches in templates | New environments behave unpredictably | ✓ grep -rE 'eq .*"(prod|dev|staging)"' templates/ |
| Has values.schema.json; version numbers are quoted | Type errors, 1.10 → 1.1 | ✓ lint | |
| Use maps, not lists, for overridable configuration | Upper-layer overrides lose configuration | Partial | |
| Secrets (M3) | The release manifest contains no kind: Secret plaintext data (or it has been reviewed) | release Secret leaks | ✓ helm get manifest Scan |
; secret sources are ESO/CSI; --set contain no secrets | CI log leak | ✓ Pipeline scanning | |
| Hooks (M4) | Migration Job: idempotent,activeDeadlineSeconds < --timeout, small backoffLimit | pending-upgrade stuck | ✓ yq checks annotations and fields |
delete policy includes before-hook-creation; failure logs are visible | already exists / no logs | ✓ | |
| Migrations only make expand-type changes | Old code crashes after rollback | Manual (SQL review) | |
| post-renderer (M5) | Use only for third-party charts; distribute plugins with signatures; patch targets must be precise; CI preview uses the same parameters | Patch fails / unintentionally affects hooks | Partial |
| CRD (M6) | CRD in a standalone chart + keep, or follow the upstream approach with upgrade steps | CRD not updated / CR accidentally deleted | ✓ Check crds/ and annotations |
| Charts that use CRs have a Capabilities guard | no matches for kind | ✓ | |
| Upgrade (M7) | Resource names do not change with the release name; selectors are frozen | delete and recreate / immutable | ✓ Compare old and new identity sets |
| PDB, maxUnavailable 0, readiness, preStop; do not render replicas with HPA | Upgrade jitter | ✓ Check rendered output | |
Stateful resources use keep; kubeVersion constraints; values deprecation policy | data loss, API removal | Partial |
Why: why a "review" is needed, not just lint
helm lint and schemas can only guarantee that the chart renders; architectural issues (blast radius, migration strategy, secrets path, CRD ownership) are cross-chart, cross-team design decisions that only surface when viewed together. A review's output is not a score but a list of fixes and "which checks go into CI".
How: review process (30–60 minutes)
- Draw the release topology and owners (
helm list -A+ orchestration layer configuration); - Go through the checklist dimension by dimension, recording evidence (command output);
- For each "✗", write out the failure scenario and fix;
- Write automatable checks as scripts (see the "Commands" page);
- Re-review after two weeks.
When
Before a new service joins the platform, before a chart releases a major version, and before major Helm/Kubernetes upgrades (e.g. Helm 3 → 4, see Lesson 7).
shop-platform target architecture
Review cadence
Interactive review: score shop-platform and generate a fix list
Check which items the current architecture already satisfies items. The right side computes each dimension's score in real time and lists a "failure scenario + fix command" for each unmet item. Results are saved in this browser (protected by try/catch).
Automatable review scripts
| Check | Command |
|---|---|
| Environment branches in templates | grep -rnE 'eq [^}]*"(prod|production|dev|staging)"' charts/*/templates |
| Plaintext Secrets in the release | helm get manifest R | yq 'select(.kind=="Secret") | .metadata.name' |
| Hook timeout configuration | helm template … | yq 'select(.metadata.annotations["helm.sh/hook"]) | [.kind, .metadata.name, .spec.activeDeadlineSeconds] ' |
| crds/ directory | find charts -path '*/crds/*.yaml' |
| Resource identity changes | Module 7's ids() function |
| Server-side dry run | helm upgrade … --dry-run=server |
#!/usr/bin/env bash
# Usage: ENV=prod ./review.sh (run from the shop-platform root directory)
set -uo pipefail
ENV=${ENV:-dev}; fail=0
vals() { echo "-f envs/base/common.yaml -f envs/base/$1.yaml -f envs/$ENV/common.yaml -f envs/$ENV/$1.yaml"; }
echo "== 1. Environment branches in templates"
grep -rnE 'eq [^}]*"(prod|production|dev|staging)"' charts/*/templates && fail=1 || echo "ok"
echo "== 2. crds/ directory (should be empty; CRDs go through a standalone chart)"
find charts -path '*/crds/*.yaml' | grep . && fail=1 || echo "ok"
for c in shop-api shop-web shop-db; do
out=$(helm template $c charts/$c $(vals $c) 2>&1) || { echo "$c render failed"; fail=1; continue; }
echo "== 3. $c: Secrets rendered by the chart (should be 0)"
n=$(echo "$out" | yq -N 'select(.kind=="Secret") | .metadata.name' | wc -l); echo "$n"; [ "$n" -eq 0 ] || fail=1
echo "== 4. $c: hook Job must have activeDeadlineSeconds and a delete policy that includes before-hook-creation"
echo "$out" | yq -N 'select(.kind=="Job" and .metadata.annotations["helm.sh/hook"]) |
.metadata.name + " deadline=" + (.spec.activeDeadlineSeconds // "missing" | tostring) + " policy=" + (.metadata.annotations["helm.sh/hook-delete-policy"] // "default")'
echo "== 5. $c: Deployment must have maxUnavailable=0 and a readinessProbe"
echo "$out" | yq -N 'select(.kind=="Deployment") | .metadata.name + " maxUnavailable=" + (.spec.strategy.rollingUpdate.maxUnavailable|tostring) + " readiness=" + ((.spec.template.spec.containers[0].readinessProbe != null)|tostring)'
done
exit $fail
== 1. Environment branches in templates ok == 2. crds/ directory (should be empty; CRDs go through a standalone chart) ok == 3. shop-api: Secrets rendered by the chart (should be 0) 0 == 4. shop-api: hook Job must have activeDeadlineSeconds and a delete policy that includes before-hook-creation shop-api-db-migrate deadline=240 policy=before-hook-creation,hook-succeeded shop-api-schema-verify deadline=60 policy=before-hook-creation,hook-succeeded == 5. shop-api: Deployment must have maxUnavailable=0 and a readinessProbe shop-api maxUnavailable=0 readiness=true ...
How to verify: Only exit code 0 allows merging. Common mistakes: There are two projects named yq (the Go version mikefarah/yq and the Python version); this script uses Go version v4 syntax. Production use: As one job in the Lesson 5 chart CI.
Lab 8: run a review on shop-platform (about 6 minutes)
helm list -A -o table for r in shop-db shop-api shop-web; do echo "== $r"; helm history $r -n shop --max 3; done
review.sh save it to the repository root directory,chmod +x review.sh && ENV=prod ./review.sh; echo "exit=$?".for s in $(kubectl -n shop get secret -l owner=helm -o name); do
kubectl -n shop get $s -o jsonpath='{.data.release}' | base64 -d | base64 -d | gunzip \
| grep -o -i -E '"(password|token|secret)[^"]*":"[^"]{4,}' | sed "s|^|$s: |"
done | head
(no output = no suspected plaintext secrets in the release)
Case 1: three issues caught by the platform onboarding review
Problem: A new service applied to join the platform; its chart was adapted from a Helm 3-era template. The review found:① The database password is passed via --set injected and rendered as a Secret; ② the migration Job is a regular template (not a hook), and the second upgrade reports the Job spec is immutable; ③ the CRD is in crds/ while the service depends on its new fields. Approach: Switch to ExternalSecret; change the migration to a pre-upgrade hook with a deadline; move the CRD into the platform's CRD chart. Limitation: The fix requires a major version release and migration notes.
Case 2: the effect of putting the review checklist into CI
Problem: Manual reviews struggle to cover 80 charts. Approach: Write the 9 automatable items in the checklist as scripts (similar to review.sh) and run them on every chart's PR; manual review only looks at SQL migrations, granularity, and CRD ownership. Limitation: The scripts parse output with yq; for complex templates, use helm template with multiple values sets to cover the branches.
Case 3: a dedicated review before the Helm 3 → 4 upgrade
Problem: The platform plans to switch to Helm 4. Review items: All --post-renderer usages change to plugins; check whether the post-renderer fails because hooks enter the stream; --atomic/--force renamed flags; field conflicts caused by SSA-by-default and strict field validation; Helm 4 versions of plugins such as helm-secrets. For detailed migration, see Lesson 7, Module 7.
Interactive troubleshooting tree: five categories of chart architecture faults
Start from symptoms and make step-by-step choices; finally, diagnostic commands and fix suggestions are given.
1. Use one command to find all releases in the cluster in a pending-* or failed state.
helm list -A --pending --failed
2. List the delete policies of all hooks in shop-api's current revision.
helm get hooks shop-api -n shop | yq -N '.metadata.name + " " + .metadata.annotations["helm.sh/hook-delete-policy"]'
During the review, it was found that shop-api's umbrella includes an ESO subchart (for "one-click install"), and ESO's CRDs are in its templates. Point out the risks and give a target architecture.
Risks: ① ESO is a cluster-scoped Operator; once it is bundled into a business release, uninstalling shop deletes ESO and its CRDs (if not kept), cascade-deleting ExternalSecrets across the entire cluster; ② if another business umbrella also includes ESO, ownership conflicts arise; ③ ESO upgrades are tied to the business release cadence. Target: ESO as an independent release at the platform layer (maintained by the platform team, ordered before the business in the orchestration layer), the business chart contains only ExternalSecret, and it uses Capabilities to check that the API exists.
Verified instructional videos
Official documentation
Video storyboard (about 70 seconds)
This courseware cannot directly generate a video/MP3, so a storyboard and narration script are provided instead.
Visual: a radar chart of seven dimensions, lighting up one by one.
Narration: an architecture review looks at seven things: granularity, values, secrets, hooks, post-renderer, CRDs, and upgrade compatibility.
Visual: five red warning signs flip in turn: stuck hook, CRD not updated, secret leak, post-renderer failure, resource deleted.
Narration: behind every check item is a real failure mode.
Visual: half of the checklist items turn into green checkmarks in the CI pipeline.
Narration: automatable checks go into CI; manual review focuses only on design decisions.
Command cheat sheet
Granularity and library
helm dependency update charts/shop-api # writes Chart.lock helm dependency build charts/shop-api # CI: restore per the lock file helm dependency list charts/shop-api helm template shop-api charts/shop-api --show-only templates/deployment.yaml helmfile -e prod diff helmfile -e prod -l name=shop-web apply
values layering
helm template R C -f envs/base/common.yaml -f envs/base/R.yaml \
-f envs/prod/common.yaml -f envs/prod/R.yaml -f envs/region/canadacentral.yaml
helm get values R -n NS # user-supplied
helm get values R -n NS --all # after merging
helm show values C # chart default values
helm upgrade R C --reset-then-reuse-values # not recommended as a long-term dependency
--set-json 'x={"a":1}' --set-literal k='a,b.c'Secrets
helm get manifest R -n NS | yq 'select(.kind=="Secret")'
kubectl -n NS get secret sh.helm.release.v1.R.vN -o jsonpath='{.data.release}' \
| base64 -d | base64 -d | gunzip | jq '.config'
for p in secrets secrets-getter secrets-post-renderer; do
helm plugin install oci://ghcr.io/jkroepke/helm-secrets/$p:4.7.11; done
helm upgrade R C -f secrets://secrets/prod.enc.yaml
kubectl get externalsecret -A
kubectl -n NS annotate externalsecret X force-sync=$(date +%s) --overwriteHooks
helm get hooks R -n NS helm upgrade R C --timeout 10m # per-hook limit helm upgrade R C --rollback-on-failure # formerly --atomic helm upgrade R C --no-hooks # emergency skip helm test R -n NS --logs # annotations: helm.sh/hook / hook-weight / hook-delete-policy / hook-output-log-policy
post-renderer plugin
helm plugin install ./plugins/kustomize-pr helm plugin list helm plugin package plugins/kustomize-pr --key KEY -d dist/ helm plugin verify dist/kustomize-pr-0.1.0.tgz helm upgrade R C --post-renderer kustomize-pr --post-renderer-args overlays/prod helm env HELM_PLUGINS
CRD
helm show crds C --version X | kubectl apply --server-side -f -
helm install R C --skip-crds
helm template R C --include-crds
kubectl wait --for=condition=Established crd/X
kubectl get crd X -o jsonpath='{.status.storedVersions}'
helm upgrade --install R C --take-ownershipZero downtime and compatibility
helm diff upgrade R C -f … # helm-diff plugin helm upgrade R C -f … --dry-run=server helm template R C | yq -N 'select(.kind) | .kind+"/"+.metadata.name' | sort kubectl delete sts X --cascade=orphan helm template R C --api-versions autoscaling/v2/HorizontalPodAutoscaler --kube-version 1.37.0
Review
helm list -A --pending --failed helm history R -n NS --max 5 grep -rnE 'eq [^}]*"(prod|dev|staging)"' charts/*/templates find charts -path '*/crds/*.yaml' ENV=prod ./review.sh
Quick troubleshooting table
| Symptom / error | Most likely cause | Where to look |
|---|---|---|
library charts are not installable | Installed a library chart | M1 |
| prod env variables missing | List replaced entirely by the upper layer | M2 |
helm get values Password appears in | Secrets enter values / release | M3 |
pre-upgrade hooks failed … already exists | Delete policy missing before-hook-creation | M4 |
pre-upgrade hooks failed … timed out / pending-upgrade | Migration Job stuck, no deadline | M4, Lesson 7 |
produced empty output | post-renderer script did not write to stdout | M5 |
| New CR field disappears / unknown field | CRD in crds/ not upgraded | M6 |
no matches for kind … ensure CRDs are installed first | Operator/CRD ordering | M6 |
spec.selector … field is immutable | Selector label changed | M7 |
| Service/PVC gone after upgrade | Resource renamed or template turned off | M7 |
Recommended configuration snippets
metadata:
annotations:
helm.sh/hook: pre-install,pre-upgrade
helm.sh/hook-weight: "0"
helm.sh/hook-delete-policy: before-hook-creation,hook-succeeded
helm.sh/hook-output-log-policy: hook-failed
spec:
backoffLimit: 1
activeDeadlineSeconds: 240 # < helm --timeout
ttlSecondsAfterFinished: 3600
apiVersion: v2
name: shop-api
version: 1.0.0 # delete-and-recreate / breaking values change → major
kubeVersion: ">=1.33.0-0"
dependencies:
- { name: shop-lib, version: "~0.1.0", repository: "file://../shop-lib" }
Comprehensive lab + final quiz
lab 's namespace shop .cd ~/helm-lab/shop-platform helm version --short; kubectl config current-context helm list -n external-secrets; kubectl get clustersecretstore lab-fake ls charts envs plugins overlays
Missing ESO or ClusterSecretStore: go back to Module 3 lab steps 1–2. Missing directory: go back to Module 0.
selectorLabels contains only name/instance; all three charts file://../shop-lib depend on it.
for c in shop-api shop-web; do helm dependency build charts/$c >/dev/null && helm lint charts/$c | tail -1; done helm lint charts/shop-db | tail -1
1 chart(s) linted, 0 chart(s) failed 1 chart(s) linted, 0 chart(s) failed 1 chart(s) linted, 0 chart(s) failed
postRenderer/postRendererArgs, per the Helmfile docs; or use helm commands directly):
# Equivalent plain Helm commands (in needs order)
V() { echo "-f envs/base/common.yaml -f envs/base/$1.yaml -f envs/prod/common.yaml -f envs/prod/$1.yaml -f envs/region/canadacentral.yaml"; }
helm upgrade --install shop-db charts/shop-db -n shop $(V shop-db) --wait --timeout 5m
helm upgrade --install shop-api charts/shop-api -n shop $(V shop-api) --wait --timeout 5m --rollback-on-failure
helm upgrade --install shop-web charts/shop-web -n shop $(V shop-web) --wait \
--post-renderer kustomize-pr --post-renderer-args overlays/prod
helm list -n shop
NAME NAMESPACE REVISION STATUS CHART APP VERSION shop-api shop 7 deployed shop-api-0.3.0 6.17.0 shop-db shop 3 deployed shop-db-0.2.0 17 shop-web shop 4 deployed shop-web-0.1.0 1.29-alpine
kubectl -n shop get externalsecret shop-db-credentials for r in shop-db shop-api shop-web; do printf "%s: " $r; helm get manifest $r -n shop | yq -N 'select(.kind=="Secret") | .metadata.name' | wc -l; done helm get values shop-api -n shop -o yaml | grep -i -c password
NAME STORETYPE STORE REFRESH INTERVAL STATUS READY shop-db-credentials ClusterSecretStore lab-fake 1h SecretSynced True shop-db: 0 shop-api: 0 shop-web: 0 0
003_add_index.sql (CREATE INDEX IF NOT EXISTS idx_orders_sku ON orders(sku); and write version 3), and change migrations.requiredVersion to 3, and upgrade the chart to 0.4.0. First inject one failure to verify blocking, then upgrade normally:
cat > charts/shop-api/migrations/003_add_index.sql <<'EOF' CREATE INDEX IF NOT EXISTS idx_orders_sku ON orders(sku); INSERT INTO schema_version(version) VALUES (3) ON CONFLICT DO NOTHING; EOF sed -i 's/requiredVersion: 2/requiredVersion: 3/' charts/shop-api/values.yaml sed -i 's/^version: .*/version: 0.4.0/' charts/shop-api/Chart.yaml helm upgrade shop-api charts/shop-api -n shop $(V shop-api) --set migrations.injectFailure=true --rollback-on-failure --timeout 3m; echo "exit=$?" helm history shop-api -n shop --max 3
Expected: exit non-zero, the last two revisions are failed and Rollback to …; the Deployment is unchanged. Note: the injected failure happens after the SQL runs, so version 3 has already been written to the database — this is live evidence that "rollback does not undo migrations; migrations must be backward compatible."
helm diff upgrade shop-api charts/shop-api -n shop $(V shop-api) 2>/dev/null | grep -E '^(\+|-) .*kind:' || echo "no resources added or removed"
helm upgrade shop-api charts/shop-api -n shop $(V shop-api) --dry-run=server >/dev/null && echo "server dry-run OK"
helm upgrade shop-api charts/shop-api -n shop $(V shop-api) \
--set config.env.PODINFO_UI_MESSAGE="shop v0.4.0" --wait --timeout 5m --rollback-on-failure
kubectl -n shop logs probe | awk '{print $2}' | sort | uniq -c
kubectl -n shop exec shop-db-0 -- psql -U shop -d shop -tAc 'select max(version) from schema_version'
no resources added or removed server dry-run OK Release "shop-api" has been upgraded. Happy Helming! 2817 200 3
The count shows only 200 means it passes. If 000/503, check readinessProbe,maxUnavailable, preStop, and PDB.
ENV=prod ./review.sh, record the result. End of lab:
kubectl -n shop delete pod probe --ignore-not-found # Keep the environment for Lesson 7 (fault injection reuses shop-platform); for a full cleanup: # helm -n shop uninstall shop-web shop-api shop-db # kubectl -n shop delete pvc -l app.kubernetes.io/name=shop-db # kubectl -n shop delete cm,job -l app.kubernetes.io/component=hook # helm -n external-secrets uninstall external-secrets; kubectl delete clustersecretstore lab-fake # helm plugin uninstall kustomize-pr
Open-ended self-test (answer first yourself, then expand the reference answers)
1. When would you choose an umbrella chart? Give two reasons and one prerequisite.
Reasons: components must be released at the same version and rolled back together; a one-click install package delivered to customers. Prerequisite: the same owner, few components, and acceptance of a larger blast radius and release Secret size.
2. prod.yaml has env: [{name: X, value: "1"}] and all 8 env entries in base are gone. Why? How do you avoid this by design?
Helm replaces lists as a whole when merging values. By design, express overridable configuration as maps (config.env.X: "1"). In templates, convert them to lists; a list is only an escape hatch.
3. Why is it said that "SOPS only solves half of the secrets problem"?
SOPS keeps ciphertext in Git, but after the Helm client decrypts it, the values enter the release's config and the rendered manifest (Secret), stored in every revision of the release Secret. Runtime protection requires ESO/CSI or strict RBAC.
4. Describe the algorithm Helm 4.3 uses to run pre-upgrade hooks, and what happens when the migration Job fails.
Select the hooks for this event → sort by weight ascending, with ties sorted by name → for each: clean up the old one per the delete policy (default before-hook-creation) → create → wait (the Job until Complete, each hook with its own --timeout). On failure: output logs per the log policy, handle per the hook-failed delete policy, delete already-succeeded hooks per hook-succeeded, subsequent hooks and the main resources are not run, and the revision is marked failed; if --rollback-on-failure is set, roll back to the last successful revision, but the database is not rolled back.
5. How do you use Kustomize as a post-renderer in Helm 4? What are the two differences compared with Helm 3?
Write a type: postrenderer/v1,runtime: subprocess plugin whose script reads the manifest from stdin, calls kustomize, and writes to stdout; helm plugin install Then use --post-renderer plugin-name --post-renderer-args overlay. Differences: ① you can no longer pass an executable file path directly; ② by default, hooks also enter the post-renderer (combined).
6. If you change shop-api's resource name from shop-api to shop-api-v2 , what happens? If the business really needs the rename, how should it be done?
Helm treats it as a new resource: it creates the new one and immediately deletes the old one (before --wait); the Service name change disconnects clients, so the outage is unavoidable. Correct approach: release in two steps — first let old and new resources coexist (new name + the old Service continues pointing to available Pods, or a new Service is added); after clients are switched, delete the old resources in the next version; add keep to PVCs, etc.; bump the major version and write upgrade notes.
Final quiz (12 questions, covering all modules)
Sources and version notes
| Topic | Verified conclusion | Source (accessed 2026-11-15) |
|---|---|---|
| Helm versions and Helm 4 changes | Helm 4.3.2 (2026-11-13); --atomic→--rollback-on-failure,--force→--force-replace (old names marked deprecated); --wait shortened to hookOnly, written as watcher; install --server-side defaults to true; upgrade defaults to auto; --take-ownership,--force-conflicts | helm/helm releases · Helm 4.3.2 source code pkg/cmd/install.go,upgrade.go,flags.go |
| Hook execution algorithm | 9 event types; sorted by weight ascending, with ties sorted by name (sort.Stable); when no delete policy is written, the default is before-hook-creation; Jobs/Pods wait until complete; each hook individually --timeout; failures are handled via logs/delete policy; CRD hooks are never deleted; added helm.sh/hook-output-log-policy | source pkg/action/hooks.go,pkg/release/v1/hook.go,pkg/kube/wait.go · Chart Hooks |
| upgrade order and deletion semantics | pre-upgrade hooks → KubeClient.Update (after create/update, immediately delete the difference; skip keep) → wait → post-upgrade hooks; on failure --rollback-on-failure roll back to the most recent deployed/superseded; updates use Strict field validation | source pkg/action/upgrade.go,pkg/kube/client.go |
| post-renderer plugin | plugin metadata apiVersion: v1,type: postrenderer/v1,runtime: subprocess,runtimeConfig.platformCommand; stdin/stdout; empty output raises an error; --post-renderer-args appended arguments; SDK's PostRenderStrategy: combined (default, includes hooks) / separate / nohooks; not exposed by the CLI | source pkg/postrenderer/postrenderer.go,internal/plugin/metadata_v1.go,internal/plugin/runtime_subprocess.go,pkg/action/action.go · Post Rendering |
| Plugin installation and signing | helm plugin install Default --verify=true; local directories run in development mode and are not verified; when the source does not support verification, you need --verify=false; helm plugin package Default --sign | source pkg/cmd/plugin_install.go,plugin_package.go |
| CRD | crds/ creates CRDs that do not yet exist only on install (including the first upgrade --install) and waits for Established; if they already exist, they are skipped; not upgraded, not deleted; --skip-crds | source pkg/action/install.go · CRD Best Practices |
| helm-secrets | latest v4.7.11; under Helm 4 it is split into secrets,secrets-getter,secrets-post-renderer three plugins; Helm 4 does not support --version, use a tgz URL or oci://ghcr.io/jkroepke/helm-secrets/<plugin>:<ver>; signing public key github.com/jkroepke.gpg | releases · Installation wiki |
| SOPS | latest v3.13.3 (2026-07) | getsops/sops releases |
| External Secrets Operator | v2.15.0 / chart 2.15.0 (2026-11-10); API external-secrets.io/v1; fake provider example structure | ESO releases · Fake provider |
| Secrets Store CSI Driver | v1.6.2 (2026-11-05) | releases |
| Kustomize | kustomize/v5.8.3 (2026-10-08); this lesson uses kubectl's built-in kubectl kustomize | kustomize releases |
| Helmfile | v1.8.4 (2026-11-13); from v1.7.2 supports Helm 4's rollback-on-failure; v1.8.2 skips recreatePods under Helm 4; built-in tests use Helm versions 3.22.1 / 4.3.1 | helmfile releases |
| Kubernetes / kind | v1.37.1; kind v0.33.0 default kindest/node:v1.37.0; Storage Version Migrator v1.37 GA | kubernetes.io/releases · v1.37 release blog |
Video verification notes
The following videos were verified via the YouTube oEmbed endpoint (https://www.youtube.com/oembed?url=…&format=json, verified on 2026-11-16, the titles and channels: TechWorld with Nana "What is Helm in Kubernetes? Helm and Helm Charts explained | Kubernetes Tutorial 23" (-ykwb1d0DXU); CNCF "Building Helm Charts From the Ground Up: An Introduction to Kubernetes [I] - Amy Chen, Heptio" (vQX5nokoqrQ); DevOps Journey "How to Create Helm Charts - The Ultimate Guide" (jUYNS90nq8U), "Helm and Helm Charts Explained - Helm Tutorial for Beginners" (w51lDVuRWuk); KodeKloud "What is Helm? | Helm Concepts Explained | KodeKloud" (kJscDZfHXrQ); IBM Technology "What is Helm?" (fy8SHvNZGeE); DevOps & AI Toolkit "Manage Kubernetes Secrets With External Secrets Operator (ESO)" (SyRZe5YVCVk); Microsoft Developer "Introduction to External Secrets - Secrets Operator for Kubernetes" (2FOB49oXts8); Lachlan Evenson "OSS Unboxing: secrets-store-csi-driver - Integrates secrets stores with Kubernetes via a CSI volume" (3wks5Mioclg). oEmbed does not return duration or publish date, so the cards list no specific durations. No verified videos were found for Helm hooks, the Helm 4 post-renderer plugin, CRD lifecycle, zero-downtime compatibility, or helm-secrets/SOPS, so storyboards are provided instead. All videos are in English and were recorded before Helm 4; this lesson takes precedence on behavioral differences.
Voice narration notes
The "Voice" page uses the browser's Web Speech API (speechSynthesis, en-US) to read the narration script aloud in real time; English terms are pronounced with en-US. The result depends on the voices installed in the operating system. The environment that generated this courseware cannot call a TTS service, so no MP3 is embedded; for offline audio, the narration script can be handed to a TTS service.
Known limitations
- The lab commands in this lesson were not actually executed in the generation environment; the revision numbers, times, hashes, counts, and error text wording in the "Expected output" sections are example values; your Helm 4.3 and cluster's actual output takes precedence.
- ESO's fake provider is for demonstration only and provides no security whatsoever; for production, use Azure Key Vault (Lesson 3) or AWS Secrets Manager (Lesson 4).
- For the signature verification flow of helm-secrets under Helm 4 (keyring import), see its Installation docs; this lesson only gives the OCI installation method and the note that "the lab environment can
--verify=false". For helm-secrets, thesecrets-post-rendererplugin's specific purpose is not covered in this lesson. - PostRenderStrategy (combined/separate/nohooks) comes from the Helm 4.3.2 source code; as of this version the CLI does not provide a switch parameter; future versions may add one, so check the release notes.
- Helmfile's
postRendererfield, FluxpostRenderers, and Argo CD's mapping of Helm hooks are overviews; check each project's docs for details. Support for Helm 4 in helm-mapkubeapis has not been verified. - "ESO 0.17 onward provides
external-secrets.io/v1" is based on a recollection of the project's release history; follow the ESO docs; this lesson's lab pins v2.15.0. - kubectl field validation (strict/warn) and API server error text vary slightly between versions. The curlimages/curl tag is an example; replace it with a pinned version available in your environment.
- The times and counts in the animations are illustrative values, used to explain the mechanism.