Helm Hour 2: Writing a Production-Grade Chart
helm create myapp refactor it into a production-grade chart that passes review: templates, helpers, values design, schema validation, subcharts, lint and test- Read and hand-write Chart.yaml (
apiVersion: v2,type,dependencies,kubeVersion,annotations), and understandtemplates/,charts/,crds/,.helmignore,NOTES.txtthe role of each in the render pipeline. - Use Go template actions, pipelines and common Sprig/Helm functions fluently:
toYaml | nindent,default,required,tpl,lookup, and use{{-/-}}to precisely control whitespace. - Understand scope:
.and$differences,with/rangehow to change.,includeandtemplatedifferences, and write a helper that truncates names to 63 characters and selector labels that “never change”. - Design a good values.yaml (camelCase, optional resource toggles, image tag defaulting to
.Chart.AppVersion), and use values.schema.json to catch bad input during lint/install/template. - Manage dependencies:
helm dependency update/build,Chart.lock,condition/tags,global, subchart values passing, and use library chart to reuse templates. - Use
helm lint --strict,helm testandhelm template | kubeconformto build chart quality gates and quickly pinpoint problems fromnil pointer evaluating,error converting YAML to JSON,field is immutableand similar errors.
One-hour schedule
| # | Time | Module | Core content | Animation / Interactive | Lab (kind cluster lab) |
|---|---|---|---|---|---|
| 0 | Before class | Warm-up | Check Helm 4.3, the kind cluster and the myapp chart from Lesson 1; if needed, use helm create rebuild | “production-grade chart” 10-item self-assessment | helm lint Baseline |
| 1 | 00–07 | Chart structure and Chart.yaml | Directory conventions, apiVersion v2, application/library, dependencies, kubeVersion, annotations, .helmignore, NOTES.txt, crds/ | Chart loader: click a file to see how Helm handles it | Rewrite Chart.yaml + .helmignore + NOTES.txt |
| 2 | 07–15 | Template syntax: Go template and Sprig | Actions, pipelines, common function list,toYaml | nindent,required,default,tpl,lookup, whitespace control | Step-by-step pipeline evaluation + whitespace control visualization | ConfigMap template and helm template debugging |
| 3 | 15–22 | Named templates, _helpers.tpl and scope | define/include/template,. and $, with/range, labels and selector helpers, 63-character truncation | Core animation: template rendering and values scope | Refactor _helpers.tpl |
| 4 | 22–30 | Conditionals, loops and values design | if/else, range over lists and dicts, camelCase, optional resource toggles, probes/resources/HPA/PDB/securityContext, Ingress/HTTPRoute | values toggle → rendered manifest | Production deployment/pdb/hpa templates |
| 5 | 30–36 | values.schema.json validation | JSON Schema drafts (Helm 4 supports up to 2020-12), type/required/enum/additionalProperties, when validation runs | Schema validation simulator | Write a schema for myapp and deliberately introduce errors |
| 6 | 36–44 | Dependencies, subcharts and library charts | dependency update/build, Chart.lock, condition/tags, alias, global, subchart values, import-values, library chart | Dependency resolution and values flow | myapp + CloudPirates redis subchart (OCI) + common-lib |
| 7 | 44–51 | helm lint and helm test | lint rules and --strict, --with-subcharts, test hook Pod, writing tests, kubeconform | Quality gate pipeline + test Pod lifecycle | Write and run a redis connectivity test |
| 8 | 51–60 | Chart readiness review and common mistakes | Review checklist, nil pointer, indentation, YAML→JSON, immutable selectors, subchart values not taking effect | Review scorecard + interactive troubleshooting tree | Fault injection and fixes |
| — | After class | Cheat sheet · Capstone lab | Complete a production-grade myapp chart and pass lint --strict, helm test, kubeconform | Final quiz (12 questions) | Capstone lab |
Knowledge Coverage Matrix
| Target skills | M1 | M2 | M3 | M4 | M5 | M6 | M7 | M8 | Key commands | Lab |
|---|---|---|---|---|---|---|---|---|---|---|
| Write and explain Chart.yaml metadata | ✓ | · | · | · | · | ✓ | ✓ | ✓ | helm show chart | M1 lab |
| Go template and Sprig functions | · | ✓ | ✓ | ✓ | · | · | · | ✓ | helm template --debug | ConfigMap template |
| Scope and named templates | · | · | ✓ | ✓ | · | ✓ | · | ✓ | helm template -s | _helpers.tpl refactor |
| Values design and optional resources | · | · | · | ✓ | ✓ | ✓ | · | ✓ | helm show values,--set | HPA/PDB/Ingress toggles |
| schema validation | · | · | · | · | ✓ | ✓ | ✓ | ✓ | helm lint,install | deliberate errors |
| Dependencies and subcharts | ✓ | · | · | · | · | ✓ | ✓ | ✓ | helm dependency update/build/list | redis subchart |
| library chart reuse | ✓ | · | ✓ | · | · | ✓ | · | · | include "common-lib.x" | common-lib |
| lint / test / kubeconform gates | · | · | · | · | ✓ | · | ✓ | ✓ | helm lint --strict,helm test --logs | Capstone lab |
| Template error troubleshooting | · | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | --debug,get manifest | M8 fault injection |
Topics not covered in this lesson (and where to learn them)
| Topic | Why not in this lesson | Where to learn |
|---|---|---|
| What Helm is, install/upgrade/rollback, values precedence, OCI distribution basics | Covered in Lesson 1 (the Kubernetes course's Hour 6 has a shorter Helm 4 introduction) | Lesson 1 · Kubernetes course |
| Chart design for ACR / Workload Identity / Key Vault, ingress on AKS | Belongs to cloud platform topics | Lesson 3 (Azure), Lesson 4 (AWS) |
| Hook execution order and weights (pre-install/post-upgrade, etc.), chart-testing (ct), chart-releaser, helm-docs | This lesson only uses the test hook; other hooks and the CI toolchain are covered in the automation course | Lessons 5 and 6 |
| GitOps (Argo CD / Flux HelmRelease), Helmfile, helm-secrets | Belongs to delivery and operations | Lesson 5 |
| Deep troubleshooting for stuck pending-upgrade, oversized release Secret, SSA conflicts, etc. | Requires writing charts first | Lesson 7 · Lesson 8 (50 problems) |
| Chart API v3 (experimental) | Still requires an environment variable in Helm 4.3 HELM_EXPERIMENTAL_CHART_V3 to enable it; production charts still use apiVersion: v2 | Helm HIPs |
How to use these course materials
Principles · Diagrams · Animation · Commands · Labs · Production cases · Troubleshooting · Quizzes · Voice · Video. Read “Principles” and “Animation” first, then do the “Lab”. All labs build on the same
~/helmlab/myapp directory, accumulating changes.A quiz score ≥ 70% or clicking “Mark this module complete” counts toward progress, saved in this browser (cleared on refresh if the browser blocks local storage).
The “Voice” page reads the narration aloud with the browser's built-in Web Speech API (en-US); without a Chinese voice pack, the script is still readable or can be passed to a TTS tool.
santhosh-tekuri/jsonschema/v6 validation, supports draft-04/06/07/2019-09/2020-12; helm template --validate is now deprecated; use --dry-run=server; --dry-run accepts none/client/server; Sprig's env/expandenv was intentionally removed. Helm 3.22 users: template syntax is identical; for schema draft support and dry-run flags, follow the 3.x docs.Module 0 · Warm-up (helm create)
- CompletedLesson 1: Helm 4 (
get-helm-4), kind clusterlab(1 control-plane + 2 workers), working directory~/helmlab; namespacemyapphas two releases:redis(CloudPirates redis 0.39.1, OCI, Secretrediskeyredis-password) andmyapp(Lesson 1 Module 8, created byhelm createmodified chart +values-lab.yaml). - The myapp image comes from Lesson 1 Module 0 (based on the Docker course): Flask + gunicorn, listening on 5000, health checks
/healthz, environment variablesREDIS_HOST,REDIS_PASSWORD;myapp:1.0andmyapp:1.1already usedkind load docker-imageto load into the nodes. - Tools: kubectl 1.37, kind v0.33.0, Helm v4.3.x; this lesson adds kubeconform v0.8.0 (installed in Module 7).
Step 1: Check tools and cluster
helm version --short kubectl config use-context kind-lab kubectl get nodes helm list -n myapp ls ~/helmlab/myapp
v4.3.2+g<commit> Switched to context "kind-lab". NAME STATUS ROLES AGE VERSION lab-control-plane Ready control-plane 3d v1.37.0 lab-worker Ready <none> 3d v1.37.0 lab-worker2 Ready <none> 3d v1.37.0 NAME NAMESPACE REVISION UPDATED STATUS CHART APP VERSION myapp myapp 4 2026-11-15 10:41:05 ... deployed myapp-0.1.0 1.0 redis myapp 1 2026-11-15 10:30:12 ... deployed redis-0.39.1 8.10.2 Chart.yaml charts templates values.yaml
REVISION and timestamps depend on your environment (Lesson 1's upgrade and rollback drills add revisions). The Lesson 1 capstone lab runs in shop-helm namespace, has been uninstalled, and is unrelated to this lesson.
Step 2 (only if missing): rebuild the cluster, images and Redis following Lesson 1
If the cluster has been deleted, followLesson 1 Module 0 steps 2–3 to rebuild the kind cluster lab (three nodes, node image with digest), then build and load myapp:1.0/myapp:1.1; then install Redis per Lesson 1 Module 8:
kind load docker-image myapp:1.0 myapp:1.1 --name lab # when the images are already built and only need reloading helm upgrade --install redis \ oci://registry-1.docker.io/cloudpirates/redis@sha256:423b2ec14ca56bac26bf8ef429ed01e480eedeee0759fad2a71ef397b76f9dc4 \ -n myapp --create-namespace --set persistence.size=1Gi --wait --timeout 5m
Step 3: Keep the Lesson 1 chart and refactor from a clean skeleton
The Lesson 1 chart used sed to insert a list-form env block, together with values-lab.yaml usage. The capstone also temporarily set the version to 1.0.0 for the OCI distribution demo. This lesson redesigns the values interface, so the old chart is renamed as a backup and re- helm create, and treat the refactored chart as a new 0.x version line (0.2.0 → 0.3.0 at course end; Lesson 3 continues from 0.3.0). Template names myapp.fullname/labels/selectorLabels/serviceAccountName stay the same as in Lesson 1, the selector is unchanged, so the same-named release can be upgraded directly myapp.
cd ~/helmlab mv myapp myapp-lesson1 # Lesson 1 chart backup (values-lab.yaml stays in place; no longer needed after this lesson) helm create myapp find myapp -type f | sort
myapp/.helmignore myapp/Chart.yaml myapp/templates/NOTES.txt myapp/templates/_helpers.tpl myapp/templates/deployment.yaml myapp/templates/hpa.yaml myapp/templates/httproute.yaml myapp/templates/ingress.yaml myapp/templates/service.yaml myapp/templates/serviceaccount.yaml myapp/templates/tests/test-connection.yaml myapp/values.yaml
There is also an empty directory myapp/charts/. Note: Helm 4's helm create already includes Gateway API httproute.yaml (default httpRoute.enabled: false), but does not generate values.schema.json, PDB and crds/—these are what this lesson adds.
Step 4: See what the skeleton renders by default
cd ~/helmlab helm lint myapp helm template myapp ./myapp -n myapp | grep -E '^(kind| name):'
==> Linting myapp [INFO] Chart.yaml: icon is recommended 1 chart(s) linted, 0 chart(s) failed kind: ServiceAccount name: myapp kind: Service name: myapp kind: Deployment name: myapp kind: Pod name: "myapp-test-connection"
myapp.fullname helper uses the release name directly when it contains the chart name. Module 3 explains this helper line by line.Warm-up: answer from memory (30 seconds)
What is the values precedence in Lesson 1 (lowest to highest)?
The chart's values.yaml → parent chart's values (for a subchart) → -f/--values files (later ones win when there are several) → --set/--set-string/--set-file/--set-json. The Module 3 animation starts from this step.
helm template and helm install --dry-run difference?
helm template fully offline by default (--dry-run=client),.Capabilities uses built-in default values,lookup returns empty; helm install --dry-run=server connects to the cluster and can use lookup and have the API Server validate.
“Production-grade chart” 10-item self-assessment
Check off your myapp chart currently meets items (saved in this browser). Check again after completing the capstone lab.
Module 1 · Chart structure and Chart.yaml
- Explain the role of each conventional file in the chart directory:
Chart.yaml,values.yaml,values.schema.json,templates/,templates/NOTES.txt,templates/_*.tpl,charts/,crds/,.helmignore,Chart.lock. - Correctly fill in
Chart.yaml:apiVersion: v2,version(SemVer 2) andappVersiondifferences,type,kubeVersionconstraints (including the pre-release suffix trap),annotations,dependencies. - Know
crds/directory's four rules, and.helmignorethe matching rules for (Gofilepath.Match, not supporting**).
What: a chart is a conventional directory (or its .tgz package)
myapp/ ├── .helmignore # files excluded when packaging and for .Files (glob) ├── Chart.yaml # required: chart metadata (name, version, dependencies, ...) ├── Chart.lock # generated by helm dependency update: pins exact dependency versions and digests ├── values.yaml # default configuration values ├── values.schema.json # optional: JSON Schema validation of merged .Values ├── charts/ # dependent subcharts (directories or .tgz) ├── crds/ # optional: CRDs, plain YAML, not run through template rendering ├── templates/ # templates: rendered and sent to Kubernetes │ ├── NOTES.txt # printed to the user after rendering, not sent to Kubernetes │ ├── _helpers.tpl # starts with _: only define blocks, no manifest output │ ├── deployment.yaml │ └── tests/ # test hooks used by helm test (conventional location) ├── README.md # optional: shown by helm show readme └── LICENSE # optional
Why: why so many conventions
Helm does not read any “config file telling it where the templates are.” It relies on directory conventions to do four things: Load (the loader reads Chart.yaml, values, templates and subcharts),render (the Go template engine treats templates/ all files under it as one template set),install (installs crds/ first, then sends the rendered output in resource-kind order),package and distribute (helm package by .helmignore filtering, then packaging as myapp-0.2.0.tgz, and pushing to an OCI or HTTP repository). With consistent conventions, anyone handed any chart knows where to start reading.
How: go through the Chart.yaml fields one by one
| Field | Required? | Notes and cautions |
|---|---|---|
apiVersion | Required | v2: requires Helm 3 or later (Helm 4 uses it too); v1 is the Helm 2 format (dependencies go in requirements.yaml). Helm 4.3 internally already has the Chart API v3 code, but requires setting HELM_EXPERIMENTAL_CHART_V3 to enable it; do not use in production. |
name | Required | Chart name. Best practice: lowercase letters, digits and hyphens, no uppercase or underscores; the directory name must match. |
version | Required | The chart's own version; must be SemVer 2 (0.2.0). Increment when templates or default values change; it is also the .tgz file name and OCI tag. |
appVersion | Optional | Version of the deployed application; informational field, SemVer not required,quoting recommended ("1.1", otherwise 1.10 will be parsed as a float by YAML 1.1). Often used as the default image tag (Module 4). |
type | Optional | application (default, installable) or library (only provides helpers, not installable, Module 6). |
kubeVersion | Optional | SemVer constraint, for example ">=1.33.0-0". Compared against the cluster version on install/upgrade; the install fails if unsatisfied. Supports >= < ~ ^ || and hyphen ranges. |
dependencies | Optional | Dependency list: name,version (usable range),repository (https://,oci://,file:// or @repo-alias),condition,tags,alias,import-values (Module 6). |
description / keywords / home / sources / icon | Optional | For display; helm lint Gives a hint when icon is missing [INFO] icon is recommended (INFO level,--strict and does not fail because of it). |
maintainers | Optional | name (required by lint),email,url. |
deprecated | Optional | true when set to true, repository search and Artifact Hub show it as deprecated. |
annotations | Optional | Arbitrary key-value pairs (values must be strings), for example the artifacthub.io/changes,artifacthub.io/images,artifacthub.io/license. Helm itself does not interpret them. |
kubeVersion pre-release suffix trap
Hosted cluster versions often carry a suffix: EKS reports v1.37.0-eks-abc123, and GKE uses v1.37.1-gke.1000. SemVer specifies that versions with a pre-release suffix do not satisfy a range without -0 range, so kubeVersion: ">=1.33.0" will reject the install directly on EKS. The official docs recommend writing ">=1.33.0-0".
Four rules for the crds/ directory (from the official Charts documentation)
- Files are not rendered as templates, must be plain YAML;
- only on install installs,upgrade and rollback do not handle it; if a CRD with the same name already exists in the cluster, it is skipped (versions are not compared);
- Helm never deletes CRDs (uninstall does not either), to avoid cascading deletion of all custom resources;
- Helm installs CRDs first, waits until the API Server serves that type, then renders and installs the remaining templates. You can use
--skip-crdsto skip;helm templateDoes not output CRDs by default; add--include-crdsto output them.
Because CRD upgrades are not managed by Helm, many operator charts put CRDs in a separate chart (for example xxx-crds) or put them in templates/ and handle upgrade risk themselves. myapp does not need CRDs; this lesson only introduces them.
.helmignore
One pattern per line, using Go's filepath.Match (not .gitignore): supports *,?,[...] and directory names (ending with / matches directories); does not support **; trailing spaces at line ends are always ignored. Excluded files do not enter .tgz, and in templates they are read via .Files cannot read them either.
When: which file to change, and when
- Change templates or default values → increment
version; new application release → updateappVersion(usually also increment chart version). - Minimum cluster version requirement (e.g., using a field only available from v1.33) → set
kubeVersion. - To keep CI or dev files out of the package (
ci/,*.md.gotmpl,.vscode/) → set.helmignore.
Comparison with similar tools
| Helm chart | Kustomize | Plain YAML + kubectl apply | |
|---|---|---|---|
| Parameterized | Go template + values | overlay/patch, no templates | None |
| Versioning and distribution | chart version, push .tgz to OCI/HTTP repository | Git reference | Git |
| Dependencies | dependencies + Chart.lock | resources reference remote base | None |
| Release history and rollback | release Secret,helm rollback | None (relies on GitOps) | None |
| CRD handling | crds/ installed only on first install | Treated as ordinary resources | Treated as ordinary resources |
version and appVersion are the same thing”—the former is the chart package version, the latter the application version; they can change independently. ② “Putting CRDs in crds/ means that later helm upgrade will upgrade CRDs for me”—it won't. ③ “.helmignore and .gitignore syntax are the same”—not supported **, based on filepath.Match. ④ “NOTES.txt is plain text”—it is also a template and can use .Values,include.Architecture diagram: how Helm processes each part of the chart directory
Version field relationships
Interactive: Helm's chart loader
Click a file on the left to see how Helm treats it at each stage: “Load → Render → Install → Package”. The .helmignore tester uses the same semantics as Go filepath.Match in a simplified implementation: enter patterns to see which files will be excluded from the package.
.helmignore tester
Separate multiple patterns with spaces or new lines.
Core commands and flags
| Command | Purpose | Key flags / notes |
|---|---|---|
helm create NAME | Generate a skeleton chart | --starter/-p Use a custom starter (placed in $HELM_DATA_HOME/starters) |
helm show chart|values|readme|crds|all | Show the contents of a local directory, .tgz or remote chart | --version Specify the remote chart version |
helm package DIR | Package as .tgz, respecting .helmignore | --version/--app-version Override version; -u Update dependencies before packaging; -d Output directory |
helm lint DIR | Check Chart.yaml, templates and values | Module 7 details |
helm template REL DIR --include-crds | Output crds/ together with rendering | CRDs not output by default |
helm install ... --skip-crds | Skip crds/ on install | Use when CRDs are managed separately by the platform team |
helm get notes REL | View the rendered NOTES.txt again | Also printed on install/upgrade |
cd ~/helmlab helm show chart ./myapp helm package myapp -d /tmp && tar -tzf /tmp/myapp-0.1.0.tgz
apiVersion: v2 appVersion: 1.16.0 description: A Helm chart for Kubernetes name: myapp type: application version: 0.1.0 Successfully packaged chart and saved it to: /tmp/myapp-0.1.0.tgz myapp/Chart.yaml myapp/values.yaml myapp/templates/NOTES.txt myapp/templates/_helpers.tpl myapp/templates/deployment.yaml ... myapp/.helmignore
How to verify: Every path in the tar listing starts with the chart name; files excluded by .helmignore do not appear. Common mistakes: Putting .git/, or large test data, in the package; the .tgz becomes too large (the release Secret also stores chart contents; see the 1 MiB limit in Lesson 7). Production use: In CI, use helm package --version $CHART_VER --app-version $GIT_TAG to stamp versions consistently.
Lab 1: Rewrite Chart.yaml, .helmignore and NOTES.txt (about 5 minutes)
apiVersion: v2
name: myapp
description: Flask + gunicorn counter app myapp (Docker course example), optionally with built-in Redis
type: application
version: 0.2.0
appVersion: "1.1"
kubeVersion: ">=1.33.0-0"
keywords:
- flask
- redis
- demo
home: https://example.com/myapp
sources:
- https://example.com/myapp/src
maintainers:
- name: platform-team
email: platform@example.com
icon: https://example.com/myapp/icon.png
annotations:
artifacthub.io/license: Apache-2.0
artifacthub.io/changes: |
- kind: changed
description: Refactored into a production-grade chart (probes, resources, HPA, PDB, schema).git/,*.swp,.vscode/ , etc.):
cat >> ~/helmlab/myapp/.helmignore <<'EOF' # added in this lesson ci/ *.md.gotmpl Makefile EOF mkdir -p ~/helmlab/myapp/ci && echo "replicaCount: 1" > ~/helmlab/myapp/ci/kind-values.yaml
ci/ directory holds the CI values (chart-testing reads them by convention from ci/*-values.yaml, Lesson 6); it does not need to go into the release package.
myapp {{ .Chart.AppVersion }} deployed to namespace {{ .Release.Namespace }} (revision {{ .Release.Revision }}).
{{- if .Values.ingress.enabled }}
Access URL:
{{- range .Values.ingress.hosts }}
http{{ if $.Values.ingress.tls }}s{{ end }}://{{ .host }}/
{{- end }}
{{- else if .Values.httpRoute.enabled }}
Created HTTPRoute {{ include "myapp.fullname" . }}; access it through the Gateway address.
{{- else }}
Local access:
kubectl -n {{ .Release.Namespace }} port-forward svc/{{ include "myapp.fullname" . }} 8080:{{ .Values.service.port }}
curl http://127.0.0.1:8080/healthz
{{- end }}
Run tests: helm test {{ .Release.Name }} -n {{ .Release.Namespace }} --logscd ~/helmlab helm lint myapp helm package myapp -d /tmp && tar -tzf /tmp/myapp-0.2.0.tgz | grep -c ci/ ; echo "ci file count (should be 0)" # Only preview the NOTES rendering: client-side dry-run, no cluster connection, no release created helm install notes-demo ./myapp -n myapp --dry-run=client --set service.port=5000 | sed -n '/^NOTES:/,$p'
==> Linting myapp 1 chart(s) linted, 0 chart(s) failed Successfully packaged chart and saved it to: /tmp/myapp-0.2.0.tgz 0 ci file count (should be 0) NOTES: myapp 1.1 deployed to namespace myapp (revision 1). Local access: kubectl -n myapp port-forward svc/notes-demo-myapp 8080:5000 curl http://127.0.0.1:8080/healthz Run tests: helm test notes-demo -n myapp --logs
After setting icon,[INFO] icon is recommended disappears. The release name notes-demo does not contain the chart name, so the fullname becomes notes-demo-myapp (Module 3 explains). The skeleton's probes, image and ports are not changed yet; do not use it to upgrade the running myapp for now, since Module 4 converts everything to production config.
helm template myapp ./myapp --kube-version 1.31.0 >/dev/null
Error: chart requires kubeVersion: >=1.33.0-0 which is incompatible with Kubernetes v1.31.0
Case 1: “chart requires kubeVersion” on EKS even though the version is sufficient
Problem: The chart declares kubeVersion: ">=1.30.0", and the install fails on EKS 1.33. Approach: EKS reports the version as v1.33.x-eks-…, with a pre-release suffix, which does not satisfy a range without -0 range. Configuration: Change it to ">=1.30.0-0", and run helm template --kube-version 1.33.0-eks-1234 in CI for regression. Limitation:kubeVersion Only checks before install; it cannot replace .Capabilities.APIVersions.Has on-demand rendering.
Case 2: CRD upgrade “has no effect”
Problem: A newer version of an operator chart added a field to the CRD, but after running helm upgrade , the new field is pruned by the API Server. Approach: This is the designed behavior of crds/: CRDs are created only on the first install. Configuration: Before upgrading, first kubectl apply --server-side -f crds/ (or use the project's standalone CRD chart), then helm upgrade. Limitation: Deleting a CRD deletes all its CRs; always go through change review.
Case 3: chart package is 40 MB, release install fails
Problem: A developer put a test dump file in the chart directory, and helm install reported that the release Secret was too large. Approach:tar -tzvf Find the large file and add it to .helmignore; add a CI step that checks “chart package size < 1 MB”. Limitation: The release Secret stores the compressed chart and manifests, subject to the Kubernetes object 1 MiB limit (detailed in Lesson 7).
Common errors and fixes
Error: validation: chart.metadata.version "latest" is invalid
Cause:version must be parseable as SemVer. latest,1.0.0- etc. error out directly; 0.2 Such loose formats can be parsed, but helm lint will give a “non-strict SemVer 2” warning, and --strict fails under it.
helm lint myapp --strict
Fix: Use the three-part form MAJOR.MINOR.PATCH, for example 0.2.0.
Error: chart requires kubeVersion: >=1.33.0 which is incompatible with Kubernetes v1.37.0-eks-…
Cause: The pre-release suffix issue (see the Principles page).
Fix: Write the constraint as ">=1.33.0-0".
Error: apiVersion 'v3' is not valid. The value must be either "v1" or "v2"
Cause: Chart API v3 is still an experimental feature in Helm 4.3.
Fix: Use apiVersion: v2. Only set HELM_EXPERIMENTAL_CHART_V3 when explicitly evaluating the experimental feature.
CRD updated, but the cluster still has the old schema (new fields pruned after upgrade)
kubectl get crd widgets.example.com -o jsonpath='{.metadata.annotations}'
helm show crds ./mychart | kubectl diff --server-side -f -
Fix: Apply it manually or with a pipeline using kubectl apply --server-side -f crds/; consider splitting the CRDs into their own chart.
templates/foo.json: file extension '.json' not valid. Valid extensions are .yaml, .yml, .tpl, or .txt
Cause: lint only accepts templates/ with these extensions.
Fix: Rename the JSON template to .yaml (YAML is a superset of JSON), or put static JSON in another chart directory and use .Files.Get to read it.
1. Without extracting, view the Chart.yaml and default values of a chart in an OCI repository.
helm show chart oci://registry.example.com/charts/myapp --version 0.2.0 helm show values oci://registry.example.com/charts/myapp --version 0.2.0
2. When packaging the chart, set the chart version to 0.2.1 and appVersion to 1.1.1, and output to dist/.
helm package myapp --version 0.2.1 --app-version 1.1.1 -d dist/
The team wants to put cert-manager's CRDs into their business chart's crds/ directory so that “one command installs everything.” How would you review this?
Not recommended. crds/ only takes effect on the first install; later cert-manager upgrades will not update the CRDs, causing version drift; when several charts ship the same CRD, it is unclear which one “owns” it; uninstall does not delete CRDs. Instead, install cert-manager as its own release (the official chart has crds.enabled options; check its documentation for details), and have the business chart use .Capabilities.APIVersions.Has "cert-manager.io/v1" to decide whether to render a Certificate.
Verified teaching videos
Official documentation
- Charts (Chart.yaml, crds, dependencies, library)
- The .helmignore file
- Best Practices: General Conventions
- Best Practices: Custom Resource Definitions
Video storyboard script (about 90 seconds)
This courseware cannot directly generate video or MP3; the storyboard and narration below can be handed to a video tool.
Visual: the myapp folder expands; each file is highlighted in turn and labeled: metadata, default values, templates, subcharts, CRDs.
Narration: a chart is a conventional directory; Helm knows what each file does without any extra configuration.
Visual: in Chart.yaml, version and appVersion connect to “package name myapp-0.2.0.tgz” and “image tag 1.1” respectively.
Narration: version is the chart's own version, appVersion is the application's version; the two increase independently.
Visual: the crds directory is pulled out separately and enters the cluster first on install; the upgrade arrow is blocked by a red cross.
Narration: the crds directory is not rendered; it is created only on the first install, and upgrade and uninstall never touch it.
Visual: a helm package funnel, with .helmignore rules keeping the ci directory and swp files out.
Narration: when packaging, .helmignore excludes files using Go's filepath.Match rules; note that it does not support double asterisks.
Module 2 · Template syntax: Go template and Sprig
- Read Go template actions (
{{ }}), comments, variables, pipelines, and the built-in objects Helm injects.Values.Release.Chart.Capabilities.Template.Files. - Master the common function list, especially
toYaml | nindent,quote,default(and its trap forfalse/0),required,tpl,lookup(empty during offline rendering). - Use
{{-and-}}to precisely control whitespace and avoid blank lines and indentation errors.
What: template = text + actions
Helm uses the Go standard library text/template, plus Sprig function library (Helm 4.3.2 depends on Masterminds/sprig/v3 v3.3.0) and Helm's own functions (include,tpl,required,lookup,toYaml , etc.). In templates, {{ … }} text outside is output as-is; {{ … }} is called an action.
| Syntax | Meaning | Example |
|---|---|---|
{{ .Values.x }} | Output field value | replicas: {{ .Values.replicaCount }} |
{{/* comment */}} | Template comment, not output (YAML's # comments are copied to the manifest as is) | {{- /* compute image */ -}} |
{{ $v := … }} / {{ $v = … }} | Define / reassign variable | {{- $fullName := include "myapp.fullname" . }} |
a | f b | Pipeline: passes the result on the left as the last argument of the function on the right | .Values.tag | default "1.1" ≡ default "1.1" .Values.tag |
(f a) | Parentheses group, evaluated first | {{ default (include "x" .) .Values.name }} |
if / else if / else / end,with,range | Control structures (Modules 3, 4) | {{- if .Values.pdb.enabled }} |
{{- / -}} | Remove the action's left / right all whitespace (including newlines) | see whitespace control below |
Built-in objects injected by Helm (top-level .)
| Object | Common fields |
|---|---|
.Values | Merged values (defaults + parent chart + -f + --set) |
.Release | .Name,.Namespace,.Revision,.IsInstall,.IsUpgrade,.Service (fixed to Helm) |
.Chart | Chart.yaml contents: .Name,.Version,.AppVersion,.Annotations… (field names capitalized) |
.Capabilities | .KubeVersion.Version,.APIVersions.Has "policy/v1",.HelmVersion. Offline helm template uses built-in default values; you can use --kube-version,--api-versions to override |
.Template | .Name (e.g., myapp/templates/deployment.yaml),.BasePath |
.Files | .Get,.Glob,.Lines,.AsConfig,.AsSecrets (reads non-template files inside the chart, cannot read templates/ and files excluded by .helmignore) |
Why: why you must know toYaml | nindent
In values, the resources,securityContext, and tolerations are all nested structures; writing templates field by field is verbose and easy to get wrong. toYaml Serialize the whole object as YAML text,nindent N output a newline first, then indent each line by N spaces so it lands at the correct level. indent No leading newline; suitable when already at the start of a new line.
resources:
{{- toYaml .Values.resources | nindent 12 }}
# ↓ rendered result (12 spaces to align with the children of resources)
resources:
limits:
memory: 256Mi
requests:
cpu: 100m
memory: 128Mi
How: common function list (by purpose)
| Category | Function | Key points |
|---|---|---|
| Defaults and validation | default,required,fail,empty,coalesce,ternary | default Treat false,0,"", empty lists and dicts are also treated as “empty”; required "please set this value" .Values.x fails rendering when empty |
| Strings | quote,squote,printf,trunc,trimSuffix,replace,lower,upper,contains,hasPrefix,b64enc | Annotations and environment variable values always quote, to prevent true,1.10,0755 from being parsed as booleans or numbers |
| Serialization | toYaml,toJson,fromYaml,fromJson,toToml,mustToYaml | must* return an error rather than an empty string on version errors |
| Templates | include,tpl | tpl .Values.x . re-render a string as a template; the context must be passed |
| Lists / dicts | list,append,has,join,uniq,dict,get,hasKey,merge,mergeOverwrite,pick,omit,keys,deepCopy | merge the first argument is used and modified in place; copy it first when you need immutability deepCopy |
| Comparison / logic | eq,ne,lt,gt,and,or,not,semverCompare | since Go 1.18 and/or short-circuit evaluation; eq mismatched types error out (int vs float64) |
| Hashing / encoding | sha256sum,b64enc,b64dec | checksum/config: {{ include (print $.Template.BasePath "/configmap.yaml") . | sha256sum }} trigger rolling updates on config changes |
| Cluster lookups | lookup | see below |
| avoid using | randAlphaNum,now,uuidv4 | output differs on every render → a diff on every upgrade; Sprig's env/expandenv is intentionally removed in Helm |
lookup: only has a value when “actually connected to a cluster”
{{- $existing := lookup "v1" "Secret" .Release.Namespace "myapp-session" }}
{{- if $existing }}
session-key: {{ index $existing.data "session-key" }} {{/* reuse existing value; unchanged on upgrade */}}
{{- else }}
session-key: {{ randAlphaNum 32 | b64enc }}
{{- end }}
- Signature:
lookup apiVersion kind namespace name; returns a list when name is an empty string (.items); when not found, returns an empty dict. helm template(default--dry-run=client,helm install/upgrade --dry-run=client,helm lintin offline rendering does not connect to a cluster, so lookup always returns empty; to test lookup, use--dry-run=server.- GitOps tools such as Argo CD usually use
helm templateto render, so lookup is also empty; charts that rely on lookup generate new random values on every sync under GitOps.
Whitespace control
{{- Trim action left all consecutive whitespace (including the newline on the previous line),-}} removes the right all consecutive whitespace. Note that {{- and content must have a space between them: {{-3}} will be parsed as the number -3. The most common pattern: use {{- for control structures (it eats the newline and indentation before its own line); do not add -,toYaml use {{- … | nindent N }}.
When: which function to choose
- Put static defaults in
values.yaml,do not re-applydefaultin the templatedefaultonly use for values computed defaults (such as.Chart.AppVersion, helper results) — this is the official documentation's recommendation. - Values with no sensible default that the user must supply (external Redis address, domain) →
required, and pair it with a schema (Module 5). - If users may reference the release name and similar info in values → for that field use
tpl.
Comparison with similar tools
| Helm (Go template + Sprig) | Jinja2 (Ansible) | Kustomize | |
|---|---|---|---|
| Function call | prefix form default "x" .v, pipes the last argument | filter v | default('x') | no templates, relies on patches |
| whitespace control | {{- -}} | {%- -%} | — |
| understands YAML | does not understand, plain text concatenation (you handle indentation) | plain text | structured merge |
error converting YAML to JSON. ② “{{ default true .Values.enabled }} can enable a default-on feature”—a user writes false when default they expect it to be empty, but the result is still true, and the user cannot turn it off. ③ “lookup can get cluster data in dry-run”—only with --dry-run=server is it possible.Pipeline: data flows left to right and is passed as the last argument
Whitespace control: - which side it trims
{{- and nindent standard usageInteractive 1: step-by-step pipeline evaluator
Pick an expression, change the input values, then step through it. Each step shows the arguments the current function receives and its return value, and finally the rendered YAML lines. These rules match Helm's real implementation (default 's “empty” check,required 's error format,tpl needs context).
Interactive 2: whitespace control visualization
Toggle the four - switches and watch the rendered output (· means space,↵ means newline). Goal: the output has no blank lines and correct indentation.
Commands for debugging templates
| Command | Purpose | Key flags / notes |
|---|---|---|
helm template REL DIR | Render all templates offline | -f,--set,-n (affects .Release.Namespace) |
helm template … -s templates/x.yaml | Show only one template (--show-only) | can be given multiple times; for a subchart, write charts/redis/templates/x.yaml |
helm template … --debug | still outputs the content rendered so far when rendering fails, which makes problems easier to locate | you can see the original text when YAML parsing fails |
helm template … --kube-version 1.37.0 --api-versions policy/v1/PodDisruptionBudget | simulates the target cluster's .Capabilities | offline render .Capabilities.APIVersions.Has branch |
helm template … --dry-run=server | Render with a live cluster connection (lookup returns values, API Server validates) | replaces the deprecated --validate |
helm template … --is-upgrade | makes .Release.IsUpgrade true | tests a branch that only renders on upgrade |
helm template … --output-dir out/ | write each template as a separate file | to make it easier to diff -r compare two renders |
cd ~/helmlab helm template myapp ./myapp -s templates/service.yaml --set service.port=5000
---
# Source: myapp/templates/service.yaml
apiVersion: v1
kind: Service
metadata:
name: myapp
labels:
helm.sh/chart: myapp-0.2.0
app.kubernetes.io/name: myapp
app.kubernetes.io/instance: myapp
app.kubernetes.io/version: "1.1"
app.kubernetes.io/managed-by: Helm
spec:
type: ClusterIP
ports:
- port: 5000
targetPort: http
protocol: TCP
name: http
selector:
app.kubernetes.io/name: myapp
app.kubernetes.io/instance: myapp
How to verify: Each output section is preceded by a # Source: comment that shows which template file it came from; check it first when troubleshooting. Common mistakes: Using -s deployment.yaml omitting templates/ prefix causes could not find template. Production use: Compare the output in a PR helm template diff to review which manifests a template change actually affects.
Lab 2: Write a ConfigMap with functions and walk into three pitfalls yourself (about 6 minutes)
cat >> ~/helmlab/myapp/values.yaml <<'EOF'
# -- Application config (rendered into a ConfigMap and injected as environment variables)
config:
logLevel: info
featureFlags:
newCounter: true
# Allows template references: values are passed through tpl rendering
greeting: "Hello from {{ .Release.Name }} in {{ .Release.Namespace }}"
EOFapiVersion: v1
kind: ConfigMap
metadata:
name: {{ include "myapp.fullname" . }}
labels:
{{- include "myapp.labels" . | nindent 4 }}
data:
LOG_LEVEL: {{ .Values.config.logLevel | upper | quote }}
FEATURE_NEW_COUNTER: {{ .Values.config.featureFlags.newCounter | quote }}
GREETING: {{ tpl .Values.config.greeting . | quote }}
APP_VERSION: {{ .Values.image.tag | default .Chart.AppVersion | quote }}
{{- /* Only written on upgrade; demonstrates the .Release object */}}
{{- if .Release.IsUpgrade }}
LAST_UPGRADE_REVISION: {{ .Release.Revision | quote }}
{{- end }}
cd ~/helmlab helm template myapp ./myapp -n myapp -s templates/configmap.yaml | tail -6 helm template myapp ./myapp -n myapp -s templates/configmap.yaml --is-upgrade | tail -2
data: LOG_LEVEL: "INFO" FEATURE_NEW_COUNTER: "true" GREETING: "Hello from myapp in myapp" APP_VERSION: "1.1" APP_VERSION: "1.1" LAST_UPGRADE_REVISION: "1"
ConfigMap's data values must be strings, so booleans also need quote, or the API Server reports cannot unmarshal bool into Go struct field ConfigMap.data of type string.
FEATURE_NEW_COUNTER line's | quote and then validate in server mode:
helm template myapp ./myapp -n myapp -s templates/configmap.yaml --dry-run=server 2>&1 | tail -2
Error: ... ConfigMap in version "v1" cannot be handled as a ConfigMap: json: cannot unmarshal bool into Go struct field ConfigMap.data of type string
Offline-only rendering helm template won't catch this, which is exactly why Module 7 adds kubeconform and --dry-run=server to catch it. Revert to | quote.
cat > /tmp/t.yaml <<'EOF'
apiVersion: v1
kind: ConfigMap
metadata: {name: default-demo}
data:
wrong: {{ default true .Values.config.featureFlags.newCounter | quote }}
right: {{ ternary "true" "false" (.Values.config.featureFlags.newCounter | default false) | quote }}
EOF
cp /tmp/t.yaml ~/helmlab/myapp/templates/zz-demo.yaml
helm template myapp ./myapp -s templates/zz-demo.yaml --set config.featureFlags.newCounter=false | tail -2
rm ~/helmlab/myapp/templates/zz-demo.yaml
wrong: "true" right: "false"
A user explicitly sets false,default true but default treats it as empty and replaces it with true. Boolean defaults belong directly in values.yaml; if you really need to check in the template whether a value was set, use hasKey: {{ if hasKey .Values.x "enabled" }}.
cat > ~/helmlab/myapp/templates/zz-lookup.yaml <<'EOF'
{{- $ns := lookup "v1" "Namespace" "" .Release.Namespace }}
apiVersion: v1
kind: ConfigMap
metadata: {name: lookup-demo}
data:
nsUid: {{ dig "metadata" "uid" "EMPTY" $ns | quote }}
EOF
cd ~/helmlab
helm template myapp ./myapp -n myapp -s templates/zz-lookup.yaml | tail -1
helm template myapp ./myapp -n myapp -s templates/zz-lookup.yaml --dry-run=server | tail -1
rm ~/helmlab/myapp/templates/zz-lookup.yaml
nsUid: "EMPTY" nsUid: "6b1c2f0e-3d7a-4c55-9e0b-1f2a3b4c5d6e"
dig Safely reads a nested dictionary value and returns a default if the path is missing, which is safer than $ns.metadata.uid (the latter fails when $ns is nil and produces a nil pointer error; see Module 8).
Case 1: every upgrade restarts all Pods
Problem: The chart uses randAlphaNum 32 to generate a password, and adds a checksum annotation for the Secret to the Deployment, so every helm upgrade (even when nothing changed) generates a new password and triggers a rolling restart. Approach: Change to lookup reuse the existing Secret, or simply require users to supply existingSecret. Configuration: In a GitOps environment (where lookup returns empty), you can only use existingSecret + External Secrets. Limitations: lookup requires the release's runtime identity to have get permission on Secrets.
Case 2: an annotation value "true" becomes a boolean and causes the install to fail
Problem: An Ingress annotation nginx.ingress.kubernetes.io/ssl-redirect: {{ .Values.sslRedirect }} renders as true, and the API Server reports that annotation values must be strings. Approach: Quote all annotation, label, and env values consistently with quote, or use toYaml to output the whole annotations dict (toYaml automatically quotes the values that need it). Limitations: Label values must also meet the 63-character and character set rules (Module 3).
Case 3: config changed, Pods did not restart
Problem: A ConfigMap is injected as environment variables; after you change values, helm upgrade only the ConfigMap is updated, and Pods keep the old values. Approach: Add to the Pod template annotations checksum/config: {{ include (print $.Template.BasePath "/configmap.yaml") . | sha256sum }}, so a config change leads to an annotation change, which triggers a rolling update (recommended in the official Tips & Tricks). Limitations: Only works for configuration rendered within the same chart.
Common mistakes and fixes
Error: parse error at (myapp/templates/configmap.yaml:9): function "Quote" not defined
Cause: Function names are case-sensitive (quote), or you used a function that does not exist in Helm or was removed (such as env,expandenv, or a function only added in Helm 4.4 toPrettyRawJson).
Fix: Check the official Template Function List; this is a parse-time error, so the whole chart will not render.
Error: execution error at (myapp/templates/deployment.yaml:35:20): image.repository is required
Cause:required Validation failed; the message is the hint text you wrote.
Fix: Provide the value (--set image.repository=…); also mark it as required in the schema so lint catches it early (note: helm lint for required only logs a warning and does not fail).
error calling include: template: no template "myapp.fullnam" associated with template "gotpl"
Cause: The include template name is misspelled, or it is defined in a file that is never loaded (for example, a library chart that was not added to dependencies).
grep -rn 'define "' ~/helmlab/myapp/templates ~/helmlab/myapp/charts 2>/dev/null
error calling eq: incompatible types for comparison
Cause: YAML numbers are parsed as float64 (JSON semantics) or int64, which has a different type from the integer literal when compared in the template.
Fix: Convert both sides: {{ if eq (int .Values.replicaCount) 1 }}; or use toString to compare strings.
Output has extra blank lines, or “mapping values are not allowed in this context”
Cause: Whitespace control is wrong: missing {{- leaves a blank line, or -}} eats the newline of the next line, so two lines get joined together.
helm template myapp ./myapp -s templates/x.yaml --debug | cat -A | sed -n '1,40p'
Fix: Apply the rule: control structures use {{-, not -}} (practice this in Interactive 2).
1. Render only the deployment template, and simulate a Kubernetes 1.37.0 cluster where the Gateway API HTTPRoute exists.
helm template myapp ./myapp -s templates/deployment.yaml --kube-version 1.37.0 \ --api-versions gateway.networking.k8s.io/v1/HTTPRoute
2. Write an expression: the Pod annotation checksum/config equals the sha256 of the rendered configmap template.
checksum/config: {{ include (print $.Template.BasePath "/configmap.yaml") . | sha256sum }}A colleague wrote {{ default 3 .Values.replicaCount }}, and a user, to “temporarily stop the service,” sets replicaCount: 0, but 3 replicas are still running. Explain why and give a fix.
default Treats 0 as empty and returns 3. Fix: put the default value 3 in values.yaml, and have the template use {{ .Values.replicaCount }}; declare it in the schema "type":"integer","minimum":0. If you must distinguish “unset” from 0, use hasKey .Values "replicaCount".
Verified teaching videos
Official docs
- Template Functions and Pipelines (includes notes on lookup and dry-run)
- Template Function List
- Flow Control (whitespace control)
- Chart Development Tips and Tricks
- Go text/template
Video storyboard (about 90 seconds)
Visual: one line of template code, three functions chained like a pipe, with a data ball flowing from left to right.
Narration: the pipe passes the result on the left as the last argument to the function on the right, which is why default and quote can be chained.
Visual: the resources dict is flattened into multi-line text by toYaml, and nindent pushes it to the 12-space position.
Narration: templates do not understand YAML; indentation depends entirely on nindent.
Visual: the user enters false, and the default true box drops false and replaces it with true, with a red warning.
Narration: default treats both false and 0 as empty, so write boolean defaults in values.yaml.
Visual: lookup reaches out to the cluster, but in a helm template run its hand is blocked and it returns an empty dict; with dry-run set to server, it gets the data back.
Narration: lookup only returns values when it is actually connected to a cluster.
Module 3 · Named templates, _helpers.tpl and scope
- Use
defineto define a named template, and useinclude(nottemplate) to call it and pipe the result; know that template names are global, so they must be prefixed with the chart name. - Accurately state what
.and$point to on any given line: top level,withinsiderangeinside, and inside a named template; usedictto pass multiple arguments to a helper. - Write a standard helper:
name/fullname(63-character truncation +trimSuffix "-"),labelsand the never-changingselectorLabels,serviceAccountName,image.
What: named template (also called a partial)
{{/* Definition: names should follow "<chart name>.<purpose>" */}}
{{- define "myapp.selectorLabels" -}}
app.kubernetes.io/name: {{ include "myapp.name" . }}
app.kubernetes.io/instance: {{ .Release.Name }}
{{- end }}
selector:
{{- include "myapp.selectorLabels" . | nindent 4 }}
- Template files whose names start with
_(e.g._helpers.tpl) are not output as manifests, and only holddefine. - Helm loads the chart and all of its subcharts templates into a single template set, so template names are global: if two charts both define
"fullname", the one loaded later overrides the earlier one. Official best practice: always prefix template names with the chart name (myapp.fullname).
include vs. template
{{ template "x" . }} | {{ include "x" . }} | |
|---|---|---|
| Source | Go template built-in action | Helm-provided function |
| Can it be piped? | No: output is written directly to the result | Yes: returns a string, which can be | nindent 4,| sha256sum,| trim |
| Indentation control | can only hard-code the indentation of the define content | the caller decides the indentation, so the same helper can be reused at different levels |
| Recommendation | Avoid using | in charts; always use (official docs:it is considered preferable to use include over template) |
Why: why scope is so easy to get wrong
In Go templates, . (dot) is the “current context,” and it is rebound:
| Location | . points to | $ points to |
|---|---|---|
| top level of the template file | root context {Values, Release, Chart, Capabilities, Template, Files} | same as above (root) |
{{ with .Values.resources }} inside | .Values.resources value of | root (unchanged) |
{{ range .Values.hosts }} inside | current element | root (unchanged) |
{{ range $k, $v := .Values.env }} inside | current value (same as $v ) | root (unchanged) |
define inside (called include "x" ARG by) | ARG | is also ARG—inside a named template, the $ is the passed-in argument, not the outer root! |
So inside range if you want to use .Release.Name you must write $.Release.Name; when calling a helper inside range, you must pass $: {{ include "myapp.fullname" $ }}. When you need to pass both the root context and the current element, use dict to bundle them:
{{- range .Values.extraServices }}
{{ include "myapp.extraService" (dict "root" $ "svc" .) }}
{{- end }}
{{- define "myapp.extraService" -}}
name: {{ include "myapp.fullname" .root }}-{{ .svc.name }}
port: {{ .svc.port }}
{{- end }}
How: walk through the standard helpers one by one (from Helm 4.3.2's helm create)
{{- define "myapp.fullname" -}}
{{- if .Values.fullnameOverride }}
{{- .Values.fullnameOverride | trunc 63 | trimSuffix "-" }}
{{- else }}
{{- $name := default .Chart.Name .Values.nameOverride }}
{{- if contains $name .Release.Name }}
{{- .Release.Name | trunc 63 | trimSuffix "-" }}
{{- else }}
{{- printf "%s-%s" .Release.Name $name | trunc 63 | trimSuffix "-" }}
{{- end }}
{{- end }}
{{- end }}
- Why 63: Service names must be DNS-1035 labels (≤ 63 characters), and label values are also ≤ 63 characters.
trunc 63After truncation, it may end with-(invalid), so also applytrimSuffix "-". - Release name limit 53: Helm validates that release names are ≤ 53 characters (leaving room for
-myapp,-redisand similar suffixes). - The contains check: if the release name already includes the chart name (
myapp,myapp-prod), use the release name directly, to avoidmyapp-myapp. - labels vs selectorLabels:
labels= selectorLabels +helm.sh/chart(including the chart version) +app.kubernetes.io/version+managed-by; The selector may only use selectorLabels. The Deployment'sspec.selectorafter creation is immutable, so if you put the version into the selector, the next chart upgrade willfield is immutable(Module 8).
When: when to extract a helper
- The same content appears in two or more templates (labels, image address, Redis address, ServiceAccount name).
- It has calculation logic (truncation, conditional selection): put it in a helper with comments, to make it easier to test and reuse.
- Reuse across charts → put it in a library chart (Module 6).
Comparison with similar tools
| Helm named templates | Jinja2 macro | Kustomize component | |
|---|---|---|---|
| Parameters | Only one parameter (use dict/list to bundle multiple) | multiple named parameters | — |
| Scope | Global namespace (prefix required) | Scoped per import | Scoped per directory |
| Returns | string (include) | string | resource patches |
$ is it still the outer root?” — No,$ it is the argument passed to include. ② “{{ include "myapp.labels" }} you can call it without arguments”—without arguments, . is nil, so the .Release.Name immediately causes a nil pointer error. ③ “Adding the version to the selector makes it more precise”—this causes upgrades to fail. ④ “The _helpers.tpl file name is required”—any file starting with _ works,_helpers.tpl it is only a convention.Scope diagram: . moves with the structure,$ stays at the root
with/range/include Impact on . and $ Helper call relationships (myapp after refactoring)
Core animation: how values and “.” change during one template render
Starts from merging values, then runs a simplified deployment.yaml line by line. The left side highlights the template line currently executing; the middle panel shows what . and $ point to, the helper call stack; the right side generates the output YAML step by step. Tick “Show misuse in range” to see the real error.
Commands to inspect helpers and scope
| Command | Purpose | Notes |
|---|---|---|
helm template REL DIR -s templates/x.yaml | Show only how one template uses helpers | The helper file itself cannot be -s (it produces no manifests) |
grep -rn 'define "' DIR/templates | List all named templates | Check prefixes and name clashes |
helm template … --set nameOverride=… / fullnameOverride=… | Test name truncation | Use awk '{print length}' to measure length |
helm template … | yq 'select(.kind=="Deployment").spec.selector' | Confirm the selector contains only stable labels | Requires installing yq (mikefarah/yq) |
kubectl get deploy myapp -n myapp -o jsonpath='{.spec.selector}' | View existing selectors in the cluster | Check before changing a helper to avoid immutable conflicts |
cd ~/helmlab
LONG=customer-portal-production-blue-green-canary-0001 # 48 characters
helm template $LONG ./myapp -s templates/service.yaml | grep -m1 ' name:'
helm template $LONG ./myapp -s templates/service.yaml --set nameOverride=frontend-service-with-a-very-long-component-name | grep -m1 ' name:' | awk '{print $2, length($2)}'
name: customer-portal-production-blue-green-canary-0001-myapp customer-portal-production-blue-green-canary-0001-frontend-serv 63
How to verify: The second name is truncated to 63 characters. If the truncation point falls exactly on -,trimSuffix it will be trimmed again, and the length becomes 62. Common mistakes: A custom helper forgets to truncate, so with a long release name, Service creation fails (must be no more than 63 characters). Production use: Run once in CI with a 53-character release name helm template | kubeconform, to catch naming problems early.
Lab 3: Refactor _helpers.tpl (about 6 minutes)
{{/*
Image address: digest takes priority; otherwise the tag defaults to Chart.AppVersion
*/}}
{{- define "myapp.image" -}}
{{- $repo := required "image.repository is required" .Values.image.repository -}}
{{- if .Values.image.digest -}}
{{- printf "%s@%s" $repo .Values.image.digest -}}
{{- else -}}
{{- printf "%s:%s" $repo (.Values.image.tag | default .Chart.AppVersion | toString) -}}
{{- end -}}
{{- end }}
{{/*
Redis address: when the Redis subchart (CloudPirates redis) is enabled, point to its Service (<release>-redis),
otherwise externalRedis.host must be provided
*/}}
{{- define "myapp.redisHost" -}}
{{- if .Values.redis.enabled -}}
{{- printf "%s-redis" .Release.Name | trunc 63 | trimSuffix "-" -}}
{{- else -}}
{{- required "must set externalRedis.host when redis.enabled=false" .Values.externalRedis.host -}}
{{- end -}}
{{- end }}
{{/*
Name of the Secret that holds the Redis password; precedence:
redisAuth.existingSecret > redis.auth.existingSecret > the <release>-redis auto-generated by the subchart > "" (no password injected)
*/}}
{{- define "myapp.redisSecretName" -}}
{{- $sub := dig "auth" "existingSecret" "" .Values.redis -}}
{{- if .Values.redisAuth.existingSecret -}}
{{- .Values.redisAuth.existingSecret -}}
{{- else if and .Values.redis.enabled $sub -}}
{{- $sub -}}
{{- else if .Values.redis.enabled -}}
{{- printf "%s-redis" .Release.Name | trunc 63 | trimSuffix "-" -}}
{{- end -}}
{{- end }}
{{/*
Component labels: usage include "myapp.componentLabels" (dict "root" $ "component" "web")
*/}}
{{- define "myapp.componentLabels" -}}
{{ include "myapp.labels" .root }}
app.kubernetes.io/component: {{ .component }}
{{- end }}image: section, add digest, and add redis / redisAuth / externalRedis sections; Module 6 will make redis a real subchart — CloudPirates redis):
cd ~/helmlab/myapp # image section: change repository to myapp and add digest sed -i 's#^ repository: nginx# repository: myapp#' values.yaml sed -i 's|^ tag: ""$| tag: ""\n # -- Takes precedence over tag when set, e.g. sha256:abc...\n digest: ""|' values.yaml cat >> values.yaml <<'EOF' # -- Redis subchart (CloudPirates redis; Module 6 adds the dependency) redis: enabled: true # -- Secret from which myapp reads the Redis password (leave empty to use the <release>-redis generated by the subchart) redisAuth: existingSecret: "" passwordKey: redis-password # -- External Redis used when redis.enabled=false externalRedis: host: "" port: 6379 EOF grep -n -A6 '^image:' values.yaml
9:image: 10- repository: myapp 11- # This sets the pull policy for images. 12- pullPolicy: IfNotPresent 13- # Overrides the image tag whose default is the chart appVersion. 14- tag: "" 15- # -- Takes precedence over tag when set, e.g. sha256:abc...
Comment lines in the skeleton values.yaml may differ slightly between minor versions; use the line numbers in your own file.
image: line to
image: {{ include "myapp.image" . | quote }}
cd ~/helmlab helm template myapp ./myapp -s templates/deployment.yaml | grep 'image:' helm template myapp ./myapp -s templates/deployment.yaml --set image.digest=sha256:0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef | grep 'image:' helm template myapp ./myapp -s templates/deployment.yaml --set image.repository= 2>&1 | tail -1
image: "myapp:1.1"
image: "myapp@sha256:0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"
Error: execution error at (myapp/templates/deployment.yaml:41:20): image.repository is required
The error location points to the line that calls the helper (where include is), while required is written inside the helper; check both places when troubleshooting.
data: temporarily add
{{- range $k, $v := .Values.config.featureFlags }}
FLAG_{{ $k | upper }}: {{ $v | quote }}
FLAG_OWNER: {{ .Release.Name }}
{{- end }}
helm template myapp ./myapp -s templates/configmap.yaml 2>&1 | tail -1
Error: template: myapp/templates/configmap.yaml:13:24: executing "myapp/templates/configmap.yaml" at <.Release.Name>: can't evaluate field Release in type bool
Inside range, . is the current value (a boolean in this case true). Change .Release.Name to $.Release.Name then re-render to pass; remove this temporary code after verifying.
Case 1: a subchart overrides the parent chart's helper
Problem: Two in-house charts both define {{ define "fullname" }}, and after combining them into an umbrella chart, the parent chart's resource names suddenly follow the subchart's naming rules. Approach: Template names are shared globally; the later-loaded one wins. Configuration: Prefix all define names with the chart name; put shared helpers in a library chart (common-lib.fullname). Limitations: Renaming a helper does not change the rendered output, but if the fullname rule changes, resources get renamed (equivalent to delete and recreate), so assess the impact first.
Case 2: after upgrading the chart spec.selector: field is immutable
Problem: Someone, to have “more complete labels,” put myapp.labels (including helm.sh/chart: myapp-0.2.0) into the selector, and the upgrade failed after the chart moved to 0.2.1. Approach: Change the selector back to myapp.selectorLabels; for existing deployments, first do kubectl delete deploy myapp --cascade=orphan before upgrading again (Module 8 troubleshooting tree). Limitations: Pods keep running during an orphan delete, but they briefly lose their controller.
Case 3: name conflicts in multi-instance deployments
Problem: Installed in the same namespace: myapp-blue and myapp-green two releases, and a template hardcodes name: myapp-config, so the second release fails to install (the resource is already owned by another release). Approach: Generate all resource names via myapp.fullname . Configuration: During review, search for grep -n "name: [a-z]" templates/ hardcoded names. Limitations: Helm 4 uses SSA; the conflict message names the field manager, but the fix is the same.
Common mistakes and fixes
at <.Release.Name>: can't evaluate field Release in type string
Cause: Inside range/with you used a root object field, but here . is not the root.
Fix: Change to $.Release.Name; when calling the helper, pass $.
at <.Release.Name>: nil pointer evaluating interface {}.Name
Cause:include "myapp.fullname" No second argument was passed, or you passed nil (such as .Values.notExist), and inside the helper . is nil.
Fix:{{ include "myapp.fullname" . }}; when you need multiple arguments, use dict.
template: no template "myapp.labels" associated with template "gotpl"
Cause: The helper name is spelled inconsistently, or the template was copied from a library chart without changing the prefix.
grep -rn 'define "' ~/helmlab/myapp/templates | sort
Service "…" is invalid: metadata.name: Invalid value: "…": must be no more than 63 characters
Cause: A custom helper or hardcoded name is not truncated.
Fix: Pass all names through trunc 63 | trimSuffix "-"; when adding a suffix, concatenate first and then truncate (printf "%s-metrics" $fullName | trunc 63 | trimSuffix "-").
Error: INSTALLATION FAILED: release name "…": invalid release name, must match regex … and the length must not be longer than 53
Cause: The release name exceeds 53 characters or contains uppercase letters or underscores.
Fix: Shorten the release name; when CI generates it from a branch name, lowercase and truncate it first.
1. List the names of all named templates in the chart (including subchart directories), and find the ones without a chart name prefix.
grep -rhoE 'define "[^"]+"' ~/helmlab/myapp | sort -u grep -rhoE 'define "[^"]+"' ~/helmlab/myapp/templates | grep -v 'define "myapp\.'
2. Render the deployment, output only the selector, and confirm it contains no version label.
helm template myapp ./myapp -s templates/deployment.yaml | yq '.spec.selector'
You need to add a worker Deployment to myapp (same image, different command). How do you design the helpers so the web and worker Service selectors do not interfere with each other, and a chart upgrade does not trigger an immutable selector error?
Keep myapp.selectorLabels (name + instance) unchanged, and add a myapp.componentSelectorLabels: selectorLabels + app.kubernetes.io/component: web|worker, passed via (dict "root" $ "component" "worker") as an argument. Both Deployments and the web Service use the selector with component. Note: adding existing web Deployment's selector to include component is also an immutable change. Either use the component selector only for the new worker and leave web as is, or plan a migration that does an orphan delete and then recreates the resources.
Verified teaching videos
Official docs
- Named Templates (include vs template)
- Variables ($ and scope)
- Best Practices: Templates
- Best Practices: Labels and Annotations
- Kubernetes Recommended Labels
Video storyboard (about 100 seconds)
Visual: three sets of values (chart defaults, prod.yaml, --set) stack like layers and merge into one .Values dict.
Narration: rendering starts from the merged values; later sources have higher precedence.
Visual: a glowing dot represents “.” and moves between template lines; entering with jumps it to the resources dict, while the $ anchor stays pinned to the root.
Narration: the dot is the current context; with and range change it, while the dollar sign always points to the root.
Visual: include calls are pushed onto the stack like function calls; inside the helper, both the dot and the dollar sign become the passed-in argument.
Narration: inside a named template, the dollar sign is the passed-in argument, not the outer root, so what you pass at the call site is critical.
Visual: selector labels are locked with a padlock icon, while version labels in labels change with each upgrade.
Narration: the selector uses only the stable selectorLabels; versioned labels go into labels, which avoids immutable selector errors on upgrade.
Module 4 · Conditionals, loops and values design
- Be fluent with
if/else if/else(understanding Go template's truthiness rules),rangeiterating over lists and dicts (dict output is sorted by key), andand/or/not. - Design values following official best practices: camelCase, flat preferred, explicit types, suitable for
--set, every key commented; useenabledswitches to control optional resources. - Build a production-grade Deployment for myapp: image tag defaults to
.Chart.AppVersion, three probe types, resources, securityContext, HPA and replicas mutually exclusive, PDB, topology spread, and optional Ingress/HTTPRoute.
What: conditionals and loops
| Construct | Syntax | Key points |
|---|---|---|
| Conditional | {{- if .Values.pdb.enabled }} … {{- else if … }} … {{- else }} … {{- end }} | Falsy values: false,0,nil, empty string, empty list, empty dict; everything else is truthy |
| Combining | {{- if and .Values.ingress.enabled (not .Values.httpRoute.enabled) }} | and/or is a function; sub-expressions in its arguments need parentheses |
| with | {{- with .Values.nodeSelector }} nodeSelector: {{- toYaml . | nindent 8 }} {{- end }} | “output only if non-empty + switch scope” in one; can take {{- else }} |
| range over a list | {{- range .Values.ingress.hosts }} - host: {{ .host | quote }} {{- end }} | . $v is the element; {{ range $i, $h := … }} $i gets the index |
| range over a dict | {{- range $name, $value := .Values.env }} | in alphabetical key order—output is stable, so random map ordering does not cause a diff each time |
| range over an integer | {{- range $i := until 3 }} | Sprig's until generates 0..n-1 |
| Abort rendering | {{- fail "message" }} | Gives a readable error for invalid combinations (in lint mode it only logs and does not fail) |
Why: values.yaml is the chart's public interface
Users almost never read templates; they only read helm show values Once key names are published, renaming them is a breaking change (a user's -f prod.yaml is silently ignored, because unknown keys do not error by default unless there is a schema (Module 5). So design values as carefully as you would design an API.
How: official values best practices (helm.sh Best Practices → Values)
- Naming: start with a lowercase letter, use camelCase:
replicaCount,podDisruptionBudget; do not use-(templates cannot access it via.Values.pod-annotations). - Flat first: in most cases flat is better than nested, so templates need fewer existence checks; use nesting only when there is a group of strongly related fields (such as
image.repository/tag). - Explicit types: quote strings; values that might be misparsed (
"1.10","true","0755") must always be quoted. - Consider
--set: dicts are easier to override than lists (--set env.LOG_LEVEL=debugversus--set extraEnv[0].value=…). - Comment every key, starting the comment with the key name or using
## @param/# --style (helm-docs uses this to generate the README; Lesson 6). - Control optional resources with
enabledenabled flags:ingress.enabled,httpRoute.enabled,autoscaling.enabled,podDisruptionBudget.enabled,serviceAccount.create.
Key design decisions for the production version of myapp
| Decision | Template approach | Reason |
|---|---|---|
| Image tag defaults to AppVersion | tag | default .Chart.AppVersion (in the myapp.image helper) | When chart and app versions are released together, users do not need to remember a tag; digest takes precedence over tag for immutable deployments |
| HPA and replicas are mutually exclusive | {{- if not .Values.autoscaling.enabled }} replicas: … {{- end }} | If replicas is still written when HPA is enabled, every helm upgrade upgrade resets the replica count to a fixed value |
| Three probes | startup (slow-start protection) + liveness + readiness, all generated from values using toYaml output | Allows users to fully replace the probe structure (httpGet/exec/grpc) |
| Default requests set | resources.requests with defaults; only memory limit is set | The skeleton suggests no default resources; production charts usually provide conservative requests for HPA and scheduling (this differs from the skeleton's comments, and is a deliberate choice) |
| securityContext is tightened by default | runAsNonRoot,readOnlyRootFilesystem,drop: [ALL],seccompProfile: RuntimeDefault | meets the restricted level of Pod Security Standards; the myapp image runs as UID 10001 (Docker course) |
| PDB enabled by default | minAvailable: 1, mutually exclusive with maxUnavailable (if both are set, then fail) | Keeps at least one replica during node maintenance; with 1 replica, NOTES warns that it will block drain |
| Config changes trigger a rolling update | Pod annotation checksum/config | ConfigMap is injected via envFrom and does not hot-reload |
| HTTPRoute needs the CRD | .Capabilities.APIVersions.Has "gateway.networking.k8s.io/v1/HTTPRoute", and if it is missing, fail | when enabled but the cluster lacks Gateway API, give a clear error instead of failing partway through the install |
When: what should not be turned into values
- Things users should not change: selector labels, container names, port names
http(probes and the Service reference them). - “Pass-through everything” should be used with restraint: provide
extraEnv,volumes,podAnnotationsand similar extension points; do not expose the entire Pod spec as values.
Comparison with similar tools
| Helm values | Kustomize | Terraform variables | |
|---|---|---|---|
| Interface definition | values.yaml + values.schema.json | None (patches are the interface) | variable block + validation |
| optional resources | if .Values.x.enabled | components / different overlays | count / for_each |
| Unknown keys | silently ignored by default (a schema can reject them) | a missing patch target is an error | undeclared variables are an error |
if .Values.replicaCount can tell whether a value was set”—setting it to 0 is also falsy. ② “The order of range over a dict is random”—Go templates sort maps by key. ③ “Keeping replicas when HPA is enabled is fine”—every upgrade overwrites the replica count computed by HPA (under Helm 4's SSA, the replicas field is still managed by Helm). ④ “The more defaults, the better”—hardcoding nodeSelector,tolerations and similar environment-specific settings will make the chart unschedulable on other clusters.values toggles → rendered resources
Interactive: values design bench
Toggle switches and change the replica count; the right side shows live helm template the resource list and key fields that will be output, and review comments below (for example, “1 replica + PDB minAvailable 1 will block drain”). The rules match the templates in this module's lab.
Commands to check values and conditional rendering
| Command | Purpose | Notes |
|---|---|---|
helm show values ./myapp | View default values (user's perspective) | The first step in reviewing values |
helm template … --set autoscaling.enabled=true | grep -c 'replicas:' | Verify that HPA and replicas are mutually exclusive | Result should be 0 |
helm template … --set-json 'env={"LOG_LEVEL":"debug"}' | Override complex structures with JSON | --set-json good for lists/dicts |
helm template … --set podDisruptionBudget.maxUnavailable=1 | Trigger the mutual-exclusion check | should report the fail message |
helm get values REL -a | View all values the release actually uses | -a including defaults |
kubectl get pdb,hpa -n myapp | Confirm optional resources | ALLOWED DISRUPTIONS column |
cd ~/helmlab helm template myapp ./myapp -f values-ext-redis.yaml | grep '^kind:' | sort | uniq -c helm template myapp ./myapp -f values-ext-redis.yaml --set autoscaling.enabled=true | grep -E '^kind:|replicas:'
1 kind: ConfigMap
1 kind: Deployment
1 kind: Pod
1 kind: PodDisruptionBudget
1 kind: Service
1 kind: ServiceAccount
kind: PodDisruptionBudget
kind: ServiceAccount
kind: ConfigMap
kind: Service
kind: Deployment
kind: HorizontalPodAutoscaler
kind: Pod
How to verify: After enabling HPA, the Deployment has no replicas:, and a HorizontalPodAutoscaler appears. Ordinary manifests are sorted by the order in the Helm source ( InstallOrder PodDisruptionBudget → ServiceAccount → ConfigMap → Service → Deployment → HPA), and the test hook Pod comes last. Common mistakes: HPA is enabled but the cluster has no metrics-server, so HPA shows <unknown>/70%. Production use: Write common combinations as ci/*-values.yaml, and render and validate each one in CI.
Lab 4: Write production-grade templates and deploy them (about 8 minutes)
## Default configuration for myapp. Key names use camelCase; the comment above each key describes its purpose.
# -- Replica count (ignored when autoscaling.enabled=true; controlled by the HPA)
replicaCount: 2
# -- Number of old ReplicaSets to retain
revisionHistoryLimit: 5
image:
# -- Image repository (required)
repository: myapp
# -- Pull policy: Always / IfNotPresent / Never
pullPolicy: IfNotPresent
# -- Image tag; if empty, uses appVersion from Chart.yaml
tag: ""
# -- Image digest (sha256:...); takes precedence over tag when set
digest: ""
# -- Pull secrets for private repositories, e.g. [{name: regcred}]
imagePullSecrets: []
# -- Override the chart name (affects the name label and resource names)
nameOverride: ""
# -- Fully override resource names
fullnameOverride: ""
serviceAccount:
# -- Whether to create a ServiceAccount
create: true
# -- Whether to automatically mount the API token (myapp does not call the API, so disabled by default)
automount: false
# -- ServiceAccount annotations (e.g. Workload Identity; see Lesson 3)
annotations: {}
# -- Name; if empty, uses fullname
name: ""
# -- Extra Pod annotations
podAnnotations: {}
# -- Extra Pod labels (not included in the selector)
podLabels: {}
# -- Container listening port (myapp's gunicorn listens on 5000)
containerPort: 5000
# -- Pod-level security context (meets PSS restricted)
podSecurityContext:
runAsNonRoot: true
runAsUser: 10001
runAsGroup: 10001
fsGroup: 10001
seccompProfile:
type: RuntimeDefault
# -- Container-level security context
securityContext:
allowPrivilegeEscalation: false
readOnlyRootFilesystem: true
capabilities:
drop: ["ALL"]
service:
# -- Service type
type: ClusterIP
# -- Service port (forwards to the container's http port)
port: 80
ingress:
# -- Whether to create an Ingress
enabled: false
# -- IngressClass name
className: ""
# -- Ingress annotations
annotations: {}
# -- Hosts and paths
hosts:
- host: myapp.local
paths:
- path: /
pathType: Prefix
# -- TLS configuration
tls: []
httpRoute:
# -- Whether to create a Gateway API HTTPRoute (the cluster must have the Gateway API CRDs installed)
enabled: false
# -- HTTPRoute annotations
annotations: {}
# -- Gateways to attach to
parentRefs:
- name: gateway
sectionName: http
# -- Hostnames
hostnames:
- myapp.local
# -- Routing rules
rules:
- matches:
- path:
type: PathPrefix
value: /
# -- Resources: conservative requests by default; only memory is limited
resources:
requests:
cpu: 100m
memory: 128Mi
limits:
memory: 256Mi
# -- Startup probe: gives the app up to 150 seconds to start
startupProbe:
httpGet:
path: /healthz
port: http
periodSeconds: 5
failureThreshold: 30
# -- Liveness probe
livenessProbe:
httpGet:
path: /healthz
port: http
periodSeconds: 10
timeoutSeconds: 2
failureThreshold: 3
# -- Readiness probe
readinessProbe:
httpGet:
path: /healthz
port: http
periodSeconds: 5
timeoutSeconds: 2
failureThreshold: 3
# -- Graceful termination period (seconds)
terminationGracePeriodSeconds: 30
autoscaling:
# -- Whether to create an HPA (requires metrics-server)
enabled: false
# -- Minimum replicas
minReplicas: 2
# -- Maximum replicas
maxReplicas: 6
# -- Target CPU utilization (%, based on requests)
targetCPUUtilizationPercentage: 70
# targetMemoryUtilizationPercentage: 80
podDisruptionBudget:
# -- Whether to create a PDB
enabled: true
# -- Minimum available replicas (choose either this or maxUnavailable)
minAvailable: 1
# -- Maximum unavailable replicas (choose either this or minAvailable; leave empty to unset)
maxUnavailable: ""
topologySpread:
# -- Whether to spread Pods across nodes
enabled: true
# -- Maximum allowed skew
maxSkew: 1
# -- Topology key
topologyKey: kubernetes.io/hostname
# -- If the constraint cannot be met: ScheduleAnyway / DoNotSchedule
whenUnsatisfiable: ScheduleAnyway
# -- Extra environment variables (map; values support templates), e.g. {WORKERS: "4"}
env: {}
# -- Extra environment variables (full EnvVar object list; valueFrom is allowed)
extraEnv: []
# -- Application config (rendered into a ConfigMap and injected via envFrom)
config:
logLevel: info
featureFlags:
newCounter: true
greeting: "Hello from {{ .Release.Name }} in {{ .Release.Namespace }}"
# -- Extra volumes and mounts
volumes: []
volumeMounts: []
# -- Scheduling constraints
nodeSelector: {}
tolerations: []
affinity: {}
# -- Redis subchart (CloudPirates redis; Module 6 adds the dependency)
redis:
enabled: true
# -- Secret from which myapp reads the Redis password
redisAuth:
# -- Secret name; if empty: redis.auth.existingSecret, or the <release>-redis generated by the subchart
existingSecret: ""
# -- Key of the password in the Secret
passwordKey: redis-password
# -- External Redis used when redis.enabled=false
externalRedis:
host: ""
port: 6379
tests:
# -- Whether to render the test Pod for helm test
enabled: true
# -- Test image
image: busybox:1.37
# -- Image for the Redis connectivity test (uses only redis-cli)
redisImage: redis:8-alpineapiVersion: apps/v1
kind: Deployment
metadata:
name: {{ include "myapp.fullname" . }}
labels:
{{- include "myapp.labels" . | nindent 4 }}
spec:
{{- if not .Values.autoscaling.enabled }}
replicas: {{ .Values.replicaCount }}
{{- end }}
revisionHistoryLimit: {{ .Values.revisionHistoryLimit }}
selector:
matchLabels:
{{- include "myapp.selectorLabels" . | nindent 6 }}
template:
metadata:
annotations:
checksum/config: {{ include (print $.Template.BasePath "/configmap.yaml") . | sha256sum }}
{{- with .Values.podAnnotations }}
{{- toYaml . | nindent 8 }}
{{- end }}
labels:
{{- include "myapp.labels" . | nindent 8 }}
{{- with .Values.podLabels }}
{{- toYaml . | nindent 8 }}
{{- end }}
spec:
{{- with .Values.imagePullSecrets }}
imagePullSecrets:
{{- toYaml . | nindent 8 }}
{{- end }}
serviceAccountName: {{ include "myapp.serviceAccountName" . }}
automountServiceAccountToken: {{ .Values.serviceAccount.automount }}
{{- with .Values.podSecurityContext }}
securityContext:
{{- toYaml . | nindent 8 }}
{{- end }}
terminationGracePeriodSeconds: {{ .Values.terminationGracePeriodSeconds }}
containers:
- name: {{ .Chart.Name }}
image: {{ include "myapp.image" . | quote }}
imagePullPolicy: {{ .Values.image.pullPolicy }}
{{- with .Values.securityContext }}
securityContext:
{{- toYaml . | nindent 12 }}
{{- end }}
ports:
- name: http
containerPort: {{ .Values.containerPort }}
protocol: TCP
envFrom:
- configMapRef:
name: {{ include "myapp.fullname" . }}
env:
- name: REDIS_HOST
value: {{ include "myapp.redisHost" . | quote }}
- name: REDIS_PORT
value: {{ ternary "6379" (toString .Values.externalRedis.port) .Values.redis.enabled | quote }}
{{- with include "myapp.redisSecretName" . }}
- name: REDIS_PASSWORD
valueFrom:
secretKeyRef:
name: {{ . }}
key: {{ $.Values.redisAuth.passwordKey }}
{{- end }}
{{- range $name, $value := .Values.env }}
- name: {{ $name }}
value: {{ tpl (toString $value) $ | quote }}
{{- end }}
{{- with .Values.extraEnv }}
{{- toYaml . | nindent 12 }}
{{- end }}
{{- with .Values.startupProbe }}
startupProbe:
{{- toYaml . | nindent 12 }}
{{- end }}
{{- with .Values.livenessProbe }}
livenessProbe:
{{- toYaml . | nindent 12 }}
{{- end }}
{{- with .Values.readinessProbe }}
readinessProbe:
{{- toYaml . | nindent 12 }}
{{- end }}
{{- with .Values.resources }}
resources:
{{- toYaml . | nindent 12 }}
{{- end }}
volumeMounts:
- name: tmp
mountPath: /tmp
{{- with .Values.volumeMounts }}
{{- toYaml . | nindent 12 }}
{{- end }}
volumes:
- name: tmp
emptyDir: {}
{{- with .Values.volumes }}
{{- toYaml . | nindent 8 }}
{{- end }}
{{- if .Values.topologySpread.enabled }}
topologySpreadConstraints:
- maxSkew: {{ .Values.topologySpread.maxSkew }}
topologyKey: {{ .Values.topologySpread.topologyKey }}
whenUnsatisfiable: {{ .Values.topologySpread.whenUnsatisfiable }}
labelSelector:
matchLabels:
{{- include "myapp.selectorLabels" . | nindent 14 }}
matchLabelKeys:
- pod-template-hash
{{- end }}
{{- with .Values.nodeSelector }}
nodeSelector:
{{- toYaml . | nindent 8 }}
{{- end }}
{{- with .Values.affinity }}
affinity:
{{- toYaml . | nindent 8 }}
{{- end }}
{{- with .Values.tolerations }}
tolerations:
{{- toYaml . | nindent 8 }}
{{- end }}
readOnlyRootFilesystem: true when this is set, gunicorn still needs a writable temp directory, so an emptyDir is mounted at /tmp. matchLabelKeys: [pod-template-hash] Lets the new and old ReplicaSets calculate their spread separately during a rolling update (Kubernetes course Lesson 2).
{{- if .Values.podDisruptionBudget.enabled }}
{{- $pdb := .Values.podDisruptionBudget }}
{{- if and $pdb.minAvailable $pdb.maxUnavailable }}
{{- fail "Only one of podDisruptionBudget.minAvailable and podDisruptionBudget.maxUnavailable may be set" }}
{{- end }}
apiVersion: policy/v1
kind: PodDisruptionBudget
metadata:
name: {{ include "myapp.fullname" . }}
labels:
{{- include "myapp.labels" . | nindent 4 }}
spec:
{{- if $pdb.maxUnavailable }}
maxUnavailable: {{ $pdb.maxUnavailable }}
{{- else }}
minAvailable: {{ $pdb.minAvailable | default 1 }}
{{- end }}
selector:
matchLabels:
{{- include "myapp.selectorLabels" . | nindent 6 }}
{{- end }}
cd ~/helmlab/myapp/templates
# Insert the CRD check after line 1 of httproute.yaml (the if enabled line)
sed -i '1a\
{{- if not (.Capabilities.APIVersions.Has "gateway.networking.k8s.io/v1/HTTPRoute") }}\
{{- fail "httpRoute.enabled=true, but the cluster does not provide gateway.networking.k8s.io/v1 HTTPRoute (install the Gateway API CRDs)" }}\
{{- end }}' httproute.yaml
head -5 httproute.yaml
# The Service and Ingress already use service.port/targetPort: http, so no change is needed; the default ingress pathType has already been changed to Prefix in values{{- if and .Values.podDisruptionBudget.enabled (not .Values.autoscaling.enabled) (le (int .Values.replicaCount) 1) }}
Warning: replicaCount=1 and PDB minAvailable=1 will block node drain. For production, run at least 2 replicas.
{{- end }}redis (Service redis, Secret redis key redis-password):
cd ~/helmlab cat > values-ext-redis.yaml <<'EOF' redis: enabled: false externalRedis: host: redis redisAuth: existingSecret: redis EOF helm lint myapp -f values-ext-redis.yaml helm template myapp ./myapp --set podDisruptionBudget.maxUnavailable=1 >/dev/null helm template myapp ./myapp --set httpRoute.enabled=true >/dev/null helm template myapp ./myapp -f values-ext-redis.yaml -s templates/deployment.yaml | grep -A5 'name: REDIS_PASSWORD' helm upgrade --install myapp ./myapp -n myapp -f values-ext-redis.yaml \ --wait --timeout 3m kubectl -n myapp get deploy,pdb,pod -l app.kubernetes.io/instance=myapp
==> Linting myapp
1 chart(s) linted, 0 chart(s) failed
Error: execution error at (myapp/templates/pdb.yaml:4:4): Only one of podDisruptionBudget.minAvailable and podDisruptionBudget.maxUnavailable may be set
Error: execution error at (myapp/templates/httproute.yaml:3:4): httpRoute.enabled=true, but the cluster does not provide gateway.networking.k8s.io/v1 HTTPRoute (install the Gateway API CRDs)
- name: REDIS_PASSWORD
valueFrom:
secretKeyRef:
name: redis
key: redis-password
Release "myapp" has been upgraded. Happy Helming!
...
NAME READY UP-TO-DATE AVAILABLE AGE
deployment.apps/myapp 2/2 2 2 2d
NAME MIN AVAILABLE MAX UNAVAILABLE ALLOWED DISRUPTIONS AGE
poddisruptionbudget.policy/myapp 1 N/A 1 40s
NAME READY STATUS RESTARTS AGE
pod/myapp-7d9c5b6f4d-2kq8x 1/1 Running 0 38s
pod/myapp-7d9c5b6f4d-v7mzt 1/1 Running 0 25s
In offline rendering, the helm template .Capabilities.APIVersions only includes built-in APIs, so enabling httpRoute triggers fail; to render HTTPRoute offline, add --api-versions gateway.networking.k8s.io/v1/HTTPRoute. This upgrade replaces the Lesson 1 release's values entirely with the new interface (no longer using values-lab.yaml): the Service port changes from 5000 in Lesson 1 to 80,targetPort: http while it still points to container port 5000; the password is still referenced via secretKeyRef and does not enter the release record. The selector labels are the same as in Lesson 1, so an in-place upgrade works. If Pods are not Ready, first check the Module 8 troubleshooting tree (common causes: image not loaded with kind load, or wrong Secret name or key).
helm template myapp ./myapp -f values-ext-redis.yaml \
--set env.WORKERS=4 --set 'env.SERVICE_URL=http://{{ include "myapp.fullname" . }}' \
-s templates/deployment.yaml | grep -A1 -E 'name: (SERVICE_URL|WORKERS)'
- name: SERVICE_URL
value: "http://myapp"
- name: WORKERS
value: "4"
Output sorted alphabetically by key name; tpl expands templates in user values; toString ensures that the number 4 also passes through tpl without error.
Case 1: HPA scaled to 8 replicas, then went back to 2 after one helm upgrade
Problem: The chart always renders replicas, so each release scales down instantly and causes 5xx errors. Approach:{{- if not .Values.autoscaling.enabled }} Wrap replicas in a conditional. Configuration: When migrating an existing release, first confirm the HPA has taken over, then upgrade to a version without replicas. Limitations: New installs in Helm 4 use SSA; for releases upgraded from Helm 3, field ownership may still sit under the old manager. See Lesson 7 for details.
Case 2: a PDB stalled a node upgrade for 1 hour
Problem: Dev environment values set replicaCount: 1, while the PDB defaults to minAvailable: 1; during AKS node upgrades, drain kept waiting and eventually timed out. Approach: Add a warning in NOTES; in dev values, disable the PDB or use 2 replicas; in the schema, you can use if/then a constraint rule (Module 5). Limitations: Managed clusters' node upgrades usually have PDB wait timeout policies; follow each cloud's documentation.
Case 3: the user's values file “had no effect”
Problem: A user wrote replicas: 3 (but the chart's key is replicaCount), so Helm silently ignores it and the deployment still runs 2 replicas. Approach: Introduce values.schema.json and set "additionalProperties": false, so unknown keys error out directly (Module 5). Limitations: When top-level additional properties are disallowed, you must also declare the subchart name (redis) and global must also be declared.
Common mistakes and fixes
Deployment.apps "myapp" is invalid: spec.template.spec.containers[0].securityContext.runAsNonRoot … container has runAsNonRoot and image will run as root
Cause: This is an error from the kubelet while creating the container (Pod event CreateContainerConfigError): the image's default user is root, which conflicts with runAsNonRoot: true .
kubectl -n myapp describe pod -l app.kubernetes.io/instance=myapp | grep -A3 -i error
Fix: In the image, set USER 10001 (already done in the Docker course), or set runAsUser in values.
CrashLoopBackOff: OSError: [Errno 30] Read-only file system: '/tmp/…'
Cause:readOnlyRootFilesystem: true, the app writes local files.
Fix: Mount an emptyDir for directories that need writes (already mounted in this lesson /tmp); do not disable the read-only root filesystem just for convenience.
HPA TARGETS shows <unknown>/70%
Cause: No metrics-server, or the Pods have no CPU requests.
kubectl -n myapp describe hpa myapp | tail -5 kubectl get apiservices | grep metrics
Fix: Install metrics-server (Kubernetes course Lesson 2), and make sure resources.requests.cpu has a value.
error converting YAML to JSON: yaml: line 31: did not find expected key (after adding range env)
Cause: The indentation inside the range block does not match the outer env: list, or {{- eats the newline.
helm template myapp ./myapp -s templates/deployment.yaml --debug 2>&1 | sed -n '25,40p'
Fix: Check indentation line by line against the rendered output (covered in detail in Module 8).
PDB shows ALLOWED DISRUPTIONS 0 and kubectl drain is stuck: Cannot evict pod as it would violate the pod's disruption budget
Cause: Replica count ≤ minAvailable, or some Pods are not Ready.
Fix: Add replicas or adjust the PDB; investigate Pods that are not Ready. Do not use maxUnavailable: 0 (it blocks voluntary disruptions indefinitely).
1. Use one command to confirm that the Deployment has no replicas field after HPA is enabled.
helm template myapp ./myapp --set redis.enabled=false --set externalRedis.host=x \ --set autoscaling.enabled=true -s templates/deployment.yaml | grep -c 'replicas:' # expect 0
2. Render HTTPRoute offline (simulating a cluster with Gateway API).
helm template myapp ./myapp --set redis.enabled=false --set externalRedis.host=x \ --set httpRoute.enabled=true --api-versions gateway.networking.k8s.io/v1/HTTPRoute -s templates/httproute.yaml
The product team requires “production must have an Ingress; dev can do without,” and plans to migrate from Ingress to Gateway API later. How would you design the values and templates?
Two independent switches ingress.enabled and httpRoute.enabled, allowing both to be enabled during migration (both paths point to the same Service); in the template, HTTPRoute uses .Capabilities.APIVersions.Has to check the CRD and fail warn; the production values file explicitly enables ingress, and the schema uses if/then (for example, when global.environment == "prod" requires ingress.enabled or httpRoute.enabled is true). After migration, first disable ingress, then remove the Ingress template in the next major chart version.
Verified teaching videos
Official docs
- Flow Control
- Best Practices: Values
- Best Practices: Pods and PodTemplates
- Pod Security Standards
- Gateway API
Video storyboard (about 90 seconds)
Visual: values.yaml looks like a control panel with a row of switches; turn on autoscaling, the replicas line in the Deployment fades out, and an HPA card appears.
Narration: when HPA is enabled, replicas is not rendered; otherwise every upgrade resets the replica count.
Visual: the keys of the env dict enter range out of order, and come out sorted alphabetically.
Narration: range over a dict sorts by key, so the output is stable and does not produce meaningless diffs.
Visual: replica count 1 collides with PDB minimum available 1; the drain progress bar gets stuck, and NOTES pops up a warning.
Narration: encode operational experience into the template: invalid combinations fail outright, and risky combinations trigger a warning.
Visual: the user writes the key name wrong (for example, replicas) and it is silently ignored; in the next shot, the schema blocks it with an error.
Narration: values is the chart's interface; the next module adds type checking with a schema.
Module 5 · values.schema.json validation
- Explain when and on what data values.schema.json validates:
install/upgrade/lint/template, it validates the final merged values; a subchart's schema validates its own section. - Can write
type,required,enum,minimum/maximum,pattern,additionalProperties,if/then, and knows which JSON Schema draft versions Helm 4 supports. - Read Helm 4's schema error format and know when to use
--skip-schema-validation.
What: a JSON Schema that describes the shape of values
An optional file in the chart root: values.schema.json. After Helm merges all value sources, it validates the final .Values; if the values do not match, it before rendering fails, listing every violation.
Why: isn't the required enough in templates?
Template required / fail | values.schema.json | |
|---|---|---|
| Detection timing | When rendering reaches that line (and only the first error is reported) | Before rendering, listing all errors at once |
| Type checking | Almost none ("3" and 3 both render) | type: integer Precise rejection |
| Unknown keys (typos) | Silently ignored | additionalProperties: false Errors directly |
helm lint in | required/fail in lint mode,it only logs and does not fail (source: LintMode) | Errors normally |
| IDE support | None | Editors can use the schema for completion and hints |
How: implementation details in Helm 4 (verified against v4.3.2 source)
- Validation library:
github.com/santhosh-tekuri/jsonschema/v6, supporting draft-04, draft-06, draft-07, draft/2019-09, draft/2020-12. (The library used by early Helm 3 versions only supported up to draft-07; the community claim that “only draft-07 can be used” is outdated.) - If no
$schemais set, the library uses its default latest draft (currently 2020-12); library docs warn that defaults change between versions, so always declare it explicitly.$schema. format(such as"format": "uri") in 2019-09/2020-12 only annotate format by default and do not assert it. Helm does not enable format assertion, so for strict checks usepattern.- Remote
$ref(https://…) are downloaded and fail in offline environments; in that case use--skip-schema-validationor inline the referenced schema. - Validation flow: first validate the entire values with the parent chart's schema, then validate each subchart with its own schema
values.<subchart name>; skip a subchart that receives no values. - Error prefix:
values don't meet the specifications of the schema(s) in the following chart(s):, then grouped by chart name, with each entry starting with- at '/JSON pointer'.
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"type": "object",
"required": ["image"],
"properties": {
"replicaCount": { "type": "integer", "minimum": 0 },
"image": {
"type": "object",
"required": ["repository"],
"properties": {
"repository": { "type": "string", "minLength": 1 },
"pullPolicy": { "enum": ["Always", "IfNotPresent", "Never"] }
}
}
}
}
When: when it runs and when it is skipped
| Command | Validated? | Notes |
|---|---|---|
helm install / helm upgrade | Yes | Includes --dry-run all modes |
helm template | Yes | Validates offline too |
helm lint | Yes | Can be combined with --set/-f validating a specific environment's values |
any of the above commands + --skip-schema-validation | No | Only for offline or remote use $ref and similar special cases; do not use routinely in CI |
helm rollback | Does not re-render | Uses the manifest from the historical revision directly |
Comparison with similar tools
| Helm values.schema.json | Kubernetes CRD OpenAPI schema | Terraform variable validation | |
|---|---|---|---|
| Language | JSON Schema (2020-12, etc.) | OpenAPI v3 subset + CEL | HCL expressions |
| Where it runs | Helm client | API Server | Terraform CLI |
| Unknown fields | additionalProperties: false | Pruned by default (pruning) | Errors |
-f and --set. ② “Having put additionalProperties: false at the top level is all you need”: do not forget to declare the subchart names (redis) and global, otherwise enabling the dependency fails with “additional properties not allowed”. ③ “"format": "uri" can catch an invalid URL”: Helm does not assert formats. ④ “--set replicaCount=3 is a string”—--set parses 3 as an integer, while --set-string is a string.Where schema validation sits in the flow
Interactive: schema validation simulator
Edit the values below (equivalent to --set) and click “helm lint”. The simulator checks each rule in the myapp schema from this module's lab and prints an error list in the same format as Helm 4.
Schema-related commands
| Command | Purpose | Notes |
|---|---|---|
helm lint DIR --set k=v / -f env.yaml | Validate with a given set of values | In CI, run once for each environment's values |
helm template … --skip-schema-validation | Skip validation | remote $ref + offline environments |
helm show values DIR | Check whether the default values are valid against the schema | lint does this automatically |
python3 -m json.tool values.schema.json | Checks JSON syntax | If the schema itself has a syntax error, Helm reports a JSON parse error |
--set-string replicaCount=3 | Force string | Can be used to demonstrate a type error |
cd ~/helmlab helm lint myapp --set replicaCount=two --set image.pullPolicy=always --set replicas=3
==> Linting myapp [ERROR] values.yaml: - at '': additional properties 'replicas' not allowed - at '/image/pullPolicy': value must be one of 'Always', 'IfNotPresent', 'Never' - at '/replicaCount': got string, want integer [ERROR] templates/: values don't meet the specifications of the schema(s) in the following chart(s): myapp: - at '': additional properties 'replicas' not allowed - at '/image/pullPolicy': value must be one of 'Always', 'IfNotPresent', 'Never' - at '/replicaCount': got string, want integer Error: 1 chart(s) linted, 1 chart(s) failed
How to verify: All three errors are listed at once, and the templates are not rendered. lint reports them twice: values.yaml the rule validates values.yaml + overrides only with the parent chart's schema; templates/ the rule runs the same full flow as install (including subchart schemas). Note that the release name lint uses when rendering is test-release. Common mistakes: Enum values written in lowercase in the schema do not match the values Kubernetes actually uses. Production use: Treat the schema as the chart's “interface contract” and update it whenever values change in review. The exact wording of error lines may vary with the validation library version.
Lab 5: write a schema for myapp and make deliberate mistakes (about 5 minutes)
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"title": "myapp values",
"type": "object",
"additionalProperties": false,
"required": ["image", "containerPort", "service"],
"properties": {
"global": { "type": "object" },
"tags": { "type": "object", "additionalProperties": { "type": "boolean" } },
"replicaCount": { "type": "integer", "minimum": 0 },
"revisionHistoryLimit": { "type": "integer", "minimum": 0 },
"image": {
"type": "object",
"additionalProperties": false,
"required": ["repository"],
"properties": {
"repository": { "type": "string", "minLength": 1 },
"pullPolicy": { "enum": ["Always", "IfNotPresent", "Never"] },
"tag": { "type": "string" },
"digest": { "type": "string", "pattern": "^(sha256:[a-f0-9]{64})?$" }
}
},
"imagePullSecrets": {
"type": "array",
"items": { "type": "object", "required": ["name"], "properties": { "name": { "type": "string" } } }
},
"nameOverride": { "type": "string", "maxLength": 63 },
"fullnameOverride": { "type": "string", "maxLength": 63 },
"serviceAccount": {
"type": "object",
"properties": {
"create": { "type": "boolean" },
"automount": { "type": "boolean" },
"annotations": { "type": "object", "additionalProperties": { "type": "string" } },
"name": { "type": "string" }
}
},
"podAnnotations": { "type": "object", "additionalProperties": { "type": "string" } },
"podLabels": { "type": "object", "additionalProperties": { "type": "string" } },
"containerPort": { "type": "integer", "minimum": 1, "maximum": 65535 },
"podSecurityContext": { "type": "object" },
"securityContext": { "type": "object" },
"service": {
"type": "object",
"required": ["port"],
"properties": {
"type": { "enum": ["ClusterIP", "NodePort", "LoadBalancer"] },
"port": { "type": "integer", "minimum": 1, "maximum": 65535 }
}
},
"ingress": {
"type": "object",
"properties": {
"enabled": { "type": "boolean" },
"className": { "type": "string" },
"annotations": { "type": "object", "additionalProperties": { "type": "string" } },
"hosts": {
"type": "array",
"items": {
"type": "object",
"required": ["host", "paths"],
"properties": {
"host": { "type": "string" },
"paths": { "type": "array", "items": { "type": "object", "required": ["path"] } }
}
}
},
"tls": { "type": "array" }
}
},
"httpRoute": { "type": "object", "properties": { "enabled": { "type": "boolean" } } },
"resources": { "type": "object" },
"startupProbe": { "type": "object" },
"livenessProbe": { "type": "object" },
"readinessProbe": { "type": "object" },
"terminationGracePeriodSeconds": { "type": "integer", "minimum": 0 },
"autoscaling": {
"type": "object",
"properties": {
"enabled": { "type": "boolean" },
"minReplicas": { "type": "integer", "minimum": 1 },
"maxReplicas": { "type": "integer", "minimum": 1 },
"targetCPUUtilizationPercentage": { "type": "integer", "minimum": 1, "maximum": 100 },
"targetMemoryUtilizationPercentage": { "type": "integer", "minimum": 1, "maximum": 100 }
}
},
"podDisruptionBudget": {
"type": "object",
"properties": {
"enabled": { "type": "boolean" },
"minAvailable": { "type": ["integer", "string"] },
"maxUnavailable": { "type": ["integer", "string"] }
}
},
"topologySpread": {
"type": "object",
"properties": {
"enabled": { "type": "boolean" },
"maxSkew": { "type": "integer", "minimum": 1 },
"topologyKey": { "type": "string" },
"whenUnsatisfiable": { "enum": ["ScheduleAnyway", "DoNotSchedule"] }
}
},
"env": { "type": "object", "additionalProperties": { "type": ["string", "number", "boolean"] } },
"extraEnv": { "type": "array", "items": { "type": "object", "required": ["name"] } },
"config": { "type": "object" },
"volumes": { "type": "array" },
"volumeMounts": { "type": "array" },
"nodeSelector": { "type": "object", "additionalProperties": { "type": "string" } },
"tolerations": { "type": "array" },
"affinity": { "type": "object" },
"redis": { "type": "object", "properties": { "enabled": { "type": "boolean" } } },
"redisAuth": {
"type": "object",
"additionalProperties": false,
"properties": {
"existingSecret": { "type": "string" },
"passwordKey": { "type": "string", "minLength": 1 }
}
},
"externalRedis": {
"type": "object",
"properties": {
"host": { "type": "string" },
"port": { "type": "integer", "minimum": 1, "maximum": 65535 }
}
},
"tests": {
"type": "object",
"properties": { "enabled": { "type": "boolean" }, "image": { "type": "string", "minLength": 1 } }
}
},
"allOf": [
{
"if": {
"required": ["redis"],
"properties": { "redis": { "properties": { "enabled": { "const": false } }, "required": ["enabled"] } }
},
"then": {
"required": ["externalRedis"],
"properties": { "externalRedis": { "required": ["host"], "properties": { "host": { "minLength": 1 } } } }
}
}
]
}
top level additionalProperties: false reject misspelled keys; global and redis are declared. allOf + if/then Express “an external address must be provided when the built-in Redis is disabled”. redis does not forbid additional properties, because Module 6 passes subchart values here (each subchart's own schema validates that section).
cd ~/helmlab python3 -m json.tool myapp/values.schema.json >/dev/null && echo "JSON OK" helm lint myapp --strict
JSON OK ==> Linting myapp 1 chart(s) linted, 0 chart(s) failed
helm template myapp ./myapp --set-string replicaCount=3 >/dev/null helm template myapp ./myapp --set image.digest=abc >/dev/null helm template myapp ./myapp --set redis.enabled=false >/dev/null helm template myapp ./myapp --set servcie.port=8080 >/dev/null
Error: values don't meet the specifications of the schema(s) in the following chart(s):
myapp:
- at '/replicaCount': got string, want integer
Error: values don't meet the specifications of the schema(s) in the following chart(s):
myapp:
- at '/image/digest': 'abc' does not match pattern '^(sha256:[a-f0-9]{64})?$'
Error: values don't meet the specifications of the schema(s) in the following chart(s):
myapp:
- at '/externalRedis/host': minLength: got 0, want 1
Error: values don't meet the specifications of the schema(s) in the following chart(s):
myapp:
- at '': additional properties 'servcie' not allowed
Item 3: if/then The rule takes effect. Item 4: the misspelled key servcie is rejected. Without a schema, it would be silently ignored.
helm template myapp ./myapp --set servcie.port=8080 --skip-schema-validation | grep -c '^kind:'
6
Rendering proceeds as usual and the misspelled key is ignored, which is exactly what the schema is meant to prevent.
Case 1: an indentation error in production values silently disables the PDB
Problem: In prod.yaml, minAvailable is mis-indented to the top level, so Helm ignores it and the PDB falls back to defaults. Approach: top level additionalProperties: false after helm lint -f prod.yaml reports additional properties 'minAvailable' not allowed. Configuration: Run CI against environments/*.yaml and lint each one. Limitations: The schema and values must be kept in sync over time. A third-party plugin can generate a draft schema from values.yaml, which you then complete with manual constraints.
Case 2: install fails in an offline data center: Get “https://…/schema.json”: dial tcp … i/o timeout
Problem: The chart's schema uses $ref to reference an online Kubernetes JSON Schema. Approach: Inline the needed definitions into $defs, and use "$ref": "#/$defs/resources" a local reference; for a temporary workaround, use --skip-schema-validation. Limitations: Inlined Kubernetes definitions are large, so include only the fields you need.
Case 3: replicaCount: "3" causes HPA calculations to go wrong
Problem: In one environment's values a value is quoted, so the template renders it as replicas: 3 It looks fine, but in NOTES le (int …) 1 comparisons such as this and other tools reading values will then hit type errors. Approach: In the schema, "type": "integer". Limitations: JSON Schema distinguishes integer from number; 3.0 in 2020-12 it is treated as an integer.
Common errors and fixes
values don't meet the specifications of the schema(s) in the following chart(s): myapp: - at '': additional properties 'global' not allowed
Cause: Top level forbids additional properties, but does not declare global (Helm handles global values once the dependency is added).
Fix: In properties add "global": {"type":"object"}, and likewise declare each subchart name or alias.
Error: … invalid character '}' looking for beginning of object key string
Cause: The schema file itself is not valid JSON (an extra comma is the most common cause).
python3 -m json.tool myapp/values.schema.json
- at '/podDisruptionBudget/maxUnavailable': got string, want integer
Cause: Kubernetes IntOrString fields (minAvailable, maxUnavailable, maxSurge) can be 1 or "25%", but the schema only allows integer.
Fix:"type": ["integer", "string"], and for strings where needed, add pattern: "^[0-9]+%$".
Subchart error: redis: - at '/auth/enabled': got string, want boolean
Cause: The subchart's own schema validation values.redis section; the parent chart passed "true" a string (for example --set-string).
Fix: Use --set redis.auth.enabled=true; to inspect the subchart schema: tar -xOzf myapp/charts/redis-*.tgz redis/values.schema.json.
With "format": "hostname" set, an invalid hostname still passes
Cause: Helm does not enable format assertion, and under 2019-09/2020-12 format is only an annotation by default.
Fix: Use pattern, for example an RFC 1123 hostname regex.
1. Validate the chart with the production values file, and treat warnings as failures.
helm lint ./myapp -f environments/prod.yaml --strict
2. In the schema, make service.type can only be ClusterIP or LoadBalancer. Write the JSON fragment for that property.
"type": { "enum": ["ClusterIP", "LoadBalancer"] }The platform team wants “resources.limits.memory must be set in production, but may be omitted in development.” How would you express this in the schema? What are its limitations?
Add global.environment to values (or the top-level environment) an enum ["dev","staging","prod"], and in the schema write allOf: [{ if: {properties:{environment:{const:"prod"}}, required:["environment"]}, then: {properties:{resources:{required:["limits"], properties:{limits:{required:["memory"]}}}}} }]. Limitations: the schema can only validate the values themselves and cannot check whether a value is reasonable (for example, whether 64Mi is enough); it also cannot read cluster state. Stronger policy belongs in the cluster as admission control (Kyverno, Gatekeeper, ValidatingAdmissionPolicy), with the schema serving as the first line of defense in shift-left testing.
Verified instructional videos
No verified video specifically covering Helm values.schema.json (for the Helm 4 validation library) was found. The following are related general chart-authoring videos:
Official docs
- Charts → Schema Files
- JSON Schema Draft 2020-12
- santhosh-tekuri/jsonschema (the validation library used by Helm 4)
Video storyboard (about 80 seconds)
Visual: three values files merge into one JSON object, passing a “security gate” labeled values.schema.json.
Narration: before rendering, Helm uses the schema to check the final merged values.
Visual: replicaCount set to two, pullPolicy set to always, and the misspelled servcie are each stopped at the gate; the screen lists three errors with JSON pointers.
Narration: type, enum and unknown-key errors are all reported at once.
Visual: redis.enabled is switched to false, the if/then rule lights up and requires externalRedis.host.
Narration: conditional rules can express dependencies between fields.
Visual: five draft version labels, with 2020-12 highlighted and a note beside it reading “explicitly declare $schema”.
Narration: Helm 4 supports drafts up to 2020-12; declare the version explicitly in the schema.
Module 6 · Dependencies, subcharts and library charts
- In
Chart.yamldeclare dependencies (https://,oci://,file://), distinguishhelm dependency updatefrombuild, understandChart.lockandcharts/*.tgz. - Use
condition,tagsto control whether a subchart is enabled, usealiasto import the same chart multiple times; learn how the parent passes values to subcharts,globalglobal values andimport-values. - Create
type: librarychart and reuse its templates in the application chart.
What: a dependency is “another chart placed in charts/”
dependencies:
- name: redis # the subchart's name (must match its Chart.yaml)
version: "0.39.1" # same exact version as Lesson 1; a range such as "~0.39.1" also works
repository: "oci://registry-1.docker.io/cloudpirates" # OCI: stop at the namespace, do not include the chart name
condition: redis.enabled # boolean path in the parent values that decides whether it is enabled
tags:
- cache # group switch: disabled when tags.cache=false
- name: common-lib # local library chart (file:// example)
version: "0.1.0"
repository: "file://../common-lib"
| Field | Description |
|---|---|
repository | https://charts.example.com (classic repository, must first run helm repo add or use the URL directly),oci://registry/path (OCI, no repo add needed),file:// relative path (local directory),@alias (refers to an added repository) |
version | can be a range (~,^,>=); the exact version actually selected is written to Chart.lock |
condition | comma-separated multiple paths,the first boolean value that exists takes effect; condition takes precedence over tags |
tags | any tag set to true enables it; under the parent values'top level tags: set it under |
alias | Import it under another name, for example the same redis chart as cache and queue each installed once; the values keys then become the alias |
import-values | Import subchart values into the parent chart (the subchart's exports key or child:/parent mapping) |
update vs build, Chart.lock
| Command | Reads | What it does | When to use |
|---|---|---|---|
helm dependency update | Chart.yaml | by range re-resolves the latest matching versions, downloading them to charts/,rewrites Chart.lock, and deletes stale .tgz files | When adding or changing dependencies, or when you want to upgrade them |
helm dependency build | Chart.lock | Rebuilds strictly from the versions in the lock file charts/; errors out if the lock file and Chart.yaml do not match | CI, reproducible builds |
helm dependency list | Chart.yaml + charts/ | Shows the status of each dependency: ok,missing,wrong version etc., useful for | troubleshooting |
Chart.lock records the exact version and overall digest, should be committed to Git; charts/*.tgz Whether to commit it is up to the team (committed means it builds offline; if not committed, CI must run helm dependency build). Note: charts/ the .tgz files in it are “snapshots”—Changing ../common-lib a local (file://) dependency or switching the version of an OCI dependency requires rerunning helm dependency update, otherwise rendering keeps using the old .tgz. Dependencies can have their own dependencies too: the CloudPirates redis chart depends on the common library chart (listed in Chart.lock as oci://registry-1.docker.io/cloudpirates), which is already packaged in redis-0.39.1.tgz internally.
How values flow to subcharts
- Keys in the parent values that match a subchart's name (or alias) are passed to that subchart as a whole: the parent
redis.resources→ the subchart's.Values.resources. - The subchart cannot see the parent chart's other values, nor the values of sibling subcharts; the parent chart can read
.Values.redis.*(the result after the subchart's defaults are merged in). global: in the parent values,global:keys under it are copied to each subchart's.Values.global; values only pass downward, and the parent chart's global takes precedence over a subchart's own global defaults.- The key used by condition
redis.enabledalso appears as.Values.enabledin the subchart: if the subchart's schema forbids additional properties, you must declareenabledandglobal.
library chart
type: library chart cannot be installed (helm install reports library charts are not installable), and usually contains only _*.tpl defined in define. Once added as a dependency, its named templates enter the same global template set, and the application chart uses include "common-lib.xxx" to invoke them. Useful for standardizing labels, names, PDBs, probes and similar patterns across a team's charts.
When: write your own subchart, or use a community chart?
- Community charts (OCI or HTTP repositories): full-featured and actively maintained, but check licensing and image sources. For example, since August 2025 Bitnami has changed its free image catalog (old images moved to
bitnamilegacyand no longer updated). Read the latest announcement before using its charts. - This lesson's choice: consistent with Lesson 1, use CloudPirates redis 0.39.1 (Artifact Hub verified publisher, uses the official redis image pinned by tag@sha256, enables authentication by default, and generates a Secret
<fullname>keyredis-password, and supportsauth.existingSecret). Lesson 1 is a standalone releaseredis; this lesson turns it into a subchart of myapp, so the resource names becomemyapp-redis. - Local subchart / umbrella chart: several internal components released together; use
file://to reference them; this lesson uses a library chartcommon-libto demonstrate a file:// dependency. - In production, stateful services such as databases are more commonly run as managed services or separate operators, connected via
redis.enabled=false+externalRedis.host.
Comparison with similar tools
| Helm dependencies | Kustomize remote base | Terraform module | |
|---|---|---|---|
| Version locking | Chart.lock | Git ref | .terraform.lock.hcl (providers only) |
| Switch | condition / tags | Choose whether to reference | count |
| Passing values | Same-named keys in parent values + global | Patch | module input variables |
helm upgrade will be picked up automatically”—no, you must first helm dependency update. ② “A subchart can read the parent chart's .Values.image”—no. It can only get them via global or the redis: section in the parent values. ③ “Putting tags in the dependency entry is enough to toggle it”—the switch value must be set at the top level of the parent values tags: under it. ④ “The values.yaml in a library chart takes effect”—a library chart only provides templates, so do not rely on its values.Dependency resolution and values distribution
Interactive: dependency switches and values distribution
Adjust the parent chart's values, watch how condition / tags are evaluated (condition takes precedence), and see what each subchart finally receives in its .Values.
Dependency management commands
| Command | Purpose | Key flags / notes |
|---|---|---|
helm dependency update DIR (helm dep up) | Resolves per Chart.yaml, downloads, and rewrites Chart.lock | --skip-refresh does not refresh local repository indexes; --verify verifies signatures |
helm dependency build DIR | Rebuilds charts/ from Chart.lock | Use in CI for reproducibility |
helm dependency list DIR | Dependency status | --max-col-width |
helm package DIR -u | Run dependency update before packaging | Common in release pipelines |
helm template … -s charts/redis/templates/service.yaml | Look at a specific template in a subchart only | Path starts with charts/subchart-name/ . |
helm lint DIR --with-subcharts | Also lint subcharts | By default, only lint the parent chart |
helm pull oci://… --version X --untar | Download a community chart to inspect its source | When evaluating a dependency, read its values and schema first |
cd ~/helmlab helm dependency list myapp helm dependency update myapp helm dependency list myapp cat myapp/Chart.lock
NAME VERSION REPOSITORY STATUS redis 0.39.1 oci://registry-1.docker.io/cloudpirates missing common-lib 0.1.0 file://../common-lib missing Saving 2 charts Pulled: registry-1.docker.io/cloudpirates/redis:0.39.1 Digest: sha256:423b2ec14ca56bac26bf8ef429ed01e480eedeee0759fad2a71ef397b76f9dc4 Deleting outdated charts NAME VERSION REPOSITORY STATUS redis 0.39.1 oci://registry-1.docker.io/cloudpirates ok common-lib 0.1.0 file://../common-lib ok dependencies: - name: redis repository: oci://registry-1.docker.io/cloudpirates version: 0.39.1 - name: common-lib repository: file://../common-lib version: 0.1.0 digest: sha256:4f6b0c… generated: "2026-11-15T10:42:17.123456+08:00"
How to verify: STATUS changes from missing to ok,charts/ appears in redis-0.39.1.tgz and common-lib-0.1.0.tgz; the digest on the Pulled line should match the sha256:423b2ec1…9dc4 from Lesson 1 (the exact format of the Pulled and Digest lines depends on your Helm output). OCI dependencies require access to Docker Hub. Common mistakes: If classic repositories are configured on this machine, update first refreshes their indexes (showing “Hang tight while we grab the latest…”). When the network is unreachable, you can add --skip-refresh. Production use: Commit Chart.lock to Git; in CI, run helm dependency build first, then lint and package.
Lab 6: myapp + CloudPirates redis subchart (OCI) + common-lib library chart (about 10 minutes)
helm show values oci://registry-1.docker.io/cloudpirates/redis --version 0.39.1 \ | grep -nE '^global:|^ imageRegistry|^architecture|^auth:|^ enabled|^ existingSecret|^persistence:|^ size'
2:global: 4: imageRegistry: "" 38:architecture: standalone 108:auth: 110: enabled: true 118: existingSecret: "" 120: existingSecretPasswordKey: "redis-password" 279:persistence: 281: enabled: true 287: size: 8Gi
Key points: authentication is enabled by default; auth.existingSecret when empty, the chart generates the Secret itself <fullname> (key redis-password). Its secret template uses lookup to reuse an existing password, otherwise generates one with randAlphaNum—this is the pattern covered in Module 2, so offline helm template renders a different password every time. As the release myapp 's subchart, with fullname myapp-redis (Service, StatefulSet and Secret share this name).
kubectl -n myapp create secret generic myapp-redis-auth \
--from-literal=redis-password="$(openssl rand -hex 16)"
cd ~/helmlab
cat > values-kind.yaml <<'EOF'
# kind environment: the Redis subchart and myapp both use the same existing Secret
redis:
auth:
existingSecret: myapp-redis-auth
existingSecretPasswordKey: redis-password
redisAuth:
existingSecret: myapp-redis-auth
passwordKey: redis-password
EOF
redis.auth.* passed to the subchart (Redis uses it to set the access password),redisAuth.* is myapp's own key (the secretKeyRef for REDIS_PASSWORD in the Deployment). Both point to the same Secret; when only the former is set, the helper myapp.redisSecretName also falls back to redis.auth.existingSecret.
mkdir -p ~/helmlab/common-lib/templates
cat > ~/helmlab/common-lib/Chart.yaml <<'EOF'
apiVersion: v2
name: common-lib
description: Shared Helm templates for the team (library chart)
type: library
version: 0.1.0
EOF
cat > ~/helmlab/common-lib/templates/_pdb.tpl <<'EOF'
{{/*
A generic PDB. Usage:
include "common-lib.pdb" (dict "fullname" … "labels" … "selectorLabels" … "pdb" .Values.podDisruptionBudget)
*/}}
{{- define "common-lib.pdb" -}}
{{- $pdb := .pdb -}}
{{- if $pdb.enabled }}
{{- if and $pdb.minAvailable $pdb.maxUnavailable }}
{{- fail "Set only one of podDisruptionBudget.minAvailable and maxUnavailable" }}
{{- end }}
apiVersion: policy/v1
kind: PodDisruptionBudget
metadata:
name: {{ .fullname }}
labels:
{{- .labels | nindent 4 }}
spec:
{{- if $pdb.maxUnavailable }}
maxUnavailable: {{ $pdb.maxUnavailable }}
{{- else }}
minAvailable: {{ $pdb.minAvailable | default 1 }}
{{- end }}
selector:
matchLabels:
{{- .selectorLabels | nindent 6 }}
{{- end }}
{{- end }}
EOF
helm install lib-test ~/helmlab/common-lib --dry-run=client 2>&1 | tail -1
Error: INSTALLATION FAILED: library charts are not installable
cd ~/helmlab
cat >> myapp/Chart.yaml <<'EOF'
dependencies:
- name: redis
version: "0.39.1"
repository: "oci://registry-1.docker.io/cloudpirates"
condition: redis.enabled
tags:
- cache
- name: common-lib
version: "0.1.0"
repository: "file://../common-lib"
EOF
# pdb.yaml now calls the library chart
cat > myapp/templates/pdb.yaml <<'EOF'
{{- include "common-lib.pdb" (dict
"fullname" (include "myapp.fullname" .)
"labels" (include "myapp.labels" .)
"selectorLabels" (include "myapp.selectorLabels" .)
"pdb" .Values.podDisruptionBudget) }}
EOF
# values.yaml: add defaults passed to the subchart under the redis: section
sed -i 's/^redis:$/redis:\n # -- the following keys are passed to the CloudPirates redis subchart (same structure as its values.yaml)\n auth:\n enabled: true\n existingSecret: ""\n existingSecretPasswordKey: redis-password\n persistence:\n size: 1Gi\n resources:\n requests:\n cpu: 50m\n memory: 64Mi\n limits:\n memory: 128Mi/' myapp/values.yaml
cat >> myapp/values.yaml <<'EOF'
# -- Global values: copied to all subcharts (CloudPirates redis supports global.imageRegistry)
global:
# -- Image registry prefix (empty means use the image's own registry)
imageRegistry: ""
EOF
helm dependency update myapp
ls myapp/charts
Saving 2 charts Pulled: registry-1.docker.io/cloudpirates/redis:0.39.1 Digest: sha256:423b2ec14ca56bac26bf8ef429ed01e480eedeee0759fad2a71ef397b76f9dc4 Deleting outdated charts common-lib-0.1.0.tgz redis-0.39.1.tgz
Go templates allow line breaks inside an action, so the dict arguments can span multiple lines. redis.enabled Already added to values.yaml in Module 3; myapp's schema, for the redis section, only constrains enabled, and the remaining keys are validated by CloudPirates' bundled values.schema.json (draft-07).
helm template myapp ./myapp | grep '^# Source:' | sed 's/# Source: //' | sort helm template myapp ./myapp -f values-ext-redis.yaml | grep -c 'charts/redis' helm template myapp ./myapp -f values-kind.yaml | grep -c 'charts/redis/templates/secret.yaml' helm template myapp ./myapp -f values-kind.yaml -s templates/deployment.yaml | grep -A4 'name: REDIS_PASSWORD' helm template myapp ./myapp --set global.imageRegistry=registry.example.com -s charts/redis/templates/statefulset.yaml | grep -m1 'image:' helm template myapp ./myapp --set tags.cache=false | grep -c 'charts/redis'
myapp/charts/redis/templates/configmap.yaml
myapp/charts/redis/templates/headless-service.yaml
myapp/charts/redis/templates/secret.yaml
myapp/charts/redis/templates/service.yaml
myapp/charts/redis/templates/statefulset.yaml
myapp/templates/configmap.yaml
myapp/templates/deployment.yaml
myapp/templates/pdb.yaml
myapp/templates/service.yaml
myapp/templates/serviceaccount.yaml
myapp/templates/tests/test-connection.yaml
0
0
- name: REDIS_PASSWORD
valueFrom:
secretKeyRef:
name: myapp-redis-auth
key: redis-password
image: registry.example.com/redis:8.10.2@sha256:…
5
Item 3 is 0: setting auth.existingSecret stops the subchart from generating a Secret. Last item: tags.cache=false does not disable redis, because condition: redis.enabled is present and true—condition takes precedence over tags. To use tags as the single switch, do not also set the subchart's condition value.
helm lint myapp --strict -f values-kind.yaml helm upgrade --install myapp ./myapp -n myapp -f values-kind.yaml --wait --timeout 5m kubectl -n myapp get sts,deploy,svc,pvc -l app.kubernetes.io/instance=myapp kubectl -n myapp exec deploy/myapp -- printenv REDIS_HOST kubectl -n myapp port-forward svc/myapp 8080:80 >/dev/null & sleep 2; curl -s localhost:8080; curl -s localhost:8080; kill %1 # The standalone redis release from Lesson 1 is no longer needed (data is not migrated; the counter restarts from 1) helm uninstall redis -n myapp --wait kubectl -n myapp delete pvc data-redis-0
==> Linting myapp 1 chart(s) linted, 0 chart(s) failed Release "myapp" has been upgraded. Happy Helming! NAME READY AGE statefulset.apps/myapp-redis 1/1 60s NAME READY UP-TO-DATE AVAILABLE AGE deployment.apps/myapp 2/2 2 2 1d NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE service/myapp ClusterIP 10.96.31.7 <none> 80/TCP 1d service/myapp-redis ClusterIP 10.96.188.42 <none> 6379/TCP 60s service/myapp-redis-headless ClusterIP None <none> 6379/TCP 60s NAME STATUS VOLUME CAPACITY ACCESS MODES STORAGECLASS AGE persistentvolumeclaim/data-myapp-redis-0 Bound pvc-… 1Gi RWO standard 60s myapp-redis myapp v1.1 from myapp-6f8c9d7b5-2kq8x, hits=1 myapp v1.1 from myapp-6f8c9d7b5-v7mzt, hits=2 release "redis" uninstalled persistentvolumeclaim "data-redis-0" deleted
The exact names of the headless Service and PVC depend on the chart's rendered output (helm get manifest myapp -n myapp | grep -E '^kind|^ name'). Lint only the parent chart: its lint renders the subchart templates along with it; --with-subcharts suits subcharts you maintain; for third-party charts, add --strict may fail due to that chart's warnings.
Case 1: the chart built in CI differs from the local one
Problem: The dependency was written as version: "^12.0.0", and CI runs helm dependency update, and one day after upstream released 12.5.0, the subchart version in the CI package silently changed. Approach: Run update locally and commit Chart.lock; CI only runs helm dependency build. Configuration: Renovate or Dependabot periodically opens PRs to update Chart.lock. Limitations: build fails when Chart.yaml and Chart.lock disagree, which is exactly the behavior we want.
Case 2: the same redis chart used for caching and queues
Problem: Two independent Redis instances are needed. Approach: List redis twice in the dependencies, giving each alias: cache,alias: queue, and in values use cache:,queue: two separate sections, with condition set to cache.enabled etc. Limitations: Whether a subchart's fullname is based on the chart name or the alias depends on its helper implementation (the scaffold helper uses .Chart.Name, and with an alias Helm changes the subchart's name to the alias); before going live, use helm template to confirm the resource names do not collide.
Case 3: the umbrella chart's global was overwritten by a subchart default?
Problem: The team assumed the subchart's built-in global.imageRegistry: docker.io would override the private registry set by the parent chart. Approach: According to the official docs, the parent chart's global takes precedence over the subchart's global defaults. In practice, the investigation found that the subchart's templates were not using the global key. Configuration: When reviewing a subchart, check whether it supports global.imageRegistry,global.imagePullSecrets and similar conventions. Limitations: global is a convention, not a standard; different charts support different keys.
Common errors and fixes
Error: found in Chart.yaml, but missing in charts/ directory: redis
Cause: The dependency is declared but has not been downloaded.
helm dependency list myapp helm dependency update myapp # or helm dependency build in CI
Error: can't get a valid version for 1 subchart(s): "redis" (repository "oci://registry-1.docker.io/cloudpirates", version "0.99.0"). Make sure a matching chart version exists in the repo, or change the version constraint in Chart.yaml
Cause: No version in the repository satisfies the range (the version number is wrong, or the OCI address was written as the full path including the chart name).
helm show chart oci://registry-1.docker.io/cloudpirates/redis --version 0.39.1
Fix: Correct the version or range; for the OCI dependency, repository stop at the namespace (oci://registry-1.docker.io/cloudpirates).
Error: the lock file (Chart.lock) is out of sync with the dependencies file (Chart.yaml). Please update the dependencies with 'helm dependency update'
Cause: After changing the Chart.yaml dependencies, you ran build.
Fix: Run helm dependency update locally and commit the new Chart.lock.
Subchart values “have no effect”: persistence.size / resources are set, but redis still uses its defaults
Cause:① The keys are not placed under redis: (the subchart name or alias); ② the subchart's templates do not use the key at all; ③ the dependency version in Chart.yaml was changed, but did not re-run dependency update (charts/ still holds the old snapshot); ④ a StatefulSet's volumeClaimTemplates is immutable, so changing the PVC size does not affect existing PVCs.
helm get values myapp -n myapp -a | yq '.redis' helm template myapp ./myapp -s charts/redis/templates/statefulset.yaml | grep -A6 -E 'resources:|storage:' tar -tzf myapp/charts/redis-0.39.1.tgz | head
Error: INSTALLATION FAILED: library charts are not installable
Cause: Installing the type: library chart directly.
Fix: Add it as a dependency of the application chart, and use it through include.
1. In CI, restore dependencies from the lock file, lint (including subcharts), and package into dist/.
helm dependency build ./myapp helm lint ./myapp --strict -f ci/default-values.yaml helm package ./myapp -d dist/
2. Disable the redis subchart at install time and use an external Redis redis.prod.internal, with the password coming from an existing Secret prod-redis.
helm upgrade --install myapp ./myapp -n myapp --set redis.enabled=false --set externalRedis.host=redis.prod.internal --set redisAuth.existingSecret=prod-redis
The company has 20 microservice charts, each with different labeling, naming, probe and PDB conventions, which makes auditing hard. How would you standardize them with a library chart without breaking every service at once?
Set up common-lib (hosted in an internal OCI repository, versioned with SemVer), providing common-lib.labels,common-lib.fullname,common-lib.pdb,common-lib.probes etc., with name prefixes to avoid helper collisions with each chart. Migrate services one at a time: first replace only parts like PDBs and probes that do not affect resource names or selectors; helpers related to names and selectors must produce output identical to the original character for character (use helm template before-and-after diff to verify), otherwise you trigger resource recreation or immutable selector errors. When the library chart publishes a new version, use Renovate to open PRs for each service, together with the helm template | kubeconform and snapshot diff.
Verified instructional videos
No verified video specifically covering library charts was found.
Official docs
- Charts → Chart Dependencies
- helm dependency
- Subcharts and Global Values
- Library Charts
- Best Practices: Dependencies
Video storyboard (about 90 seconds)
Visual: the dependency list in Chart.yaml; after running dependency update, two archives appear in the charts directory, and a “lock” stamp is placed on Chart.lock.
Narration: update resolves version ranges and writes the lock file; build rebuilds strictly from the lock file.
Visual: two switches, condition and tags; the condition switch sits on top of tags.
Narration: condition takes precedence over tags; when the condition is false, the whole subchart is removed.
Visual: the redis section is cut from the parent values and sent to the subchart; the global section is copied and distributed to every subchart.
Narration: a subchart receives only the section matching its own name, plus global.
Visual: common-lib looks like a toolbox; myapp opens it and takes out the PDB template.
Narration: a library chart cannot be installed; it only provides reusable named templates.
Module 7 · helm lint and helm test
- Know
helm lintwhat it checks (Chart.yaml, values and schema, template rendering, YAML validity, names, deprecated APIs, selectors) and does not check; be able to use--strict,--with-subcharts,--kube-version. - Write test hooks (
helm.sh/hook: test) that verify service and Redis connectivity, and usehelm test --logsto run them, and set an appropriate deletion policy. - Use
helm template | kubeconform -strictto validate manifests offline against the Kubernetes 1.37 JSON Schema, and handle the schema for CRDs (HTTPRoute).
What: each of the three checks covers its own stage
| Tool | Input | Catches | Misses |
|---|---|---|---|
helm lint | chart directory + optional values | Chart.yaml field errors, values that do not match the schema, template syntax/execution errors, rendered output that is not valid YAML, non-compliant resource names (warning), deprecated APIs (warning), workloads missing a selector | misspelled field names (resource:), type errors (ConfigMap data set to a boolean), cluster-specific issues |
kubeconform | Rendered YAML | validates each resource against JSON Schema generated from the Kubernetes OpenAPI; -strict rejects unknown fields and duplicate keys | admission policies, quotas, whether CRDs are installed, runtime behavior |
helm template --dry-run=server | chart + cluster | Real validation by the API Server (including admission webhooks) | Requires a cluster; does not run Pods |
helm test | Deployed release | whether the service is really usable (connectivity, dependencies, key endpoints) | Deep functional testing (left to application tests) |
helm lint rules (v4.3.2 source pkg/chart/v2/lint/rules)
| Level | Example | --strict under |
|---|---|---|
| INFO | icon is recommended, values.yaml missing, and in lint mode required missing-value messages | do not fail |
| WARNING | non-strict SemVer 2 version numbers, documents starting with indentation (document starts with an illegal indent), resource names that do not follow Kubernetes naming rules, and use of APIs deprecated in the target version | Fails |
| ERROR | Chart.yaml missing fields or bad format, invalid template file extensions, render failures, YAML parse failures, values that do not match the schema, Deployments and similar missing matchLabels/matchExpressions, missing dependencies | Fails |
Three “special cases” in lint mode (easy to misjudge)
- The engine runs in
LintModemode:requiredmissing values,failonly logs them and does not make lint fail—so “required” must also be written into the schema. - does not connect to a cluster,
lookupis unavailable; the release name is fixed totest-release, and the namespace defaults todefault(can be set with--namespace). - By default only the parent chart is linted;
--with-subchartsis needed to lint each subchart. lint does not handleimport-values(the source comment references helm/helm#9658).
helm test: tests are also hooks
Any resource with helm.sh/hook: test the annotation (usually a Pod or Job) is not created during install/upgrade; it is created when helm test REL you run it. A container exit code of 0 means success. They are stored in the release's hooks and can be controlled with helm.sh/hook-weight to control order,helm.sh/hook-delete-policy to control cleanup:
| Deletion policy | Behavior | Recommendation |
|---|---|---|
before-hook-creation | Delete the previous test Pod before the next run | Recommended to always include (otherwise rerunning fails with already exists) |
hook-succeeded | Delete on success | with --logs works well together: logs are printed before cleanup |
hook-failed | Delete on failure | Usually not added; keep the failure state for troubleshooting |
helm test Common flags: --logs (prints test Pod logs after all tests finish and before cleanup),--timeout (default 5m),--filter name=xxx / --filter '!name=xxx'. helm template By default, test Pods are printed; use --skip-tests to exclude them.
When: where to place it in the pipeline
- PR:
helm lint --strict --with-subcharts+ for each environment's values, thehelm template | kubeconform -strict. - After deploying to the test environment:
helm test --logs, a failure blocks promotion. - Lesson 6 uses chart-testing (ct) to chain lint, install and test into a single command.
Comparison with similar tools
| helm test | Kubernetes Job (regular resource) | External smoke test (curl in CI) | |
|---|---|---|---|
| Ships with the chart | Yes | Yes | No |
| In-cluster network view | Yes | Yes | Needs an exposed entry point |
| Run on demand | Yes (helm test) | No (runs on every install) | Yes |
required can make lint fail”—it does not in lint mode. ③ “helm test runs automatically after install”—no, it must be run explicitly (or invoked by ct or the pipeline). ④ “helm template --validate is the right way to do server-side validation”—in Helm 4 this flag is marked deprecated; use --dry-run=server.Quality gate pipeline
Lifecycle of the test hook Pod
Interactive: quality gate simulation
Pick a “defect” to inject into the chart, then run the pipeline. Watch which gate catches it (or whether it leaks to production). These mappings come from the table on this module's Principles page.
Core commands and flags
| Command | Purpose | Key flags |
|---|---|---|
helm lint DIR | Static checks | --strict (WARNING also fails),--with-subcharts,--kube-version 1.37.0 (deprecated API checks and Capabilities),--quiet,-f/--set,--skip-schema-validation |
helm test REL | Run test hooks | --logs,--timeout 5m,--filter name=… |
helm template … --skip-tests | exclude test Pods from output | optional when piping to kubeconform |
kubeconform | Offline schema validation | -strict,-summary,-kubernetes-version 1.37.0,-schema-location default,-ignore-missing-schemas,-output json|junit|tap,-cache DIR |
helm template … --dry-run=server | Server-side validation | Requires cluster connectivity and the matching RBAC |
# install kubeconform v0.8.0 (Linux amd64) curl -sSL -o /tmp/kc.tgz https://github.com/yannh/kubeconform/releases/download/v0.8.0/kubeconform-linux-amd64.tar.gz tar -xzf /tmp/kc.tgz -C /tmp kubeconform && sudo install /tmp/kubeconform /usr/local/bin/ kubeconform -v cd ~/helmlab helm template myapp ./myapp -n myapp | kubeconform -strict -summary -kubernetes-version 1.37.0
v0.8.0 Summary: 12 resources found parsing stdin - Valid: 12, Invalid: 0, Errors: 0, Skipped: 0
How to verify: Both Invalid and Errors are 0. Resources = 5 myapp objects (PDB, ServiceAccount, ConfigMap, Service, Deployment) + objects from the CloudPirates redis subchart (StatefulSet, Service, headless Service, Secret, ConfigMap, etc.; use the actual 0.39.1 rendering as the reference) + two test Pods (written in the lab). Common mistakes: After enabling httpRoute, kubeconform reports could not find schema for HTTPRoute—it needs an extra CRD schema location (see the lab). Production use: In CI, add -cache /tmp/kc-cache to avoid repeated downloads; by default the schemas come from the yannh/kubernetes-json-schema (which already includes v1.37.0). Offline environments need to mirror it in advance.
Lab 7: write tests and run the gates (about 7 minutes)
{{- if .Values.tests.enabled }}
apiVersion: v1
kind: Pod
metadata:
name: "{{ include "myapp.fullname" . }}-test-http"
labels:
{{- include "myapp.labels" . | nindent 4 }}
app.kubernetes.io/component: test
annotations:
"helm.sh/hook": test
"helm.sh/hook-weight": "0"
"helm.sh/hook-delete-policy": before-hook-creation,hook-succeeded
spec:
restartPolicy: Never
automountServiceAccountToken: false
securityContext:
runAsNonRoot: true
runAsUser: 65534
seccompProfile:
type: RuntimeDefault
containers:
- name: wget
image: {{ .Values.tests.image | quote }}
command: ["sh", "-c"]
args:
- |
set -e
URL="http://{{ include "myapp.fullname" . }}:{{ .Values.service.port }}/healthz"
echo "GET $URL"
wget -q -T 5 -O - "$URL"
echo
echo "OK: myapp /healthz reachable"
securityContext:
allowPrivilegeEscalation: false
readOnlyRootFilesystem: true
capabilities:
drop: ["ALL"]
{{- end }}
{{- if and .Values.tests.enabled .Values.redis.enabled }}
apiVersion: v1
kind: Pod
metadata:
name: "{{ include "myapp.fullname" . }}-test-redis"
labels:
{{- include "myapp.labels" . | nindent 4 }}
app.kubernetes.io/component: test
annotations:
"helm.sh/hook": test
"helm.sh/hook-weight": "1"
"helm.sh/hook-delete-policy": before-hook-creation,hook-succeeded
spec:
restartPolicy: Never
automountServiceAccountToken: false
securityContext:
runAsNonRoot: true
runAsUser: 999
seccompProfile:
type: RuntimeDefault
containers:
- name: redis-cli
image: "{{ if .Values.global.imageRegistry }}{{ .Values.global.imageRegistry }}/{{ end }}{{ .Values.tests.redisImage }}"
{{- with include "myapp.redisSecretName" . }}
env:
- name: REDISCLI_AUTH # redis-cli reads the password from this environment variable, so it does not appear on the command line
valueFrom:
secretKeyRef:
name: {{ . }}
key: {{ $.Values.redisAuth.passwordKey }}
{{- end }}
command: ["sh", "-c"]
args:
- |
set -e
HOST={{ include "myapp.redisHost" . | quote }}
echo "PING $HOST"
test "$(redis-cli -h "$HOST" -p 6379 ping)" = "PONG"
echo "OK: redis replied PONG"
securityContext:
allowPrivilegeEscalation: false
readOnlyRootFilesystem: true
capabilities:
drop: ["ALL"]
{{- end }}
Test Pods must also follow PSS restricted (non-root, read-only root filesystem, all capabilities dropped), so they are not rejected in namespaces where Pod Security Admission is enabled.
cd ~/helmlab helm lint myapp --strict --kube-version 1.37.0 -f values-kind.yaml helm lint common-lib --strict
==> Linting myapp 1 chart(s) linted, 0 chart(s) failed ==> Linting common-lib [INFO] Chart.yaml: icon is recommended 1 chart(s) linted, 0 chart(s) failed
The parent chart's lint renders the CloudPirates redis templates along with it and runs schema validation; lint your own common-lib separately (INFO does not affect --strict). For third-party subcharts, avoid using --with-subcharts --strict to gate the pipeline—their warnings are not yours to fix.
helm template myapp ./myapp -n myapp -f values-kind.yaml | kubeconform -strict -summary -kubernetes-version 1.37.0
helm template myapp ./myapp -n myapp -f values-kind.yaml --set autoscaling.enabled=true --set ingress.enabled=true \
| kubeconform -strict -summary -kubernetes-version 1.37.0
# HTTPRoute is a CRD: add the Datree CRDs-catalog as a second schema source
helm template myapp ./myapp -n myapp -f values-kind.yaml --set httpRoute.enabled=true --api-versions gateway.networking.k8s.io/v1/HTTPRoute \
| kubeconform -strict -summary -kubernetes-version 1.37.0 \
-schema-location default \
-schema-location 'https://raw.githubusercontent.com/datreeio/CRDs-catalog/main/{{.Group}}/{{.ResourceKind}}_{{.ResourceAPIVersion}}.json'
Summary: 11 resources found parsing stdin - Valid: 11, Invalid: 0, Errors: 0, Skipped: 0 Summary: 13 resources found parsing stdin - Valid: 13, Invalid: 0, Errors: 0, Skipped: 0 Summary: 12 resources found parsing stdin - Valid: 12, Invalid: 0, Errors: 0, Skipped: 0
The key point is that Invalid and Errors are both 0. The third -schema-location in {{.Group}} etc. are kubeconform's own Go template variables; single quotes stop the shell from processing them. Schema versions in CRDs-catalog may differ from the Gateway API version actually installed in your cluster, so use your cluster as the reference.
helm template myapp ./myapp --set-json 'resources={"request":{"cpu":"100m"}}' -s templates/deployment.yaml \
| kubeconform -strict -summary -kubernetes-version 1.37.0
helm lint myapp --set-json 'resources={"request":{"cpu":"100m"}}' --quiet; echo "lint exit=$?"
stdin - Deployment myapp is invalid: problem validating schema. Check JSON formatting: jsonschema validation failed … - at '/spec/template/spec/containers/0/resources': additional properties 'request' not allowed Summary: 1 resource found parsing stdin - Valid: 0, Invalid: 1, Errors: 0, Skipped: 0 lint exit=0
request (missing an s) is valid YAML, and in myapp's schema resources it is only declared as an object, so lint reports no error; kubeconform's -strict Kubernetes schema rejects unknown fields. You can also refine, in the myapp schema, the resources structure so the lint stage catches it.
helm upgrade --install myapp ./myapp -n myapp -f values-kind.yaml --wait --timeout 5m helm test myapp -n myapp --logs
NAME: myapp LAST DEPLOYED: Sun Nov 15 11:05:42 2026 NAMESPACE: myapp STATUS: deployed REVISION: 9 TEST SUITE: myapp-test-http Last Started: Sun Nov 15 11:06:10 2026 Last Completed: Sun Nov 15 11:06:13 2026 Phase: Succeeded TEST SUITE: myapp-test-redis Last Started: Sun Nov 15 11:06:13 2026 Last Completed: Sun Nov 15 11:06:16 2026 Phase: Succeeded POD LOGS: myapp-test-http (wget) GET http://myapp:80/healthz ok OK: myapp /healthz reachable POD LOGS: myapp-test-redis (redis-cli) PING myapp-redis OK: redis replied PONG
/healthz The response body depends on your myapp implementation. On success, the test Pod is hook-succeeded removed: kubectl -n myapp get pod -l app.kubernetes.io/component=test should be empty.
kubectl -n myapp scale sts myapp-redis --replicas=0 helm test myapp -n myapp --filter name=myapp-test-redis --timeout 1m; echo "exit=$?" kubectl -n myapp logs myapp-test-redis kubectl -n myapp scale sts myapp-redis --replicas=1
... Phase: Failed Error: warning: Hook test myapp/templates/tests/test-redis.yaml failed: … (the exact cause depends on the output of Helm 4's kstatus waiter) exit=1 PING myapp-redis Could not connect to Redis at myapp-redis:6379: Connection refused
The failed Pod is kept (without a hook-failed policy), so you can check the logs; on the next run before-hook-creation will delete it first. Deleting directly with kubectl scale is drift; the next helm upgrade restores it.
Case 1: lint is all green, but the production install fails
Problem: The HPA in the chart was written as autoscaling/v2beta2, and lint was not given --kube-version, so with the default Capabilities it reports no deprecation; the production cluster on 1.37 has already removed this API. Approach: Add to lint --kube-version 1.37.0, and add kubeconform in CI (the 1.37 schema has no v2beta2, so it reports could not find schema). Limitations: kubeconform errors by default on resources whose schema cannot be found; only after confirming, use -ignore-missing-schemas for CRDs.
Case 2: all helm tests fail after PSA restricted is enabled on the namespace
Problem: The scaffold test Pod has no securityContext and is rejected by Pod Security Admission: violates PodSecurity "restricted:latest". Approach: Set test Pods to non-root, seccomp, and drop ALL, the same as business Pods. Limitations: Some test images need root (for example, to install tools); switch to images that already include the tools.
Case 3: test Pods keep piling up
Problem: The tests have no deletion policy, so every helm test run fails with pods "myapp-test-http" already exists, and operators delete them by hand. Approach: Add before-hook-creation. Limitations: uninstall makes Helm clean up the release's hook resources, but old Pods left behind by manual renaming must be deleted by hand.
Common errors and fixes
[WARNING] templates/deployment.yaml: document starts with an illegal indent: " apiVersion: apps/v1", which may cause parsing problems
Cause: The template's first line is indented (common when {{ if }} is used without {{- or copy-pasting). --strict fails under it.
Fix: Start the document at column 0; use {{-.
[ERROR] templates/deployment.yaml: a Deployment must contain matchLabels or matchExpressions, and "myapp" does not
Cause: The selector helper outputs nothing (for example, include references a value that does not exist, or indentation pushed it somewhere else).
helm template myapp ./myapp -s templates/deployment.yaml | yq '.spec.selector'
Error: pods "myapp-test-http" already exists
Cause: The previous test Pod was not cleaned up.
Fix: Add helm.sh/hook-delete-policy: before-hook-creation; as a temporary measure, delete it with kubectl delete pod myapp-test-http -n myapp.
stdin - HTTPRoute myapp failed validation: could not find schema for HTTPRoute
Cause: kubeconform's default schema only includes built-in resources.
Fix: Add the schema location from CRDs-catalog -schema-location, or use Datree's CRD Extractor to export the schema from the cluster; after confirming, consider -ignore-missing-schemas.
helm test keeps waiting until timed out waiting for the condition
Cause: The test Pod is stuck in Pending/ImagePullBackOff, or the command itself hangs (wget/curl without a timeout).
kubectl -n myapp get pod -l app.kubernetes.io/component=test kubectl -n myapp describe pod myapp-test-http | tail -15
Fix: Set a timeout on every test command (wget -T 5), push test images to an accessible repository in advance, and set a reasonable --timeout.
1. Render the chart with the prod values (excluding test Pods), validate strictly against Kubernetes 1.37.0, and output a JUnit report.
helm template myapp ./myapp -f environments/prod.yaml --skip-tests \ | kubeconform -strict -kubernetes-version 1.37.0 -output junit > kubeconform.xml
2. Run only the test named myapp-test-http and print its logs.
helm test myapp -n myapp --filter name=myapp-test-http --logs
Your chart has 4 common values combinations (default, HPA, Ingress, external Redis). Design a CI job that finds as many problems as possible within 3 minutes, and explain the value of each step.
① helm dependency build (from the lock file, reproducible); ② for each ci/*-values.yaml: helm lint --strict --with-subcharts --kube-version 1.37.0 -f $f (Chart.yaml, schema, template errors); ③ the same combination with helm template -f $f | kubeconform -strict -kubernetes-version 1.37.0 -cache .kc (field names and types); ④ optionally, compare the previous version's helm template output and generate a diff comment; ⑤ install the default combination in kind, and helm test --logs (real connectivity). The first three steps need no cluster and finish in seconds; step ⑤ is the most expensive, so put it last and run only one combination. Hand the remaining combinations to a nightly job or to Lesson 6's chart-testing.
Verified instructional videos
No verified video specifically covering helm test and kubeconform was found.
Official docs
Video storyboard (about 90 seconds)
Visual: three gates in sequence: lint, kubeconform, helm test, with cost labels from low to high below.
Narration: run the cheaper checks earlier.
Visual: the misspelled field request passes through the lint gate and is stopped by kubeconform's strict mode.
Narration: lint does not understand Kubernetes fields; kubeconform validates the rendered output against the official schema.
Visual: helm test creates two test Pods, one wgets the service and one pings Redis; the result is a green check mark.
Narration: tests are hooks too; they are created only when helm test runs, and exit code zero means pass.
Visual: Redis is scaled to zero; the test Pod turns red and is kept, and the logs show the connection was refused.
Narration: a failed test Pod is kept for investigation and cleaned up automatically before the next run.
Module 8 · Chart readiness review and common errors
- Review a chart against seven checklist categories (metadata / values and schema / templates / security / reliability / operability / testing), and give actionable change recommendations.
- Use the error text to determine which stage it occurred in, and locate it with the matching command:
nil pointer evaluating,error converting YAML to JSON,field is immutable,invalid ownership metadata,no matches for kind, and subchart values having no effect. - Know the correct recovery for immutable selector problems (orphan delete, then upgrade), and in Helm 4
--force-replace(formerly--force) has a cost.
What: production-grade chart review checklist
| Category | Check items | Covered in |
|---|---|---|
| Metadata | apiVersion v2; version is strict SemVer and increments with each change; appVersion is quoted; kubeVersion includes -0; maintainers, sources, icon; dependency versions use ranges and a Chart.lock exists | M1, M6 |
| Values and schema | camelCase, every key has a comment; optional resources have enabled; no environment-specific defaults; values.schema.json explicitly declares $schema, key field types, required fields and enums, top level additionalProperties: false (including global and subchart names) | M4, M5 |
| Templates | helpers have a chart prefix; names are truncated to 63; selectors use only selectorLabels; include rather than template; use toYaml | nindent; string values quote; do not use randAlphaNum/now; no hard-coded namespace or resource names | M2, M3 |
| Security | runAsNonRoot, readOnlyRootFilesystem, drop ALL, seccomp RuntimeDefault; automountServiceAccountToken: false (when not needed); Secrets are not written into values defaults, and support existingSecret; image support for digest pinning | M4 |
| Reliability | three probe types; requests (at least CPU/memory); do not render replicas when using HPA; a PDB that does not block drain; topology spread; config checksum to trigger rollouts; graceful termination period | M4 |
| Operability | NOTES.txt gives access and test instructions; recommended labels app.kubernetes.io/*; README and values comments can generate docs; resources can be helm get manifest easily understood by | M1, M3 |
| Testing | helm lint --strict --with-subcharts; for multiple values sets kubeconform -strict; helm test covers service and dependency connectivity, and test Pods comply with PSS and have a deletion policy | M7 |
Why: troubleshooting by “failure stage” is the fastest
Installs fail in the same way, but the cause may be at any step in the Helm client, or in the API Server or the runtime. Error text usually includes stage-specific keywords, so determine the stage first, then choose the tool:
| Stage | Characteristic errors | First tool |
|---|---|---|
| ① Load / parse | parse error at (…),function "x" not defined,unexpected EOF, Chart.yaml validation: | helm lint |
| ② Schema validation | values don't meet the specifications of the schema(s) | Check against values.schema.json |
| ③ Template execution | execution error at (…),nil pointer evaluating interface {}.x,can't evaluate field X in type Y,wrong type for value,error calling include | helm template -s … --debug |
| ④ YAML → JSON | YAML parse error on …: error converting YAML to JSON: yaml: line N: … (did not find expected key / mapping values are not allowed / found character that cannot start any token) | helm template --debug check the original text and count to line N |
| ⑤ Build objects / API validation | resource mapping not found … no matches for kind,is invalid: spec…,unknown field | kubeconform,--dry-run=server,kubectl api-resources |
| ⑥ Apply to cluster | field is immutable,invalid ownership metadata, SSA conflict | kubectl get -o yaml,helm get manifest |
| ⑦ Runtime | --wait Timeouts, CrashLoopBackOff, helm test failures | kubectl describe/logs,helm test --logs |
How: root causes of five common problems
1. nil pointer evaluating interface {}.caSecret
Accessing .Values.externalRedis.tls.caSecret when tls does not exist (there is no tls level under externalRedis in values.yaml), so the Go template hits a nil pointer when it reads a field from nil. Fix: provide a full default structure in values.yaml, or use dig "tls" "caSecret" "" .Values.externalRedis; or {{ with .Values.externalRedis.tls }}{{ .caSecret }}{{ end }}. Note that dig only works on dictionaries (map[string]interface{}).
2. YAML indentation and error converting YAML to JSON
After Helm renders the text, it splits the documents by --- and parses the YAML. The line number in the error is the line number in the rendered document, not the line number in the template file. Common causes: nindent a number that does not match its context,{{- a swallowed line break, a tab in the template, or a colon in a value without quotes.
3. spec.selector: field is immutable
In Deployment/StatefulSet/DaemonSet, the spec.selector is immutable after creation (a Job’s selector is also immutable). If you change a helper so that the selectorLabels output changes (for example adding a version, changing nameOverride, or changing the chart name), the upgrade fails. Recovery: ① first, revert the selector; ② if you must change it, use kubectl delete deploy myapp --cascade=orphan (Pods are kept), then upgrade to create a new Deployment. After the new ReplicaSet takes over, clean up the old Pods manually; ③ Helm 4’s --force-replace (Helm 3 calls it --force), which deletes and recreates the resource; causes downtime, so use it only in non-production.
4. invalid ownership metadata
The resource to be created already exists but does not belong to the current release (missing app.kubernetes.io/managed-by: Helm label and meta.helm.sh/release-name/release-namespace annotations, or it belongs to another release). Common when resources are first created manually with kubectl apply and then switched to Helm, or when two releases render resources with the same name. Fix: after confirming there is no conflict, add the labels and annotations to claim the resource, or rename it.
5. Subchart values have no effect
Four causes, ordered by likelihood: the key is not under the subchart name (or alias); the subchart template does not read the key; you changed the dependency version or a file:// dependency without re-running dependency update; a condition turned the subchart off. Use helm get values -a,helm template -s charts/…,tar -tzf charts/*.tgz to pinpoint it.
When: when to use --debug
helm template --debug: still prints the partially rendered output if rendering fails, and shows the raw text at fault for YAML errors.helm install/upgrade --debug: prints more detailed logs (Helm 4 uses structured logging via slog).
Comparison with similar tools
| Problem | Helm | kubectl apply |
|---|---|---|
| Immutable selector | upgrade fails; release marked failed | apply fails |
| Resource ownership | Labels + annotations; conflicts are rejected | No ownership concept (SSA has field managers) |
| Template errors | Caught on the client before sending | No templates |
--force-replace --force-replace can fix selector problems without loss”: it deletes and recreates resources, causing downtime. ③ “A nil pointer means a value is an empty string”: an empty string does not cause a nil pointer; the cause is an intermediate dictionary that does not exist. ④ “Problems in a subchart should be fixed by editing the subchart’s values.yaml”: usually you should override them in the parent chart’s redis: section.Which step does the error occur at?
Immutable selector: recovery paths
Interactive 1: Chart readiness review scorecard
Check items one by one against your myapp chart (results are saved in this browser). Each category has a weight, with a maximum score of 100. Below 80 points, priority fixes are suggested.
Interactive 2: error stage identifier
Paste a Helm error. The identifier uses keywords to determine the stage and suggests the first command to run (the rules come from the table on the Principles page).
Troubleshooting commands at a glance
| Command | Used for stage | Description |
|---|---|---|
helm lint DIR --strict --with-subcharts | ①②③④ | Fastest full check |
helm template REL DIR -s templates/x.yaml --debug | ③④ | Shows only the failing template; still prints rendered text on failure |
helm template … --debug 2>&1 | awk '/# Source: myapp\/templates\/x.yaml/,/^---/' | cat -n | ④ | Add line numbers to the rendered document and compare them with the error line |
helm template … --dry-run=server | ⑤ | API Server validation |
kubectl api-resources | grep -i httproute | ⑤ | Check whether the CRD is installed |
kubectl get deploy X -o jsonpath='{.spec.selector}' | ⑥ | Compare the cluster state with the rendered result |
kubectl get X -o jsonpath='{.metadata.labels.app\.kubernetes\.io/managed-by} {.metadata.annotations.meta\.helm\.sh/release-name}' | ⑥ | Check resource ownership |
helm get manifest|values -a|notes REL | ⑥⑦ | View the manifest and values the release actually uses |
helm history REL / helm status REL | ⑥⑦ | Failed revisions and descriptions |
cd ~/helmlab helm get values myapp -n myapp -a | yq '.redis' helm history myapp -n myapp --max 5
enabled: true
global:
imageRegistry: ""
resources:
limits:
memory: 128Mi
requests:
cpu: 50m
memory: 64Mi
REVISION UPDATED STATUS CHART APP VERSION DESCRIPTION
5 Sun Nov 15 10:31:02 2026 superseded myapp-0.2.0 1.1 Upgrade complete
6 Sun Nov 15 10:48:40 2026 superseded myapp-0.2.0 1.1 Upgrade complete
7 Sun Nov 15 11:02:11 2026 failed myapp-0.2.0 1.1 Upgrade "myapp" failed: …
8 Sun Nov 15 11:03:30 2026 superseded myapp-0.2.0 1.1 Upgrade complete
9 Sun Nov 15 11:05:42 2026 deployed myapp-0.2.0 1.1 Upgrade complete
How to verify:-a Shows the redis section. It is the values the subchart receives (plus the subchart’s own defaults). Common mistakes: Without -a you only see the user-supplied values and wrongly think the defaults were lost. Production use: Use helm get manifest REL --revision N to compare manifests before and after the failure.
Lab 8: fault injection and repair (about 8 minutes)
Inject faults in a copy of the directory; the real chart is not affected. For each fault, first predict the error stage, then run the command to verify.
rm -rf /tmp/bug && cp -r ~/helmlab/myapp /tmp/bug && cd /tmp/bug sed -i 's|file://../common-lib|file://'"$HOME"'/helmlab/common-lib|' Chart.yaml
Because the copy moved, change the relative file:// path of common-lib to an absolute path (the .tgz files in charts/ are already there, so rendering is not affected; this only makes dependency the commands work too). OCI dependencies are not affected by location.
sed -i '/name: REDIS_PORT/i\ - name: REDIS_TLS_CA_SECRET\n value: {{ .Values.externalRedis.tls.caSecret | quote }}' templates/deployment.yaml
helm template t . 2>&1 | tail -1
Error: template: myapp/templates/deployment.yaml:58:42: executing "myapp/templates/deployment.yaml" at <.Values.externalRedis.tls.caSecret>: nil pointer evaluating interface {}.caSecret
Fix: {{ dig "tls" "caSecret" "" .Values.externalRedis | quote }}, or in values.yaml under externalRedis: add tls: {caSecret: ""} (and declare it in the myapp schema as externalRedis.tls).
sed -i 's|{{ .Values.externalRedis.tls.caSecret \| quote }}|{{ dig "tls" "caSecret" "" .Values.externalRedis \| quote }}|' templates/deployment.yaml
helm template t . -s templates/deployment.yaml | grep -A1 REDIS_TLS_CA_SECRET
- name: REDIS_TLS_CA_SECRET
value: ""sed -i 's/{{- toYaml . | nindent 12 }}/{{- toYaml . | nindent 10 }}/' templates/deployment.yaml # affects multiple blocks at once
helm template t . 2>&1 | tail -1
helm template t . -s templates/deployment.yaml --debug 2>/dev/null | cat -n | sed -n '50,60p'
Error: YAML parse error on myapp/templates/deployment.yaml: error converting YAML to JSON: yaml: line 45: did not find expected key
50 securityContext:
51 allowPrivilegeEscalation: false
52 capabilities:
53 drop:
54 - ALL
55 readOnlyRootFilesystem: true
56 ports:
...
’s child fields are now at the same level as it. Fix: sed -i 's/nindent 10 }}/nindent 12 }}/' templates/deployment.yaml. The line number points to in the rendered document. Use --debug + cat -n to compare.
sed -i 's/^ revisionHistoryLimit:/\trevisionHistoryLimit:/' templates/deployment.yaml helm template t . 2>&1 | tail -1 sed -i 's/^\trevisionHistoryLimit:/ revisionHistoryLimit:/' templates/deployment.yaml
Error: YAML parse error on myapp/templates/deployment.yaml: error converting YAML to JSON: yaml: line 13: found character that cannot start any token
sel-demo, delete it when done):
cd ~/helmlab helm install sel-demo ./myapp -n myapp --set redis.enabled=false --set externalRedis.host=myapp-redis \ --set redisAuth.existingSecret=myapp-redis-auth \ --set replicaCount=1 --set podDisruptionBudget.enabled=false --wait # Simulate “someone changed nameOverride”: app.kubernetes.io/name in selectorLabels changes with it helm upgrade sel-demo ./myapp -n myapp --reuse-values --set nameOverride=myapp-v2 --set fullnameOverride=sel-demo-myapp 2>&1 | tail -2
Error: UPGRADE FAILED: failed to replace object: Deployment.apps "sel-demo-myapp" is invalid: spec.selector: Invalid value: {"matchLabels":{"app.kubernetes.io/instance":"sel-demo","app.kubernetes.io/name":"myapp-v2"}}: field is immutable
# Recovery option A (preferred): revert nameOverride helm upgrade sel-demo ./myapp -n myapp --reuse-values --set nameOverride= --wait # Recovery option B (when a new selector is really needed): orphan delete, then upgrade kubectl -n myapp delete deploy sel-demo-myapp --cascade=orphan helm upgrade sel-demo ./myapp -n myapp --reuse-values --set nameOverride=myapp-v2 --wait kubectl -n myapp get rs -l app.kubernetes.io/instance=sel-demo # After the new Pod is Ready, delete the old ReplicaSet (its labels still have the old name) kubectl -n myapp delete rs -l app.kubernetes.io/instance=sel-demo,app.kubernetes.io/name=myapp helm uninstall sel-demo -n myapp
fullnameOverride keeps the resource name unchanged, which is needed to demonstrate “the selector of a same-named resource gets modified”. If the resource name also changes, Helm creates a new Deployment and deletes the old one (no immutable error, but one replacement happens).
cd /tmp/bug # Wrong: Redis disk size set at the top level (myapp’s schema rejects unknown keys) helm template t . --set persistence.size=2Gi 2>&1 | tail -1 # Correct: under the redis: section (the subchart name) helm template t . --set redis.persistence.size=2Gi -s charts/redis/templates/statefulset.yaml | grep 'storage:' # Changed the dependency version in Chart.yaml but did not run dependency update sed -i 's/version: "0.39.1"/version: "0.39.6"/' Chart.yaml helm dependency list . | grep '^redis' helm template t . | grep -m1 'helm.sh/chart: redis' sed -i 's/version: "0.39.6"/version: "0.39.1"/' Chart.yaml
- at '': additional properties 'persistence' not allowed
storage: "2Gi"
redis 0.39.6 oci://registry-1.docker.io/cloudpirates wrong version
helm.sh/chart: redis-0.39.1
Item 1: without a schema, this value is silently ignored and Redis keeps its default size. This is the most common cause of “not taking effect”. Items 3 and 4: when rendering, Helm only checks that the dependency name exists under charts/, and a version mismatch still uses the old .tgz snapshot (the source CheckDependencies compares names). Only helm dependency list shows wrong version,helm dependency build reports that Chart.lock is out of sync. storage line quoting follows the chart template. In addition, StatefulSet volumeClaimTemplates are immutable, and existing PVCs do not grow just because the size was changed.
Case 1: renaming the chart causes a full selector conflict
Problem: The team renamed the chart from web to frontend, so every release hit an immutable selector error on upgrade (the app.kubernetes.io/name value comes from the chart name). Approach: Set nameOverride: web in the new chart to keep the selector unchanged, then plan a one-time migration. Limitations: nameOverride also affects how resource names are computed, so use helm template to diff before and after and confirm that both resource names and selectors are unchanged.
Case 2: migrating from kubectl to Helm fails with invalid ownership metadata
Problem: The existing Deployment was created with kubectl, and Helm helm install reports exists and cannot be imported into the current release. Approach: After confirming the resource matches the chart rendering, add the app.kubernetes.io/managed-by=Helm labels and meta.helm.sh/release-name,meta.helm.sh/release-namespace annotations so that Helm claims it. Limitations: After claiming, the next upgrade overwrites the resource according to the chart, so diff in advance.
Case 3: nil pointer late at night, only in prod
Problem: An optional block was removed entirely from the prod values. The template accesses its child fields directly, so only the prod rendering fails. Approach: CI runs lint and template against every environment’s values. In templates, guard optional blocks consistently with with or dig. Limitations: Declaring the block as required in the schema fails earlier, but this must match the intent of making it optional.
Interactive troubleshooting tree: Helm chart errors
Start from the symptom and narrow the scope step by step. Each leaf node gives a diagnostic command and a fix.
Quick reference: common errors
nil pointer evaluating interface {}.caSecret
An intermediate dictionary does not exist. Use dig/with, or provide a full default structure in values.yaml.
error converting YAML to JSON: yaml: line N: did not find expected key
Indentation or whitespace control problem. helm template -s template --debug | cat -n, and compare with line N of the rendered output.
spec.selector: Invalid value: …: field is immutable
selectorLabels output changed. Revert it; if it must change, orphan delete and then upgrade.
Unable to continue with install: Deployment "myapp" in namespace "myapp" exists and cannot be imported into the current release: invalid ownership metadata
Resource ownership conflict. Check whether another release owns it or kubectl created it. After confirming, add the labels and annotations, or rename.
resource mapping not found for name: "myapp" namespace: "" from "": no matches for kind "HTTPRoute" in version "gateway.networking.k8s.io/v1" — ensure CRDs are installed first
The cluster does not have this CRD. Install the Gateway API CRD, or turn off httpRoute.enabled; in the chart, use .Capabilities.APIVersions.Has to report the error early.
1. The error says there is a YAML error on line 45 of deployment.yaml after rendering. Give a command to view the context of that line.
helm template myapp ./myapp -s templates/deployment.yaml --debug 2>/dev/null | cat -n | sed -n '40,50p'
Note --debug The output contains --- and # Source lines. YAML line numbers count from the first line of the document (after # Source ), so watch for a 1–2 line offset when comparing.
2. Make Helm claim a ConfigMap that was created with kubectl myapp (release myapp, namespace myapp).
kubectl -n myapp label configmap myapp app.kubernetes.io/managed-by=Helm --overwrite kubectl -n myapp annotate configmap myapp meta.helm.sh/release-name=myapp meta.helm.sh/release-namespace=myapp --overwrite
When reviewing a colleague’s chart, you find that the selector uses myapp.labels; values contain password: changeme; the Deployment writes replicas whether or not HPA is enabled; there is no schema; the test Pod runs as root. Give your review comments in priority order.
P0 (causes outages or security incidents): ① change the selector to myapp.selectorLabels—otherwise the next chart upgrade will hit an immutable selector. If it is already live, plan an orphan migration. ② Remove the default password and change it to existingSecret or require the user to supply it (schema + required). Do not put passwords into values defaults or Git. P1: ③ Do not render replicas when HPA is enabled. ④ Add values.schema.json (types, required, additionalProperties). P2: ⑤ Make the test Pod comply with PSS restricted and add a deletion policy. Attach a change example and a verification command to each item (lint --strict, kubeconform, helm test).
Verified teaching videos
No verified video specifically covering Helm template error troubleshooting was found. Use this module’s troubleshooting tree and the storyboard below.
Official documentation
- Debugging Templates
- Helm Troubleshooting FAQ
- Chart Best Practices Guide
- Deployment: Label selector updates
Video storyboard script (about 100 seconds)
Visual: a pipeline of seven cells, from parse to run. Red error text flies in and lands on the “Execute” cell.
Narration: first determine which stage the error belongs to. Client-side problems can all be reproduced offline.
Visual: in the path .Values.externalRedis.tls.caSecret, the tls node is drawn as a dashed line (it does not exist). A dot drops off the dashed line and a nil pointer appears.
Narration: a nil pointer does not mean the value is empty. It means an intermediate dictionary does not exist. Protect it with dig or with.
Visual: rendered YAML with line numbers. Line 45 is indented two spaces short, and an arrow points to nindent 10.
Narration: the line number in a YAML error belongs to the rendered output. Use debug with line numbers to compare.
Visual: the Deployment’s selector has a lock on it. Orphan delete leaves the Pods in place, and the new Deployment takes over.
Narration: the selector is immutable, so prefer reverting it. When you must change it, use orphan delete, then upgrade.
Cheat sheet
helm create myapp # scaffold (includes httproute.yaml) helm show chart|values|readme|crds ./myapp helm package ./myapp -d dist/ [--version X --app-version Y] [-u] tar -tzf dist/myapp-0.2.0.tgz # check the effect of .helmignore
helm template REL ./myapp -n NS [-f v.yaml] [--set k=v] helm template … -s templates/deployment.yaml --debug helm template … --kube-version 1.37.0 --api-versions gateway.networking.k8s.io/v1/HTTPRoute helm template … --is-upgrade # .Release.IsUpgrade=true helm template … --dry-run=server # lookup returns values + API validation helm template … --skip-tests --include-crds --output-dir out/
helm dependency list ./myapp helm dependency update ./myapp # resolve ranges → rewrite Chart.lock helm dependency build ./myapp # strictly follow Chart.lock (CI) helm template … -s charts/redis/templates/service.yaml
helm lint ./myapp --strict --with-subcharts --kube-version 1.37.0 [-f env.yaml] helm template REL ./myapp | kubeconform -strict -summary -kubernetes-version 1.37.0 helm upgrade --install REL ./myapp -n NS --wait --timeout 3m helm test REL -n NS --logs [--filter name=X] [--timeout 2m]
helm get values REL -a | manifest | notes [--revision N]
helm history REL
helm template … --debug 2>/dev/null | cat -n | sed -n '40,50p'
kubectl get deploy X -o jsonpath='{.spec.selector}'
kubectl delete deploy X --cascade=orphan # when the selector must change--dry-runValuenone|client|server;helm templatedefault clienthelm template --validatenow deprecated →--dry-run=server--force→--force-replace;--atomic→--rollback-on-failure- schema validation library jsonschema/v6: draft-04/06/07/2019-09/2020-12
- Chart API v3 requires
HELM_EXPERIMENTAL_CHART_V3, use v2 in production
Template snippets
| Need | Syntax |
|---|---|
| Output nested object | {{- with .Values.resources }} resources: {{- toYaml . | nindent 12 }} {{- end }} |
| tag defaults to AppVersion | {{ .Values.image.tag | default .Chart.AppVersion }} |
| Required | {{ required "x is required" .Values.x }} (does not fail in lint mode, so also write it in the schema) |
| String value | {{ .Values.x | quote }} |
| Allow template in value | {{ tpl .Values.greeting . }} |
| Safely get a deep value | {{ dig "tls" "caSecret" "" .Values.externalRedis }} |
| Access root in range | {{ $.Release.Name }},{{ include "myapp.fullname" $ }} |
| Helper with multiple arguments | {{ include "x" (dict "root" $ "item" .) }} |
| Name truncation | {{ printf "%s-%s" .Release.Name "x" | trunc 63 | trimSuffix "-" }} |
| Roll on config change | checksum/config: {{ include (print $.Template.BasePath "/configmap.yaml") . | sha256sum }} |
| HPA mutual exclusion | {{- if not .Values.autoscaling.enabled }} replicas: … {{- end }} |
| Render by API | {{- if .Capabilities.APIVersions.Has "gateway.networking.k8s.io/v1/HTTPRoute" }} |
| Invalid combination | {{- fail "message" }} |
| Reuse existing values | {{- $s := lookup "v1" "Secret" .Release.Namespace "n" }} (empty offline) |
| test hook | "helm.sh/hook": test + "helm.sh/hook-delete-policy": before-hook-creation,hook-succeeded |
Error → stage → action
| Error keyword | Stage | Action |
|---|---|---|
parse error / function "x" not defined | Parse | Check syntax and function name casing |
values don't meet the specifications | schema | Fix values or schema by JSON pointer |
nil pointer evaluating | Execute | dig/with/ add default structure |
can't evaluate field X in type Y | Execute | Scope: switch to $ |
error converting YAML to JSON | YAML | --debug | cat -n Check indentation / tabs |
no matches for kind | API | Install CRD / Capabilities check |
field is immutable | Apply | Revert selector or orphan delete |
invalid ownership metadata | Apply | Add labels and annotations, or rename |
Comprehensive lab + final quiz
myapp-0.3.0 (Lesson 3 pushes this version to ACR): run it in the kind cluster lab in the myapp namespace. Redis comes from the CloudPirates redis 0.39.1 subchart, and the password comes from an existing Secret (redis.auth.existingSecret and redisAuth.existingSecret). It can also switch to an external Redis, enable HPA, and enable ingress. All bad configurations must be caught in the CI stage. If you completed the labs module by module, most of the work is already done. This lab fills the gaps and provides acceptance evidence.cd ~/helmlab && ls helm dependency list myapp ls myapp/templates myapp/templates/tests test -f myapp/values.schema.json && echo "schema OK"
common-lib myapp myapp-lesson1 myapp-src values-ext-redis.yaml values-kind.yaml values-lab.yaml … NAME VERSION REPOSITORY STATUS redis 0.39.1 oci://registry-1.docker.io/cloudpirates ok common-lib 0.1.0 file://../common-lib ok NOTES.txt _helpers.tpl configmap.yaml deployment.yaml hpa.yaml httproute.yaml ingress.yaml pdb.yaml service.yaml serviceaccount.yaml tests test-connection.yaml test-redis.yaml schema OK
If any part is missing, go back to the Lab page of the matching module and complete it (Module 4: values/deployment/pdb; Module 5: schema; Module 6: dependencies; Module 7: tests).
version to 0.3.0, and update the changes annotation.
sed -i 's/^version: .*/version: 0.3.0/' myapp/Chart.yaml helm show chart ./myapp | grep -E '^(version|appVersion|kubeVersion)'
appVersion: "1.1" kubeVersion: '>=1.33.0-0' version: 0.3.0
mkdir -p myapp/ci
cat > myapp/ci/default-values.yaml <<'EOF'
{}
EOF
cat > myapp/ci/hpa-ingress-values.yaml <<'EOF'
autoscaling:
enabled: true
ingress:
enabled: true
className: nginx
EOF
cat > myapp/ci/external-redis-values.yaml <<'EOF'
redis:
enabled: false
externalRedis:
host: redis.prod.internal
redisAuth:
existingSecret: prod-redis
EOF
cat > myapp/ci/existing-secret-values.yaml <<'EOF'
redis:
auth:
existingSecret: myapp-redis-auth
redisAuth:
existingSecret: myapp-redis-auth
EOF
cat > myapp/ci/bad-values.yaml <<'EOF'
replicas: 3
image:
pullPolicy: always
EOF
ci/ is already excluded in .helmignore and will not enter the release package. bad-values.yaml Used to prove that the schema rejects bad input.
for f in myapp/ci/*-values.yaml; do echo "== $f"; helm lint myapp --strict --kube-version 1.37.0 -f "$f" --quiet && echo PASS || echo FAIL done
== myapp/ci/bad-values.yaml [ERROR] values.yaml: - at '': additional properties 'replicas' not allowed - at '/image/pullPolicy': value must be one of 'Always', 'IfNotPresent', 'Never' … FAIL == myapp/ci/default-values.yaml PASS == myapp/ci/existing-secret-values.yaml PASS == myapp/ci/external-redis-values.yaml PASS == myapp/ci/hpa-ingress-values.yaml PASS
for f in myapp/ci/{default,existing-secret,hpa-ingress,external-redis}-values.yaml; do
echo "== $f"
helm template myapp ./myapp -n myapp -f "$f" | kubeconform -strict -summary -kubernetes-version 1.37.0
done
== myapp/ci/default-values.yaml Summary: 12 resources found parsing stdin - Valid: 12, Invalid: 0, Errors: 0, Skipped: 0 == myapp/ci/existing-secret-values.yaml Summary: 11 resources found parsing stdin - Valid: 11, Invalid: 0, Errors: 0, Skipped: 0 == myapp/ci/hpa-ingress-values.yaml Summary: 14 resources found parsing stdin - Valid: 14, Invalid: 0, Errors: 0, Skipped: 0 == myapp/ci/external-redis-values.yaml Summary: 6 resources found parsing stdin - Valid: 6, Invalid: 0, Errors: 0, Skipped: 0
The existing-secret combination has one fewer object than the default (the subchart no longer generates a Secret). The external Redis combination has no redis subchart objects and no redis test Pod (template condition and .Values.tests.enabled .Values.redis.enabled), leaving the 5 myapp objects plus the HTTP test Pod.
T="helm template myapp ./myapp -n myapp" $T -s templates/deployment.yaml | yq '.spec.selector' $T --set autoscaling.enabled=true -s templates/deployment.yaml | grep -c 'replicas:' $T -s templates/deployment.yaml | yq '.spec.template.spec.containers[0].securityContext' $T -s templates/deployment.yaml | yq '.spec.template.spec.containers[0].image' $T --set image.tag=1.0 -s templates/deployment.yaml | yq '.spec.template.spec.containers[0].image'
matchLabels:
app.kubernetes.io/name: myapp
app.kubernetes.io/instance: myapp
0
allowPrivilegeEscalation: false
capabilities:
drop:
- ALL
readOnlyRootFilesystem: true
myapp:1.1
myapp:1.0helm upgrade --install myapp ./myapp -n myapp -f values-kind.yaml --wait --timeout 5m kubectl -n myapp get sts,deploy,svc,pdb -l app.kubernetes.io/instance=myapp helm test myapp -n myapp --logs | grep -E 'TEST SUITE|Phase|OK:' kubectl -n myapp port-forward svc/myapp 8080:80 & sleep 2; curl -s http://127.0.0.1:8080/healthz; kill %1
NAME READY AGE statefulset.apps/myapp-redis 1/1 1h NAME READY UP-TO-DATE AVAILABLE AGE deployment.apps/myapp 2/2 2 2 2d NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE service/myapp ClusterIP 10.96.31.7 <none> 80/TCP 2d service/myapp-redis ClusterIP 10.96.188.42 <none> 6379/TCP 1h service/myapp-redis-headless ClusterIP None <none> 6379/TCP 1h NAME MIN AVAILABLE MAX UNAVAILABLE ALLOWED DISRUPTIONS AGE poddisruptionbudget.policy/myapp 1 N/A 1 1h TEST SUITE: myapp-test-http Phase: Succeeded TEST SUITE: myapp-test-redis Phase: Succeeded OK: myapp /healthz reachable OK: redis replied PONG ok
helm package myapp -d dist/ tar -tzf dist/myapp-0.3.0.tgz | grep -E 'ci/|Chart.lock|charts/|values.schema.json'
Successfully packaged chart and saved it to: dist/myapp-0.3.0.tgz myapp/Chart.lock myapp/values.schema.json myapp/charts/common-lib-0.1.0.tgz myapp/charts/redis-0.39.1.tgz
The package does not contain ci/. Pushing to an OCI repository and signing are covered in Lessons 3 and 6.
Acceptance checklist
Open-ended self-check (6 questions)
1. include and template : what is the fundamental difference? Why should a chart always use include?
template is a Go template action: its output is written straight into the result and cannot be piped. include is a Helm function that returns a string, so it can be used in pipelines such as | nindent,| sha256sum. Indentation can only be decided at the call site, so include lets the same helper be reused at different levels.
2. In range , why does .Release.Name give an error? In a named template, what does $ point to?
Inside range, . is rebound to the current element; use $.Release.Name. In named templates, the $ is the argument passed to include, not the root of the outer template, so what you pass at the call determines what the helper can access.
3. Why must “required” be written both as required and also written into the schema?
required only errors when rendering reaches that line, and it reports only the first error; in lint mode it only logs and does not fail. The schema validates the merged values before rendering and lists all errors at once, and lint fails too. They complement each other: the schema covers input shape, while required covers the computation prerequisites in the template.
4. helm dependency update and build When should each be used? Why does a change to a file:// dependency or a dependency version not take effect?
update re-resolves according to the ranges in Chart.yaml and rewrites Chart.lock; use it when adding or upgrading dependencies. build restores strictly from Chart.lock; use it in CI. The .tgz files in charts/ are snapshots: after changing ../common-lib or the dependency version in Chart.yaml, you need to run update again. Rendering only checks dependency names, so a version mismatch produces no error.
5. What problems can lint, kubeconform, and helm test each find? Give one example that only kubeconform can find.
lint: Chart.yaml, schema, template syntax, and YAML validity; kubeconform: whether field names and types conform to the Kubernetes schema; helm test: whether the deployed service and dependencies actually work. Example: resources.request (missing s)—valid YAML; lint passes when the schema only declares object, while kubeconform -strict reports additional properties not allowed.
6. When an upgrade reports spec.selector … field is immutable, how do you handle it?
First confirm which helper changed selectorLabels (nameOverride, a chart rename, or putting the version label into the selector). Preferably revert to the original selector. When a new selector is truly needed,kubectl delete deploy --cascade=orphan keep the Pods, then run helm upgrade to create a new Deployment, and after the new Pods are Ready, clean up the old ReplicaSet. --force-replace deletes and recreates the resource, which causes downtime, so use it only in non-production.
Final quiz (12 questions, covering all modules)
Sources and version notes
| Topic | Verified conclusion | Source (accessed 2026-11-15) |
|---|---|---|
| Helm version | v4.3.2 (2026-11-13) is the latest; v4.3.1 and v3.22.1 were released on 2026-10-15 | helm/helm releases |
helm create Scaffold | v4.3.2 generates Chart.yaml, values.yaml, .helmignore, NOTES.txt, _helpers.tpl, deployment, hpa,httproute, ingress, service, serviceaccount, tests/test-connection; it does not generate a schema; fullname is truncated at 63 + trimSuffix; release name limit is 53 | Source pkg/chart/v2/util/create.go,validate_name.go (v4.3.2 tag) |
| schema validation | Dependency santhosh-tekuri/jsonschema/v6 (go.mod v6.0.3); this library supports draft-04/06/07/2019-09/2020-12; if $schema is not declared, the latest draft is used; Helm does not enable format assertions; error prefix values don't meet the specifications of the schema(s); subcharts validate their values section with their own schema | Source pkg/chart/common/util/jsonschema.go,values.go;jsonschema README;Charts docs(Schema Files) |
| lint | --strict makes WARNING fail; --with-subcharts,--kube-version,--quiet,--skip-schema-validation; icon is INFO; in LintMode, required/fail do not fail and lookup is unavailable; release name test-release; template extensions .yaml/.yml/.tpl/.txt; selector and naming checks | Source pkg/cmd/lint.go,pkg/action/lint.go,pkg/chart/v2/lint/rules/*,pkg/engine/engine.go |
| template / dry-run | --dry-run: install/upgrade take none|client|server, template takes client|server; --validate marked deprecated; --skip-tests,--include-crds,--is-upgrade,--api-versions | Source pkg/cmd/template.go,helpers.go |
| Template functions | Sprig v3.3.0; env/expandenv removed; lookup in helm template is always empty; testing requires --dry-run=server; toPrettyRawJson is provided from 4.4.0 onward | Template Function List · Functions and Pipelines |
| Chart.yaml / crds / dependencies / global / library | apiVersion v2; kubeVersion constraints; condition takes precedence over tags; global only propagates downward; crds/ is not rendered, is installed only on install, and is neither upgraded nor deleted; library charts are not installable (%s charts are not installable); Chart API v3 is controlled by HELM_EXPERIMENTAL_CHART_V3 . | Charts; source internal/gates/gates.go,pkg/action/install.go |
| dependency commands | update/build/list; a mismatched Chart.lock reports an error; Saving N charts / Deleting outdated charts Output | Source pkg/downloader/manager.go,internal/resolver/resolver.go |
| .helmignore | Go filepath.Match, does not support ** | The .helmignore file |
| helm test | helm.sh/hook: test; --logs,--filter,--timeout (default 300s); log header POD LOGS: pod (container) | Chart Tests; source pkg/cmd/release_testing.go |
| Install order | InstallOrder: … PodDisruptionBudget → ServiceAccount → Secret → ConfigMap … Service … Deployment → HPA … | Source pkg/release/v1/util/kind_sorter.go |
| kubeconform | v0.8.0 (2026-06-04); flags -strict/-summary/-kubernetes-version/-schema-location; the default schema repository already includes v1.37.0; CRDs-catalog includes gateway.networking.k8s.io HTTPRoute v1 | yannh/kubeconform · kubernetes-json-schema · CRDs-catalog |
| CloudPirates redis | Consistent with Lesson 1, using 0.39.1 (OCI oci://registry-1.docker.io/cloudpirates/redis); values: auth.enabled: true,auth.existingSecret,auth.existingSecretPasswordKey: redis-password,persistence.size: 8Gi,global.imageRegistry; when existingSecret is not set, the Secret template uses lookup + randAlphaNum to generate the password; dependency common 2.2.1; ships its own draft-07 values.schema.json (it does not forbid additional properties at the top level). The GitHub main branch is currently at 0.39.6 | CloudPirates-io/helm-charts(read on 2026-11-16 from the main branch values.yaml, Chart.yaml, and templates/secret.yaml) |
| Bitnami catalog change | Since 2025-08 the free image catalog has changed: old images moved to bitnamilegacy and are no longer updated (this is why Lesson 1 chose CloudPirates) | bitnami/charts(README announcement) |
Video verification notes
The following videos were verified for title and channel through the YouTube oEmbed endpoint (2026-11-15): TechWorld with Nana, “What is Helm in Kubernetes? Helm and Helm Charts explained | Kubernetes Tutorial 23” (-ykwb1d0DXU); IBM Technology, “What is Helm?” (fy8SHvNZGeE); That DevOps Guy, “Introduction to Helm | Kubernetes Tutorial | Beginners Guide” (5_J7RWLLVeQ); DevOps Journey, “How to Create Helm Charts - The Ultimate Guide” (jUYNS90nq8U) and “Helm and Helm Charts Explained - Helm Tutorial for Beginners” (w51lDVuRWuk); Rahul Wagh, “Complete Helm Chart Tutorial: From Beginner to Expert Guide” (DQk8HOVlumI); KodeKloud, “What is Helm? | Helm Concepts Explained | KodeKloud” (kJscDZfHXrQ); Matthew Palmer, “Helm and Kubernetes Tutorial - Introduction” (9cwjtN3gkD4). The oEmbed endpoint does not return duration or publish date, so durations are not listed on the cards. All videos are in English and were recorded before Helm 4. No verified dedicated videos were found for values.schema.json, library charts, helm test, or kubeconform, so storyboard scripts are provided instead.
Voice narration notes
The “Voice” page uses the browser’s Web Speech API (en-US) to read the narration script aloud, and English terms are pronounced with en-US. The result depends on the system voice pack. This courseware does not embed MP3 files; if you need offline audio, give the narration script to a TTS service to generate it.
Known limitations
- The lab commands were not actually run in the environment that generated this courseware. The IPs, times, revisions, hashes, and line numbers in the “Expected output” are sample values; use your own environment as the reference.
- The error wording for schema and kubeconform comes from the formats of the validation libraries used and may change slightly between library versions. Under SSA, API error prefixes such as the immutable selector message may differ slightly from the examples.
- The myapp’s
/healthzbehavior and the image user UID 10001 come from the Docker lesson. If your image differs, adjust the probes and securityContext. The redis image UID 999 should follow the actual image. - The rendering details of the CloudPirates redis subchart (the generated object list, headless Service and PVC names, and image line format) are inferred from the main-branch source for the 0.39.1 behavior. The examples are marked “follow the actual output”, and the same applies to the kubeconform resource counts.
- OCI dependencies require access to Docker Hub (
registry-1.docker.io). Anonymous pulls are rate-limited. For offline environments, copy thecharts/*.tgzimage in advance and commit or mirror it to an internal repository. - The HTTPRoute schema version in CRDs-catalog may differ from the Gateway API version installed in the cluster.
- The rules in the animation are a simplified simulation of Helm behavior (for example, the schema simulator only implements the keywords used by this lesson’s schema).