Skip to content

Packaging for Kubernetes: Helm Charts, Values, Releases, Kustomize Overlays ​

"Helm uses a packaging format called charts. A chart is a collection of files that describe a related set of Kubernetes resources." — Helm documentation, Charts (helm.sh/docs/topics/charts, docs version 4.3.1)

Summary: A Kubernetes application is a dozen YAML objects that must differ slightly per environment and change together on every release; Helm solves that by rendering Go templates from values into a versioned release it can upgrade and roll back, Kustomize solves it by patching plain YAML bases into per-environment overlays, and most teams end up using one, the other, or Helm for third-party software plus Kustomize for their own. Focus: The manifest-copy problem; Helm 3 and Helm 4 architecture (no Tiller, release Secrets, revision history, three-way strategic merge, server-side apply in Helm 4, rollback); chart anatomy (Chart.yaml with apiVersion v2, values.yaml, templates/, _helpers.tpl, NOTES.txt, the crds directory, dependencies, subcharts, library chart); templating (Go templates, sprig functions, include, tpl, required, default, toYaml, nindent and indent, if else with, range, named templates with define, whitespace control); values design (values precedence, --set and --values, values.schema.json, secrets never in values); the lifecycle (helm install, helm upgrade --install, --atomic / --rollback-on-failure, --wait, --timeout, helm rollback, helm history, helm uninstall, hooks and hook weights, hook-delete-policy, helm test, the helm diff plugin); distribution (helm repo and index.yaml, OCI registry with helm push / helm pull, provenance and chart signing, Artifact Hub); chart testing (helm lint, chart-testing ct, helm unittest, helm template with kubeconform); Kustomize (kustomization.yaml, resources, bases and overlays, patches as strategic merge patch or JSON 6902 patch, images with newTag, configMapGenerator and secretGenerator with a hash suffix, namePrefix / nameSuffix, commonLabels versus labels, components, replacements, kubectl apply -k, kustomize build); Helm vs Kustomize and the hybrid; Argo CD and Flux support for both; the pitfalls (CRD upgrade pitfalls, immutable fields, selector immutability, big values files); a Go service chart with HPA, a Laravel chart (php-fpm + Nginx, queue worker, scheduler CronJob, migration hook Job) and a Kustomize overlay set for dev, staging and prod. Learning goal: Write a chart that renders the same app correctly for three environments, refuses bad values before anything reaches a cluster, upgrades without resetting scaled replicas or breaking selectors, runs Laravel migrations before the new code, one migrator at a time, and can be linted, unit-tested, signed and pushed to an OCI registry; write the same app as a Kustomize base with overlays; and choose between the two (or combine them) for a given team and GitOps tool.

This is the packaging chapter of the Kubernetes group. What the objects inside a chart mean is owned elsewhere: Deployments, probes, rollouts and Jobs are Kubernetes Workloads; ConfigMaps, Secrets, External Secrets and volumes are Configuration, Secrets & Storage; requests, limits and the HPA are Resources, Scheduling & Autoscaling; ServiceAccounts, RBAC and Pod Security are Security & RBAC; the API server, kubectl and kubectl apply are Kubernetes Architecture & Setup; CRDs and operators are Extending Kubernetes. Here those objects are only the payload. After packaging comes delivery: the pipeline that lints, tests and pushes charts is CI/CD Pipelines, Argo CD and Flux as controllers are GitOps, canary and blue-green are Deployment Strategies. The images the charts deploy are built in Images & Dockerfiles; the architectural "why Kubernetes at all" is Containers & Kubernetes; Go's text/template package, which Helm's engine is built on, is taught for HTML in html/template; and why a migration must be backwards compatible with the code still running is Zero-Downtime Schema Migrations. The command tables are in the kubectl cheatsheet.

Verified against: Helm docs 4.3.1 and the Helm v4.0.5 source (the CLI code was compiled from its Go module on the build host, see Lab), kubectl v1.36.1 with its built-in Kustomize v5.8.1, Argo CD stable docs, Flux v2 docs (HelmRelease helm.toolkit.fluxcd.io/v2, Kustomization kustomize.toolkit.fluxcd.io/v1), Laravel 13.x, on 2026-11-29.

Page map ​

If you are looking forGo to
The whole page in three tablesEverything in one minute
Why copying YAML per environment breaksWhy it exists
Helm Classic 2015, Tiller, Helm 3, Helm 4, kubectl -kWhere it comes from
Chart.yaml, apiVersion v2, version vs appVersion, typeCharts and Chart.yaml
templates/, _helpers.tpl, NOTES.txt, crds/, charts/, .helmignoreChart directory
Actions, pipelines, built-in objects, sprig, include, tpl, toYaml, nindentGo templates and sprig functions
if / else / with, range, variables, $, dash trimmingControl structures and whitespace control
define, include vs template, scopeNamed templates
Values precedence, --set pitfalls, values.schema.json, secretsValues design
dependencies, subcharts, globals, library chartsDependencies and library charts
Release Secrets, revisions, three-way merge, server-side applyReleases
install, upgrade --install, --atomic, --wait, rollback, history, uninstallLifecycle commands
pre-install, post-upgrade, weights, delete policies, migrationsHooks
helm lint, kubeconform, helm unittest, ct, helm test, helm diffTesting charts
helm repo, index.yaml, OCI, helm push, provenance, cosign, Artifact HubDistributing charts
kustomization.yaml, resources, bases and overlaysKustomize
Strategic merge patch, JSON 6902 patch, targetsPatches
images, replicas, namespace, namePrefix, labelsTransformers
configMapGenerator, secretGenerator, hash suffixGenerators
components, replacementsComponents and replacements
Helm vs Kustomize, helm template piped to kustomize, Argo CD, FluxHelm vs Kustomize
CRDs, immutable fields, selectors, huge values filesPitfalls
Render pipeline, upgrade algorithm, knobs, error messagesMechanics
CodeGo, Laravel, Kustomize overlay set
Ten classic problems and their fixesSolving the classic problems
Which tool, which values layout, which distributionChoosing
From one app to many clustersIn architecture
Commands with real and expected outputLab
Wrong beliefs, summary, quiz, termsMisconceptions, Cheat sheet, Self-check, Glossary

Everything in one minute ​

Helm in one table.

ThingWhat it isWhere it livesTrap
ChartA directory (or .tgz) of templates, default values and metadataGit, a chart repository, an OCI registryversion is the chart's version, appVersion the app's
ValuesThe parameters a chart exposesvalues.yaml (defaults), -f files, --setLater sources override earlier ones key by key; lists are replaced whole
TemplateA Go text/template file that renders Kubernetes YAMLtemplates/*.yamlRendered text must still be valid YAML: indentation is your job (nindent)
ReleaseOne installed instance of a chart, with a name and a namespaceSecrets sh.helm.release.v1.<name>.v<revision> in the release namespaceThe Secret contains the values: treat its read access like the values themselves
RevisionOne version of a release (install = 1, every upgrade or rollback +1)One Secret per revision, --history-max (default 10) keptA rollback creates a new revision
HookA resource rendered by the chart but run at a lifecycle pointhelm.sh/hook annotationNot part of the release: not upgraded, not deleted, unless a delete policy says so
TestA hook of type test, run by helm testtemplates/tests/A bare tests/ line in .helmignore silently removes it

The commands that matter.

CommandDoesCluster needed?
helm lint --strict ./chart -f values-prod.yamlChecks Chart.yaml, renders templates, validates the schemaNo
helm template rel ./chart -f values-prod.yamlRenders everything to stdout (client-side)No
helm upgrade --install rel ./chart -n ns -f values-prod.yaml --rollback-on-failure --wait --timeout 5mInstall or upgrade, wait for readiness, undo on failure (Helm 3: --atomic)Yes
helm history rel / helm rollback rel 2List revisions / return to revision 2 as a new revisionYes
helm test rel --logsRun the chart's test hooksYes
helm diff upgrade rel ./chart -f ...Show what an upgrade would change (plugin)Yes (reads live state)
helm package ./chart && helm push chart-1.3.0.tgz oci://ghcr.io/acme/chartsPublish to an OCI registryNo (registry only)
kubectl kustomize overlays/prod (= kustomize build)Render an overlay to stdoutNo
kubectl apply -k overlays/prodRender and apply an overlayYes

Kustomize in one table.

FieldDoesTrap
resourcesLists files and other kustomization directories (bases)bases: is deprecated since v2.1.0; put directories in resources
patchesStrategic merge or JSON 6902 patches, optionally by targetpatchesStrategicMerge / patchesJson6902 deprecated in v5.0.0
imagesRewrites image name, newTag or digestThe name must match the image string in the YAML
configMapGenerator / secretGeneratorBuilds ConfigMaps/Secrets with a content hash suffix and rewrites referencesA Secret literal in Git is still a secret in Git
namespace, namePrefix, nameSuffixSet namespace and rename every resource (and references)Hard-coded names inside strings (URLs) are not rewritten: use replacements
labelsAdds labels, selectors only with includeSelectors: truecommonLabels (deprecated in v5.0.0) always edits selectors, which are immutable
componentsOpt-in bundles (kind: Component) reused by several overlaysComponents are kustomize.config.k8s.io/v1alpha1
replacementsCopies a field from one object into fields of othersRuns on the final names, so it sees prefixes
orders-api/ (a chart is a directory, packaged as orders-api-1.3.0.tgz)Chart.yamlapiVersion v2, version, appVersion, depsvalues.yamldocumented defaults, no secretsvalues.schema.jsonJSON Schema: types, enums, requiredtemplates/_helpers.tpl define blocks onlydeployment.yaml service.yaml hpa.yamlconfigmap.yaml pdb.yaml serviceaccountNOTES.txt printed after installtests/ helm.sh/hook: testcrds/plain YAMLcharts/subcharts, libs.helmignore (anchor: /tests/) READMETemplate engine1 merge values (precedence)2 validate vs schema3 Go text/template + Sprig include, tpl, required, toYaml, nindent, default4 sort by kind, split hooks5 parse each file as YAMLbuilt-ins: .Values .Release .ChartRelease manifestDeployment, ServiceHPA, PDB, ConfigMapServiceAccountHookstest Pod, migrate Jobnot part of the releaseNOTES.txt textcrds/ is applied once, before templates, on install only:never upgraded, never deleted. charts/ subcharts render withtheir own values scope; a library chart renders nothing.

Why it exists ​

A real service is not one manifest. The Go orders-api in this chapter is a Deployment, a Service, a ConfigMap, a ServiceAccount, an HPA, a PodDisruptionBudget and a test Pod; the Laravel shop adds an Nginx config, a worker Deployment, a scheduler CronJob and a migration Job. Each exists three times (dev, staging, prod) with small differences: an image tag, a replica count, a database host, CPU requests. The first solution everybody tries is to copy the directory per environment and edit it. Within a month the copies drift: someone fixed a probe in prod/ and not in staging/, the dev copy still has last quarter's security context, and a "small" change touches thirty files. Nothing tells you which differences are intended.

Packaging tools make the intended differences explicit and everything else shared. Helm does it by parameterising: the YAML becomes templates, the differences become values, and a whole environment is "this chart at this version with these values". Kustomize does it by patching: the YAML stays plain and valid, a base holds the common version, and each environment is an overlay that lists its changes. Helm adds a second job Kustomize does not try to do: it records each install as a release with numbered revisions, so "what is running, with which values, and how do I go back" has an answer.

Simpler choiceRicher choiceWhat you buyWhat you pay
Copy manifests per environmentKustomize base + overlaysOne source of truth, small reviewed diffsLearning patch semantics; no release history
Kustomize overlaysHelm chart with valuesParameters with defaults, schema validation, versioned packages, hooks, rollbackTemplates are text, not YAML; harder to read and debug
kubectl apply of rendered outputHelm releaseshelm history, helm rollback, pruning of removed objectsRelease Secrets to protect; state outside Git
Chart in the app repoChart in a registry (OCI)Versioned, signed artefacts that GitOps tools pullA publish step in CI, a registry to run
One values file per env, hand-editedLayered values (common + env) + schemaMistakes caught at render timeDesign effort: a values API is a public API
Helm only or Kustomize onlyHelm for third-party charts, Kustomize for your apps (or helm template piped to kustomize)Each tool where it is strongestTwo tools to know

The analogy used through this page: a form letter versus tracing paper. A Helm chart is a form letter with blanks ("Dear {name}, your order {id}..."): the letter is not readable until the blanks are filled, but anyone can produce a correct letter by supplying the fields, and you keep a carbon copy of each letter sent (the release). Kustomize is a stack of tracing paper: the bottom sheet is a complete, readable drawing (the base), and each environment lays a sheet on top that redraws only a few lines (the overlay). You can always read every sheet on its own, but there is no list of fields: anyone may redraw any line, and nobody keeps copies of what was sent.

Three common misunderstandings, up front ​

  1. "helm upgrade --set image.tag=1.4.3 changes only the tag." If you pass any --set or -f, Helm does not reuse the last release's values (the v4.0.5 source copies the old values only "if len(newVals) == 0"): everything you passed last time with -f values-prod.yaml falls back to chart defaults. Pass the full set every time, or use --reset-then-reuse-values knowingly. See Values design.
  2. "Kustomize is a template engine." It is not: there are no variables, loops or conditionals, and a base is always valid YAML on its own. That is the point of the tool, and also its limit; see Helm vs Kustomize.
  3. "Helm upgrades CRDs from the crds/ directory." The chart docs: "CRDs are never installed on upgrade or rollback. Helm will only create CRDs on installation operations." Changing a CRD needs a separate step; see Pitfalls.

Where it comes from ​

WhenWhat happenedSource
19 Oct 2015First commit of Helm (Helm Classic, a Deis hackathon project), shown at the first KubeCon weeks laterHelm blog "Helm Turns 10", "Celebrating Helm's CNCF Graduation"
Early 2016Helm merges with Google's Deployment Manager and becomes a Kubernetes sub-project; Helm 2 introduces the in-cluster server TillerHelm blog (graduation post); Helm FAQ "Changes since Helm 2"
Helm 2.7.0A Secrets storage backend for release information appears (ConfigMaps stay the Helm 2 default)Helm FAQ "Changes since Helm 2"
25 Mar 2019Kubernetes 1.14: Kustomize is built into kubectl (kubectl apply -k, kubectl kustomize)Kubernetes 1.14 release blog; kubernetes.io Kustomize task page ("Since 1.14")
13 Nov 2019Helm 3.0.0: Tiller removed, three-way strategic merge patches, release Secrets as default storage, releases scoped to a namespace, JSON Schema for values, apiVersion: v2 charts, experimental OCI supportHelm blog "Helm 3.0.0 has been released!"; FAQ
30 Apr 2020Helm graduates in the CNCF; the post says Helm "is used by over 70% of Kubernetes users"Helm blog
24 Jan 2022Helm 3.8.0: "OCI registry support for charts is now generally available"GitHub release v3.8.0
2 Feb 2023Kustomize v5.0.0 deprecates commonLabels, patchesStrategicMerge, patchesJson6902 and other fields (kept in v1beta1, absent from a future v1)GitHub release kustomize/v5.0.0; kubectl.docs.kubernetes.io references
12 Nov 2025Helm v4.0.0 released at KubeCon NA, "the first new major version of Helm in 6 years": Wasm plugins, kstatus-based waiting, server-side apply by default for new releases, install by OCI digest, --atomic renamed --rollback-on-failure, Charts v3 experimentalHelm blog "Helm 4 Released"; Helm 4 Overview
9 Sep 2026 / 10 Feb 2027Last Helm 3 feature release / end of Helm 3 security fixesHelm blog "Helm 3 End of Life"
TodayHelm docs at 4.3.1; kubectl 1.36 ships Kustomize v5.8.1; the standalone kustomize is at v5.8.xhelm.sh version picker; kubectl version --client on the build host; kustomize releases

Two ideas fought over the same problem from the start. Helm's authors came from package management (apt, Homebrew): a chart is a package with a version, dependencies and an install/upgrade/remove lifecycle, and Helm 2 put a server (Tiller) in the cluster to run that lifecycle. Tiller had to hold broad permissions, so multi-tenant clusters had to lock it down; the Helm 3 FAQ explains the reversal: "Tiller's primary goal could be accomplished without Tiller, so one of the first decisions we made regarding Helm 3 was to completely remove Tiller." Kustomize came from the Kubernetes CLI SIG with the opposite philosophy, "template-free configuration customization": keep every file a valid Kubernetes object and express variation as patches. Neither won; Argo CD and Flux render both, and Helm 4's own overview lists post-renderers (the hook that lets Kustomize patch Helm's output) as a first-class plugin type.

The concept catalogue ​

Each block follows the same order: plain words, the common misunderstanding, the definition, a sequence, real scenarios, how the tools differ, and the fix.

Charts and Chart.yaml: apiVersion v2, version, appVersion, type Must-know ​

In plain words: Chart.yaml is the package's label: its name, its own version, the version of the application it installs, what it depends on, and whether it is installable at all.

Common misunderstanding: "version and appVersion are the same number." version is the chart's SemVer and must change whenever the templates or defaults change (chart-testing's --check-version-increment enforces this, default true); appVersion is informational, "the version of the app that this contains", and this chapter's helpers use it as the default image tag. A chart 1.3.0 can deploy app 1.4.2.

Definition: "The apiVersion field should be v2 for Helm charts that require at least Helm 3. Charts supporting previous Helm versions have an apiVersion set to v1 and are still installable by Helm 3." Version 2 moved dependencies into Chart.yaml (from requirements.yaml) and added type: "There are two types: application and library." Other fields: kubeVersion (a SemVer constraint checked at render time), description, keywords, home, sources, maintainers, icon, deprecated, annotations (Artifact Hub reads artifacthub.io/* keys from here). Helm 4 adds an experimental chart API v3 behind HELM_EXPERIMENTAL_CHART_V3=1; v2 charts "continue to work unchanged".

text
helm template orders-api ./orders-api   (Chart.yaml: kubeVersion ">=1.30.0-0")
1  load Chart.yaml; type application -> installable (type library -> "library charts are not installable")
2  compare kubeVersion with the target Kubernetes version
     client-only render: the version compiled into Helm (or --kube-version)
     a module build without the release ldflags says v1.20.0 -> "chart requires kubeVersion: >=1.30.0-0
     which is incompatible with Kubernetes v1.20.0" (seen on the build host; the Lab shows the fix)
3  load values.yaml, merge user values, validate values.schema.json
4  render templates/ with .Chart.Version = 1.3.0 and .Chart.AppVersion = 1.4.2

Real scenarios: a team bumps the image but not version, and the registry rejects the push of an existing tag (or worse, a mutable repository overwrites 1.3.0); a chart that uses autoscaling/v2 declares kubeVersion so old clusters fail at render time, not at apply time; a platform team ships a type: library chart that only contains helpers.

FieldRead byEffect
apiVersion: v2Helm 3 and 4Enables dependencies and type in Chart.yaml
versionHelm, registries, ctPackage identity; OCI tag (a + becomes _ in the tag)
appVersionYour templates, helm listShown as APP VERSION; default tag by convention
kubeVersionHelm at render timeRefuses incompatible clusters
type: libraryHelmRenders nothing; cannot be installed
dependencieshelm dependency update/buildFetches subcharts into charts/, writes Chart.lock
annotations: artifacthub.io/*Artifact HubChangelog, license, images, signing key on the hub page

Fix: the orders-api Chart.yaml pins apiVersion: v2, type: application, kubeVersion, and a changelog annotation; CI fails a pull request that changes templates without bumping version.

The chart directory: templates, _helpers.tpl, NOTES.txt, crds directory, charts, .helmignore Must-know ​

In plain words: Everything under templates/ is rendered and sent to the cluster, except files that start with _ (helpers) and NOTES.txt (a message printed to the user). crds/ and charts/ are special directories Helm treats differently.

Common misunderstanding: "crds/ files are templates too." They are not rendered at all: "CRD files cannot be templated. They must be plain YAML documents." Helm installs them before the templates and only on install.

Definition: The chart docs list the structure: Chart.yaml, optional LICENSE and README.md, values.yaml, optional values.schema.json, charts/ ("A directory containing any charts upon which this chart depends"), crds/ ("Custom Resource Definitions"), templates/ ("A directory of templates that, when combined with values, will generate valid Kubernetes manifest files") and templates/NOTES.txt ("OPTIONAL: A plain text file containing short usage notes"). "Helm reserves use of the charts/, crds/, and templates/ directories, and of the listed file names." Files whose names begin with an underscore are expected to hold named templates and produce no manifest. .helmignore lists paths to skip; "Helm ignores every path that matches a pattern when it loads the chart", for helm package and for install, upgrade and template from a directory. Its globbing is Go's filepath.Match: "The '**' syntax is not supported."

text
.helmignore line "tests/"   (what the helm-unittest README suggests, minus the slash)
1  intent: keep the unit-test suites in ./tests/ out of the package
2  the rule has no leading "/", so it matches a directory named tests at ANY depth
3  templates/tests/test-connection.yaml is skipped when the chart is loaded
4  helm template prints no test Pod; helm test later finds no tests: nothing fails
fix: "/tests/" (anchored to the chart root); found by this chapter's Go test on the first run

Real scenarios: *.txt in .helmignore also hides NOTES.txt; a chart with a secrets/ folder of local test keys gets them packaged because .helmignore was never written; a _helpers.tpl renamed to helpers.tpl produces an empty-document warning; an operator chart's CRD change never reaches clusters that already had the chart.

PathRendered?Installed whenUpgraded?
templates/*.yamlYesinstallYes (patched)
templates/_*.tplOnly as define blocksnever directlyn/a
templates/NOTES.txtYes, printedafter install/upgraden/a
templates/tests/* (hook test)Yeson helm testrecreated per run
crds/*.yamlNoinstall, before templatesNever; never deleted
charts/*Each subchart renders with its own valueswith the parentwith the parent

Fix: anchor .helmignore patterns (/tests/), keep CRDs either in crds/ with a documented manual upgrade step or in a separate chart (see Pitfalls), and keep every helper in _helpers.tpl.

Go templates and sprig functions: include, tpl, required, default, toYaml, nindent, indent Must-know ​

In plain words: A Helm template is a YAML file with holes. Each hole is an action that reads values (.Values.image.tag), passes them through functions with a pipe (| default "1.4.2" | quote) and prints the result. The output is text, and only afterwards is it parsed as YAML.

Common misunderstanding: "Helm understands YAML while it renders." It does not; it is Go's text/template printing characters. toYaml of a map prints lines starting at column zero, and only nindent 12 puts them where the YAML structure needs them. A wrong indent is not a template error; it is invalid or, worse, differently valid YAML.

Definition: Helm's engine is Go text/template plus most of the Sprig library ("Helm has over 60 available functions", most of them from Sprig, in the template guide's words) plus Helm's own: include (call a named template and return its output as a string, so it can be piped), tpl (render a string as a template, used for values that contain template syntax), required (fail the render with a message when a value is nil or empty), toYaml / fromYaml / toJson, lookup (read live objects; returns empty during helm template), and .Files accessors. The Helm source removes two Sprig functions on purpose: env and expandenv are deleted from the map, so templates cannot read the environment of whoever runs Helm. Built-in objects: .Values, .Release (Name, Namespace, Revision, IsInstall, IsUpgrade, Service), .Chart (fields of Chart.yaml, capitalised), .Capabilities (Kubernetes version, API versions), .Template (Name, BasePath), .Files.

yaml
# The idioms this chapter's charts use (excerpts; full files in the Go and Laravel sections)
metadata:
  labels:
    {{- include "orders-api.labels" . | nindent 4 }}          # named template, re-indented
data:
  LOG_LEVEL: {{ .Values.config.logLevel | default "info" | quote }}
  DATABASE_HOST: {{ required "config.databaseHost is required" .Values.config.databaseHost | quote }}
spec:
  template:
    metadata:
      annotations:
        checksum/config: {{ include (print $.Template.BasePath "/configmap.yaml") . | sha256sum }}
    spec:
      containers:
        - env:
            {{- range $name, $value := .Values.extraEnv }}
            - name: {{ $name }}
              value: {{ tpl $value $ | quote }}                    # value may contain templates
            {{- end }}
          resources:
            {{- toYaml .Values.resources | nindent 12 }}
text
Rendering one line: image: {{ include "orders-api.image" . | quote }}
1  include runs define "orders-api.image" with dot = the root context
2  required "image.repository is required" .Values.image.repository -> ghcr.io/acme/orders-api
3  digest set? printf "%s@%s" -> ghcr.io/acme/orders-api@sha256:0b7e...   (else repo:tag)
4  the string goes through | quote -> "ghcr.io/acme/orders-api@sha256:0b7e..."
5  text/template prints it; the whole file is later parsed as YAML and sorted by kind

Real scenarios: .Values.resources | toYaml printed without nindent produces resources: limits: on one line and the API server rejects it; default treats false and 0 as empty, so default true .Values.enabled can never be turned off (use hasKey or ternary); a chart reads a large JSON dashboard with .Files.Get; tpl lets a value contain template syntax such as .Release.Namespace in braces, which the prod values file in this chapter uses for an OpenTelemetry attribute.

FunctionSourceExampleWatch out
defaultSprig.Values.tag | default .Chart.AppVersionEmpty = nil, "", 0, false, empty list/map
quote / squoteSprig"8080" for env valuesEnv values must be strings in Kubernetes
requiredHelmFail with a messageLint mode only warns (see Lab)
includeHelmNamed template as a string, pipeablePrefer over template, which cannot be piped
tplHelmRender a value as a templateNeeds the context ($) as second argument
toYamlHelmMap or list to YAMLOutput has no trailing newline (Helm trims it)
nindent N / indent NSprigNewline plus N spaces / N spacesnindent after a left-trimming action is the usual pair
sha256sumSprigChecksum annotationHash of rendered text, not of the live object
lookupHelmRead a live objectEmpty map in helm template and in Argo CD
failHelmAbort with a messageLike required for arbitrary conditions

Fix: treat every template as two languages at once: check the Go template with helm lint and the YAML with helm template | kubeconform; keep logic in _helpers.tpl; use include plus nindent for every block.

Control structures, variables and whitespace control: if else with, range Must-know ​

In plain words: if renders a block only when a value is set, with does the same and also moves "dot" into that value, and range loops over a list or map. Dashes inside the braces eat the whitespace next to them, which decides whether your YAML ends up with blank lines or glued lines.

Common misunderstanding: "Inside with or range I can still write .Values." Inside them, dot is the current element; .Values there means "the field Values of this element" and renders nothing. Use $ (the root context, always available) as in include "orders-api.selectorLabels" $.

Definition: if / else if / else / end test "truthiness" (false for false, 0, nil, empty string or collection). with X sets dot to X and skips the block when X is empty. range iterates lists (range $i, $v := list) and maps (range $k, $v := map, keys in sorted order). Variables are declared with := and are scoped to the block. Whitespace control: a dash after the opening braces trims all whitespace (including newlines) before the action, a dash before the closing braces trims it after. The template guide's rule of thumb is to trim to the left and let nindent produce the newline.

yaml
# From templates/deployment.yaml: three idioms in eight lines
spec:
  {{- if not .Values.autoscaling.enabled }}      # if: omit replicas when an HPA owns them
  replicas: {{ .Values.replicaCount }}
  {{- end }}
      {{- with .Values.nodeSelector }}              # with: block only if set; dot = the map
      nodeSelector:
        {{- toYaml . | nindent 8 }}
      {{- end }}
text
Whitespace, character by character, for the "if" above with autoscaling.enabled = false
1  "spec:\n  " then the action "{{- if ...}}" trims the "\n  " before it -> "spec:"
2  the if body begins with "\n  replicas: " -> "spec:\n  replicas: 2"
3  "{{- end }}" trims the newline before it; the text after it starts with "\n"
-> "spec:\n  replicas: 2\n  revisionHistoryLimit: 5"   (no blank line, no glued line)
with autoscaling.enabled = true: "spec:\n  revisionHistoryLimit: 5" (replicas line gone)

Real scenarios: an empty podAnnotations: {} produces annotations: with nothing under it (YAML null) unless guarded by with; a range over .Values.tolerations that forgot the dash yields blank lines (harmless) or, with a dash on the wrong side, - key: a- key: b (broken); topologySpreadConstraints items rendered as a dash followed by a trimmed toYaml . | nindent 10 came out as a bare - followed by an indented map on the first render of this chapter's chart (valid YAML, ugly), fixed by starting the item with a literal key.

ConstructDot insideEmpty inputTypical use
if / elseunchangedelse branchFeature flags (autoscaling.enabled)
withthe valueblock skippedOptional maps and lists (nodeSelector)
range (list)the elementblock skippedContainers, tolerations, extra env
range (map)the value; key via $kblock skippedEnv maps, sorted by key
$root contextn/aCalling helpers inside with / range
Left dash / right dash inside the bracesn/an/aTrim whitespace before / after the action

Fix: guard optional blocks with with, use $ inside loops, and look at helm template output (not just lint) after every template change; manifestcheck and the unit tests catch the structural mistakes.

Named templates: define, include, template Important ​

In plain words: A named template is a reusable snippet: you define it once (in _helpers.tpl) and call it from any file. Labels, names and image strings are the classic ones, because they must be identical everywhere.

Common misunderstanding: "Template names are local to my chart." They are global across the chart and all its subcharts. The named-templates guide warns that template names are global and recommends prefixing every name with the chart name (orders-api.labels), which is why helm create does exactly that.

Definition: define "name" ... end declares a template; template "name" . inserts it but cannot be piped; include "name" . returns it as a string, so include "x" . | nindent 4 works. The second argument is the context; pass . for the current scope, $ for the root, or a dict to pass several values (the library chart in this chapter takes dict "ctx" $ "component" "web"). The comment form with /* and */ inside braces documents a helper without producing output.

text
include "acme-lib.labels" (dict "ctx" . "component" "worker")
1  dict builds a map {ctx: root, component: "worker"}
2  acme-lib.labels runs with dot = that map: .ctx.Chart.Name, .ctx.Release.Name, .component
3  it calls include "acme-lib.selectorLabels" . (the same map) for the immutable part
4  result: helm.sh/chart, name, instance, component, version, managed-by, part-of

Real scenarios: two subcharts both define fullname, and whichever loads last wins for both; a helper that prints a trailing newline doubles blank lines everywhere it is included; selector labels and metadata labels defined separately so the version never enters a selector.

CallPipeableTypical use
template "x" .NoLegacy; avoid
include "x" .YesEverything
include "x" $YesInside range / with
include "x" (dict "ctx" $ "k" v)YesLibrary helpers with parameters
tpl .Values.s $YesValues that contain templates

Fix: prefix names with the chart name, split selectorLabels from labels, and put shared helpers in a library chart once several charts copy them.

Values design: values precedence, --set and --values, values.schema.json, secrets Must-know ​

In plain words: Values are the chart's public API. The chart ships defaults; you layer environment files on top; the result is checked against a JSON Schema before a single template runs.

Common misunderstanding: "--set is just a shorter -f." It has its own parser and types. In Helm's source (pkg/strvals), true/false become booleans, null becomes nil (which deletes the key from the defaults), 0 becomes an integer, a string that does not start with 0 and parses as an integer becomes int64, and everything else stays a string. Values files go through sigs.k8s.io/yaml, which (its README) "first converts YAML to JSON using go-yaml and then uses json.Marshal and json.Unmarshal", so numbers become float64: tag: 1.10 arrives as 1.1, and 1000000 prints as 1e+06. This chapter's Go tests assert all of these against Helm's own packages.

Definition: The values guide lists the sources "in order of specificity": the chart's values.yaml, a parent chart's values.yaml (for a subchart), a values file passed with -f, and --set parameters. For repeated flags the install docs say "The priority will be given to the last (right-most) file specified", and the same for --set. Maps merge deeply; lists are replaced; null removes. --set-string forces strings, --set-file reads a value from a file, --set-json takes JSON, and --set-literal takes the value verbatim. A values.schema.json (JSON Schema) is validated on helm install, helm upgrade, helm template and helm lint (the Helm 3 FAQ lists exactly those four). On upgrade, only an upgrade with no new values reuses the previous release's values; --reuse-values, --reset-values and --reset-then-reuse-values change that.

Which value wins? Higher layer wins, key by key5 --set / --set-string / --set-json (last one wins)4 -f values-prod.yaml (right-most file wins)3 -f values-common.yaml2 parent chart values.yaml (subchart: key named after it)1 the chart's own values.yaml (defaults)then values.schema.json validates the merged resultMerge rulesmaps: merged deeply image.tag from 4, repository from 1lists: replaced whole tolerations in 4 drop those in 1null: deletes the default key --set nodeSelector=nulltypes: --set 3 is int64, 1.10 a string; in a file 1.10 is the float 1.1upgrade + any --set or -f: old values gone
text
helm upgrade orders-api ./orders-api -f values-prod.yaml --set image.tag=1.4.3
1  start from the chart's values.yaml (replicaCount 2, autoscaling.enabled false, ...)
2  merge values-prod.yaml: tag "1.4.2", digest sha256:0b7e..., autoscaling.enabled true, minReplicas 3
3  merge --set image.tag=1.4.3 -> tag "1.4.3" (a string: "1.4.3" is not an integer)
4  validate the result against values.schema.json (enum appEnv, digest pattern, no password keys)
5  render: digest is still set, so the image is ...@sha256:0b7e...: the --set tag changed nothing
   (the chart's rule is "digest beats tag"; know your chart's precedence rules too)

Real scenarios: --set annotations.team=a,b fails to parse because commas separate assignments (escape as a\,b); --set image.tag=2024.10 survives but the same line in a values file becomes the float 2024.1; a nightly job runs helm upgrade --set image.tag=$SHA and silently resets production to default replica counts; a values file grows to 2,000 lines because every template detail became a value; a database password in values-prod.yaml lands in Git and in the release Secret.

SourceTyped asWins overNote
Chart values.yamlYAML via JSON (float64 numbers)nothingDocument every key
Parent chart values (subchart key)samesubchart defaultsglobal: is shared by all subcharts
-f file (left to right)sameearlier sourcesThe right-most file wins
--set k=vstrvals rules (int64, bool, nil)all filesnull deletes a default
--set-string k=vstringall filesUse for tags and IDs
--set-json, --set-file, --set-literalJSON / file content / verbatimall filesListed in helm install --help (Helm 4.3 docs)
Argo CD parameters > valuesObject > values > valueFilesArgo CD's own orderthe chart's values.yamlFrom the Argo CD Helm docs

Secrets never in values. Release Secrets store the values ("The release information includes the contents of charts and values files, and therefore might contain sensitive data", from Helm's advanced guide), values files end up in Git, and helm get values prints them to anyone with read access to the release. Charts in this chapter take existingSecret: <name> and reference a Secret that the External Secrets Operator, SOPS or Sealed Secrets creates; the schema rejects password-style keys outright. The Secret side is taught in Configuration, Secrets & Storage.

Fix: quote tags in files, use --set-string for tags, pass the full set of files on every upgrade, ship a schema with enums and patterns, and keep the values surface small (what differs between environments, not every field of every object).

Dependencies, subcharts, globals and library charts Important ​

In plain words: A chart can include other charts. A subchart (say, a Redis chart) installs alongside yours with its own values; a library chart installs nothing and only lends you its named templates.

Common misunderstanding: "A subchart can read my chart's values." It cannot: the parent can set the subchart's values (under a key named after the subchart), and both can read .Values.global, but a subchart never sees its parent's other values.

Definition: Dependencies are listed in Chart.yaml under dependencies with name, version (a SemVer range), repository (https://..., oci://... or file://../path), and optionally condition (a values path such as redis.enabled), tags, alias and import-values. helm dependency update resolves the ranges, downloads .tgz files into charts/ and writes Chart.lock; helm dependency build rebuilds charts/ from the lock. A library chart has type: library; the library-charts page describes it as providing "chart primitives or definitions which can be shared by Helm templates in other charts". Installing one fails, which this chapter's tests assert against the real CLI code: Error: library charts are not installable.

text
helm dependency build ./shop-laravel   (Chart.yaml: acme-lib 0.2.0, repository file://../acme-lib)
1  no Chart.lock yet -> behaves like update: resolve 0.2.0 from the file:// path
2  package ../acme-lib into charts/acme-lib-0.2.0.tgz   ("Saving 1 charts")
3  write Chart.lock with the resolved version and a digest of the dependency list
4  helm template: acme-lib's templates are loaded; its define blocks are callable; it renders no objects

Real scenarios: a Bitnami-style Redis subchart toggled with condition: redis.enabled for dev only (production uses a managed Redis); the same labels helper copy-pasted into twelve charts until a library chart replaces it; helm dependency update in CI pulling a new minor version of a subchart because the range was ^18; a subchart's hooks running although the parent wanted none ("There is no way for a top-level chart to disable the hooks declared by subcharts").

MechanismValues flowRenders objectsTypical use
Subchart (application)parent -> .Values.<name>YesBundled Redis, Postgres for dev
global:parent -> every subchartn/aImage registry, environment name
condition / tagsparent values enable/disableYes, if enabledOptional components
aliassame chart twice under two namesYesTwo Redis instances
import-valueschild -> parentn/aExported defaults
Library chartnone (helpers only)NoShared labels, images, security contexts

Fix: pin dependency versions (or commit Chart.lock and use dependency build in CI), prefer managed services over database subcharts in production, and move shared helpers into a library chart with a prefix of its own (acme-lib.*).

Releases: release secret, revision history, three-way strategic merge, server-side apply Must-know ​

In plain words: Every helm install creates a release, and every upgrade or rollback adds a numbered revision. Helm stores each revision (chart, values, rendered manifest) in a Secret in the release's namespace, and uses the stored manifest of the last revision to work out what to change next time.

Common misunderstanding: "Helm compares the chart with the cluster." Helm 2 compared only the old and the new manifest, so kubectl scale to zero followed by helm rollback changed nothing. The Helm 3 FAQ: "In Helm 3, we now use a three-way strategic merge patch. Helm considers the old manifest, its live state, and the new manifest when generating a patch." Fields nobody owns in the chart (an injected sidecar) survive; fields the chart owns are restored.

Definition: Storage drivers are chosen by HELM_DRIVER (secret, the default since Helm 3; configmap; sql, beta; memory). The Secret name comes from fmt.Sprintf("%s.%s.v%d", HelmStorageType, rlsname, version) with HelmStorageType = "sh.helm.release.v1"; its type is helm.sh/release.v1; its labels are name, owner=helm, status and version; and "Each secret data entry is the base64 encoded gzipped string of a release" (Helm source, pkg/storage). --history-max (default 10) prunes old revisions. Release names are scoped to the namespace. In Helm 4, new releases default to server-side apply ("Helm 4 will default to server-side apply when installing a new Chart release"), while upgrades and rollbacks "follow the previous apply method of the release", so releases created by Helm 3 keep client-side apply (and its three-way merge) until you pass --server-side.

helm upgrade --install shop ... --rollback-on-failure --wait --timeout 5m1 render + validatevalues, schema, templates2 pre-upgrade hooksby weight: migrate Job (-5)3 apply new manifestpatch each object (see right)4 --waitready within --timeout5 post-upgrade hookse.g. cache warm-up Job6 record revision 3status deployedany step fails or times out: revision 3 = failed,roll back to 2, recorded as new revision 4Three-way merge (client-side apply path)old manifest(revision 2)replicas: 3live statereplicas: 0 (kubectl)+ injected sidecarnew manifestreplicas: 3image 2.1.0patch: replicas back to 3, image to 2.1.0, sidecar kept(Helm 2 diffed old vs new only: no change seen, replicas stayed 0)Helm 4: new releases use server-side apply; old ones keep their methodRelease storage (namespace of the release)Secret sh.helm.release.v1.shop.v2 type helm.sh/release.v1 supersededSecret sh.helm.release.v1.shop.v3 labels owner=helm,status=deployeddata.release = base64(gzip(chart + values + manifest + hooks))--history-max 10 prunes old revisions; helm history lists themHooks are not in the release manifest: Helm leavesthem alone unless a hook-delete-policy removes them.
text
Revision history of release "shop" (namespace shop-prod)
1  helm install          -> Secret sh.helm.release.v1.shop.v1   status=deployed
2  helm upgrade (3.8.0)  -> v1 status=superseded, v2 status=deployed
3  helm upgrade (3.9.0) fails a readiness wait with --rollback-on-failure
                         -> v3 status=failed; Helm rolls back to v2's manifest
4  the rollback is itself recorded: v4 status=deployed, description "Rollback to 2"
5  helm history shop     -> 1 superseded, 2 superseded, 3 failed, 4 deployed

Real scenarios: a 1 MB limit hit by a chart with huge embedded dashboards (the SQL backend is "particularly useful if your release information weighs more than 1MB (in which case, it can't be stored in ConfigMaps/Secrets because of internal limits in Kubernetes' underlying etcd key-value store)", from the advanced guide); a developer with namespace view permissions cannot run helm list because the default view role does not grant Secrets; a mesh-injected sidecar that Helm 2 would have deleted on upgrade; a Helm 3 release upgraded by Helm 4 still using client-side apply.

AspectHelm 2Helm 3Helm 4
Server componentTiller in the clusternone (kubeconfig permissions)none
Release storage defaultConfigMaps in Tiller's namespaceSecrets in the release namespaceSecrets in the release namespace
Release name scopecluster-widenamespacenamespace
Patch strategytwo-way strategic mergethree-way strategic mergeserver-side apply for new releases; previous method for existing ones
Waiting--wait readiness checks--wait--wait strategies watcher (kstatus), hookOnly (default), legacy
Undo on failure--atomic--atomic--rollback-on-failure (--atomic deprecated alias)

Fix: protect get on Secrets in release namespaces as carefully as the values themselves, keep --history-max small, and decide deliberately when to move old releases to server-side apply (--server-side true on an upgrade).

Lifecycle commands: helm install, helm upgrade --install, --atomic, --wait, --timeout, helm rollback, helm history, helm uninstall Must-know ​

In plain words: helm upgrade --install is the one command pipelines need: it installs the release if it does not exist and upgrades it otherwise. --wait makes Helm stay until the pods are ready, --timeout bounds that wait, and --rollback-on-failure (Helm 3: --atomic) undoes a failed attempt.

Common misunderstanding: "Without --wait, a successful helm upgrade means the new version is running." Without waiting, success means the API server accepted the objects. In Helm 4 the default --wait strategy when the flag is omitted is hookOnly (Helm waits for hooks, not for your Deployment), per the helm upgrade reference: "Use '--wait' alone for 'watcher' strategy" and "Default when flag is omitted: 'hookOnly'".

Definition: From the Helm 4.3 command reference: -i, --install ("if a release by this name doesn't already exist, run an install"); --rollback-on-failure ("if set, Helm will rollback the upgrade to previous success release upon failure. The --wait flag will be defaulted to "watcher" if --rollback-on-failure is set"); --timeout ("time to wait for any individual Kubernetes operation (like Jobs for hooks) (default 5m0s)"); --wait-for-jobs; --history-max (default 10); --cleanup-on-fail; --create-namespace; --server-side (true, false or auto, default auto = the release's previous method); --force-replace (Helm 3's --force); --take-ownership (adopt existing objects without Helm annotations). The Helm 4 overview lists the renames: "--atomic → --rollback-on-failure" and "--force → --force-replace"; the old flags "remain, but emit a deprecated warning". helm rollback <release> [revision] ("If this argument is omitted or set to 0, it will roll back to the previous release"), helm history (default --max 256), helm uninstall (deletes the release's objects and, unless --keep-history, its revision Secrets; CRDs and hook resources without a delete policy stay).

bash
# The deploy step used in this chapter's scripts/release.sh (expected, not run: needs a cluster)
helm upgrade --install orders-api oci://ghcr.io/acme/charts/orders-api --version 1.3.0 \
  --namespace shop-prod --create-namespace \
  -f charts/orders-api/values-prod.yaml \
  --rollback-on-failure --wait --timeout 5m \
  --history-max 10
helm test orders-api -n shop-prod --logs
helm history orders-api -n shop-prod --max 5
helm rollback orders-api 0 -n shop-prod --wait     # 0 = the previous revision
text
helm upgrade --install ... --rollback-on-failure --wait --timeout 5m, new image crash-loops
1  render, validate, pre-upgrade hooks (the Laravel chart: migrate Job, must complete)
2  patch Deployment -> new ReplicaSet; maxUnavailable 0 keeps every old pod serving
3  watcher strategy waits for the Deployment to become ready; the new pod never does
4  5m timeout -> revision N marked failed -> rollback to the last deployed revision as N+1
5  exit code non-zero: the pipeline stops, the cluster is back on the old ReplicaSet
   (the migration already ran: it must be backwards compatible, see Zero-Downtime Schema Migrations)

Real scenarios: a pipeline that runs helm install and fails on the second deploy with "cannot reuse a name that is still in use"; --atomic hiding the reason for a failure because the rollback deleted the failing pods (keep kubectl get events in the job log); a 5-minute default timeout shorter than a 10-minute migration hook; helm uninstall leaving a PVC and a CRD behind, by design.

FlagHelm 3Helm 4Use
--installyesyesIdempotent deploy step
--atomicundo on failure, implies --waitdeprecated alias of --rollback-on-failureCI deploys
--waitbuilt-in readiness checks (the logic Helm 4 keeps as legacy)strategies watcher (kstatus), hookOnly (default), legacyAlways in CI
--wait-for-jobsyesyesWait for chart Jobs too
--timeout5m0s5m0s, per operation (hooks too)Above the slowest hook
--history-max1010Bound Secret count
--server-siden/aauto (follow the release)Opt existing releases into SSA
--reuse-values / --reset-then-reuse-valuesyesyesOnly when you truly want last run's values

Fix: one helm upgrade --install with explicit values files, --rollback-on-failure --wait --timeout larger than the slowest hook, helm test right after, and the release history visible in the pipeline log.

Hooks: pre-install post-upgrade and the rest, hook weights, hook-delete-policy Must-know ​

In plain words: A hook is a resource (usually a Job) that Helm runs at a specific moment of a release, such as "before upgrading, run the database migration and wait for it". If the hook fails, the release fails.

Common misunderstanding: "Hooks are part of the release and are cleaned up with it." The hooks page: "The resources that a hook creates are currently not tracked or managed as part of the release." Without an annotation Helm applies the default policy before-hook-creation ("If no hook deletion policy annotation is specified, the before-hook-creation behavior applies by default"): the previous Job is deleted only when the next hook run creates its replacement, so the last Job (finished or failed) stays in the namespace between releases, and helm uninstall does not remove it.

Definition: The hook annotation helm.sh/hook takes one or more of pre-install ("Executes after templates are rendered, but before any resources are created in Kubernetes"), post-install, pre-delete, post-delete, pre-upgrade ("after templates are rendered, but before any resources are updated"), post-upgrade ("after all resources have been upgraded"), pre-rollback, post-rollback and test. "One resource can implement multiple hooks" (pre-install,pre-upgrade). helm.sh/hook-weight orders hooks: "Hook weights can be positive or negative numbers but must be represented as strings", sorted ascending; Helm sorts "by weight (assigning a weight of 0 by default), by resource kind and finally by name". For a Job or Pod, Helm "will wait until it successfully runs to completion. And if the hook fails, the release will fail." helm.sh/hook-delete-policy: before-hook-creation (delete the previous one before creating the new; "If no hook deletion policy annotation is specified, the before-hook-creation behavior applies by default"), hook-succeeded, hook-failed. The crd-install hook of Helm 2 "has been removed in favor of the crds/ directory".

text
helm upgrade shop ./shop-laravel   (job-migrate.yaml: hook pre-install,pre-upgrade, weight "-5",
                                   delete policy before-hook-creation,hook-succeeded)
1  render all templates; split hooks from the release manifest
2  pre-upgrade hooks sorted by weight: -5 migrate Job (any weight-0 hook would follow)
3  delete the old shop-shop-laravel-migrate Job (before-hook-creation), create the new one
4  wait: php artisan migrate --force --isolated runs in the NEW image (cache lock held meanwhile)
   exit 0 -> hook-succeeded: Helm deletes the Job      exit != 0 (backoffLimit 0) -> release failed,
                                                       Job kept (no hook-failed policy) for kubectl logs
5  only then the web, worker and scheduler workloads are patched to the new image

Real scenarios: the Laravel migration hook (this chapter's Laravel chart) that guarantees no new code runs on an old schema; a pre-install hook that references a ConfigMap the chart itself creates and fails on the first install because that ConfigMap does not exist yet (hooks run before the release's resources); a post-upgrade cache-warm Job; Argo CD, which "cannot know if it is running a first-time "install" or an "upgrade" - every operation is a "sync"", so pre-install and pre-upgrade hooks run on every sync.

HookRunsTypical useFails the release?
pre-installafter render, before any object existsSchema creation, one-time setupYes
post-installafter objects are created (after --wait if set)Seed data, notificationsYes
pre-upgradeafter render, before objects are updatedMigrations (php artisan migrate --force --isolated)Yes
post-upgradeafter objects are updatedCache warm-up, smoke testsYes
pre-delete / post-deletearound helm uninstallBackups, external cleanupYes
pre-rollback / post-rollbackaround helm rollbackDown-migrations (rarely safe)Yes
teston helm testConnectivity checksThe test run, not the release

Fix: give migration Jobs only what exists before the release (the image, inline env from a named template, an externally created Secret), set before-hook-creation,hook-succeeded, keep failed Jobs for logs, set activeDeadlineSeconds below --timeout, and write migrations that the old code tolerates (Zero-Downtime Schema Migrations).

Testing charts: helm lint, helm template with kubeconform, helm unittest, chart-testing ct, helm test, helm diff plugin Important ​

In plain words: Test a chart at four distances: does it render (lint), is the rendered YAML valid Kubernetes (kubeconform), does it render what you meant for given values (unit tests), and does it actually install and work (ct install plus helm test). Before a production upgrade, look at the diff.

Common misunderstanding: "helm lint passing means helm install will render." Lint runs the engine in lint mode, where required only warns. In Helm's engine source: "Don't fail on missing required values when linting". On this chapter's build host, helm lint --strict of the orders-api chart without an environment file printed level=WARN msg="missing required values" and 1 chart(s) linted, 0 chart(s) failed, while helm template of the same chart failed with config.databaseHost is required. Lint with each environment's values file.

Definition:

  • helm lint checks Chart.yaml, renders templates, validates the schema and the YAML; --strict turns warnings into failures; -f supplies values.
  • helm template renders locally; with kubeconform ("a Kubernetes manifest validation tool", in its README, which validates "over multiple routines" against schemas "for all recent versions of Kubernetes") the output is checked against the OpenAPI schemas of a given Kubernetes version: helm template ... | kubeconform -strict -summary -kubernetes-version 1.35.0.
  • helm unittest (plugin helm-unittest/helm-unittest): YAML test suites (keys suite, templates, tests, set, asserts) with assertions such as isKind, equal, matchRegex, notExists, failedTemplate; runs helm unittest charts/orders-api without a cluster.
  • chart-testing (ct): "ct lint" (Chart.yaml schema, maintainers, version increment against the target branch, helm lint) and "ct install" (installs changed charts into a cluster, runs helm test, uninstalls); usually in GitHub Actions with helm/chart-testing-action and a throwaway kind cluster from helm/kind-action. "Charts with type: library in their Chart.yaml cannot be installed, so ct install and ct lint-and-install skip the install step for them".
  • helm test <release> runs the chart's test hooks: "The container should exit successfully (exit 0) for a test to be considered a success."
  • helm diff (plugin databus23/helm-diff): helm diff upgrade shows the change an upgrade would make; --three-way-merge includes live-state drift; --detailed-exitcode: "return a non-zero exit code when there are changes" (2, per the README).
text
Pull request touches charts/orders-api (chart-ci.yml in this chapter)
1  ct lint --check-version-increment      chart version bumped? Chart.yaml valid? helm lint per ci/*.yaml
2  helm unittest charts/orders-api        5 tests: tag default, digest wins, no replicas with HPA, ...
3  helm template -f values-$env | kubeconform -strict   for dev, staging, prod
4  kind cluster -> ct install             real install, helm test, uninstall
5  merge -> tag -> helm package, helm push oci://..., cosign sign by digest

Real scenarios: a template that renders replicas: "3" (string) passes lint and fails kubeconform; a unit test that proves the selector never contains the version; ct install catching a readiness probe on the wrong port; helm diff --three-way-merge showing a kubectl edit someone made last night.

ToolNeeds a clusterCatchesCost
helm lint --strict -f values-env.yamlNoTemplate and schema errors, Chart.yaml problemsSeconds
helm template | kubeconform -strictNoInvalid Kubernetes fields, wrong typesSeconds
helm unittestNoLogic of your templates for given valuesSeconds
ct lintNoVersion bumps, maintainers, lint over changed chartsSeconds
ct install + helm testYes (kind)Real install, probes, hooks, testsMinutes
helm diff upgradeYes (read)Unintended changes before productionSeconds

Fix: the CI workflow runs all of them; the chapter's own Go tests additionally run the real Helm 4 CLI code on the build host.

Distributing charts: helm repo, index.yaml, OCI registry, helm push, helm pull, provenance, chart signing, Artifact Hub Important ​

In plain words: A chart is shipped as a versioned .tgz. Classic Helm repositories are web servers with an index.yaml catalogue; modern ones are OCI registries (the same ones that hold your images). A signature proves who published it.

Common misunderstanding: "helm repo add works for OCI registries." OCI registries have no index.yaml and are not added; you reference charts directly as oci://registry/path/chart with --version, after helm registry login (in Helm 4 with the domain only: "The helm registry login command must be done with the domain name only in v4").

Definition: A classic chart repository is "an HTTP server that houses an index.yaml file and optionally some packaged charts" (chart repository guide); helm repo index generates the index, helm repo add/update fetch it, helm search repo reads it. With an OCI registry, "When using helm push to upload a chart an OCI registry, the reference must be prefixed with oci:// and must not contain the basename or tag"; the basename comes from the chart name and the tag from its version. helm pull, helm show, helm template, helm install and helm upgrade accept oci://...; dependencies can point at oci://. Helm 4: "Install charts by digest for better supply chain security", e.g. oci://.../app@sha256:...; "Charts with non-matching digests are not installed." Provenance (classic): "Provenance files are generated at packaging time (helm package --sign ...), and can be checked by multiple commands, notably helm install --verify", using a PGP key pair; the .prov file sits next to the .tgz. For OCI charts, the registries page points to "The helm-sigstore plugin", and cosign signs the chart artefact by digest like an image. Artifact Hub is the CNCF catalogue of charts and other packages; it reads artifacthub.io/* annotations from Chart.yaml.

text
Release of orders-api chart 1.3.0 (ci/chart-ci.yml, publish job; expected, not run)
1  helm registry login ghcr.io -u $ACTOR --password-stdin
2  helm package charts/orders-api              -> dist/orders-api-1.3.0.tgz
3  helm push dist/orders-api-1.3.0.tgz oci://ghcr.io/acme/charts
     Pushed: ghcr.io/acme/charts/orders-api:1.3.0     Digest: sha256:<digest>
4  cosign sign --yes ghcr.io/acme/charts/orders-api@sha256:<digest>   (keyless, workflow OIDC identity)
5  Argo CD / Flux reference 1.3.0 (or the digest); policy verifies the signature before sync

Real scenarios: a company Harbor or GHCR hosting both images and charts under one auth model; Artifact Hub listing an operator chart with its images and a "signed" badge; a classic repository on GitHub Pages whose index.yaml grew to megabytes; Flux pulling charts with an OCIRepository source and a layerSelector for the chart media type application/vnd.cncf.helm.chart.content.v1.tar+gzip.

DistributionDiscoveryAuthSigning
Classic repo (HTTP + index.yaml)helm repo add, helm search repoBasic auth, client certs.prov files (PGP), helm verify
OCI registry (GHCR, ECR, Harbor, Docker Hub, GitLab)none built in; registry UIRegistry credentials, cloud IAMcosign / Notation by digest; helm-sigstore plugin
Git (path in a repo)Argo CD / Flux sourceGit credentialsSigned commits
Artifact HubWeb search, helm search hubn/a (catalogue only)Shows signatures and provenance

Fix: publish to the same OCI registry as the images, deploy by version (or digest in Helm 4), sign by digest in CI, and list public charts on Artifact Hub with artifacthub.io/changes and artifacthub.io/license annotations.

Kustomize: kustomization.yaml, resources, bases and overlays Must-know ​

In plain words: Kustomize reads a kustomization.yaml, loads the listed YAML files and directories, applies a fixed list of transformations (namespace, names, labels, images, patches, generated ConfigMaps) and prints the result. A base is a directory used by others; an overlay is a directory that uses a base and changes it.

Common misunderstanding: "Labels configured in the base (with includeSelectors: true) also reach resources an overlay adds." Transformations in a kustomization apply to the resources that kustomization loads, so the base's labels touch only the base's Deployment and Service. The prod overlay in this chapter added pdb.yaml with an empty selector, expecting the base's selector labels to fill it; the real kubectl kustomize overlays/prod output kept matchLabels: {} (the overlay's own labels did reach the PDB's metadata, but they have no includeSelectors), and Kubernetes' PDB docs say "An empty selector ({}) matches every pod in the namespace." The fix was to write the selector in pdb.yaml; an overlay-level labels entry with includeSelectors: true would also work, but would edit the base's selectors too.

Definition: From kubernetes.io: "A base is a directory with a kustomization.yaml, which contains a set of resources and associated customization", and "An overlay is a directory with a kustomization.yaml that refers to other kustomization directories as its bases. A base has no knowledge of an overlay and can be used in multiple overlays." Both live in resources: (the old bases: field "was deprecated in v2.1.0"; kustomize edit fix converts it). Kustomize is "a standalone tool to customize Kubernetes objects through a kustomization file", and "Since 1.14, kubectl also supports the management of Kubernetes objects using a kustomization file": kubectl kustomize <dir> renders, kubectl apply -k <dir> applies, kustomize build <dir> is the standalone equivalent (usually a newer Kustomize than the one compiled into kubectl). Remote bases (github.com/org/repo//path?ref=v1.2.0) are allowed; by default, files outside the kustomization root are not.

kustomize/orders-api: one base, one component, three overlaysbase/deployment.yaml service.yamlconfigMapGenerator (app.env)labels + includeSelectors, imagescomponents/hpakind: Component+ hpa.yamlremove /spec/replicasoverlays/devnamespace shop-devnamePrefix dev-newTag 1.5.0-rc.1, replicas 1secretGenerator (dev only)replacements: SELF_URLoverlays/stagingnamespace shop-stagingcomponents: hpanewTag 1.4.2generator behavior: mergeJSON 6902: maxReplicas 4overlays/prodnamespace shop-prodcomponents: hpa, + pdb.yamlimages: digest sha256:...strategic merge: spread, CPUJSON 6902: min 3, max 20resources: ../../base (solid), components: (dashed)kubectl kustomize overlays/prod (= kustomize build): plain YAML, ConfigMap orders-api-config-gdb27m5gh9references rewritten; new config = new name = new pod template = rollout. kubectl apply -k applies it.
text
kubectl kustomize overlays/prod   (real run on the build host, kubectl v1.36.1, Kustomize v5.8.1)
1  load ../../base: deployment.yaml, service.yaml; base labels + includeSelectors; generator app.env
2  load pdb.yaml (overlay resource: gets only the overlay's labels)
3  apply component ../../components/hpa: add hpa.yaml, JSON-patch "remove /spec/replicas"
4  merge generator literals APP_ENV=prod, DATABASE_HOST=... -> ConfigMap orders-api-config-gdb27m5gh9
5  namespace shop-prod everywhere; images: digest; patches (spread, CPU; HPA min 3 max 20)
6  rewrite the Deployment's configMapRef to the hashed name; print 5 objects

Real scenarios: one base, three overlays, reviewed as tiny diffs; a vendor's plain YAML (an ingress controller release) used as a remote base and patched locally; an overlay that sets namespace: and breaks a ClusterRoleBinding's subject namespace (Kustomize does update subjects[].namespace for ServiceAccounts it knows about; check the output); kubectl apply -k with an old embedded Kustomize that does not know a field the standalone binary supports.

Way to runVersionTypical use
kubectl kustomize dirCompiled into kubectl (v5.8.1 in kubectl 1.36.1 here)Local render, CI
kubectl apply -k dirsameDirect apply (no history, no pruning by default)
kustomize build dirStandalone release (v5.8.x)Newest features, plugins, --enable-helm
Argo CDBundled or custom Kustomize versionGitOps sync of an overlay path
Flux Kustomizationkustomize-controllerGitOps with pruning and health checks

Fix: keep the base environment-neutral and valid, keep overlays small, write selectors explicitly in resources that overlays add, and render every overlay in CI (scripts/kustomize-build-all.sh).

Patches: strategic merge patch, JSON 6902 patch, targets Must-know ​

In plain words: A strategic merge patch looks like a partial copy of the object with only the fields you want to change. A JSON 6902 patch is a list of operations (add, replace, remove) on paths. Use the first for "set these fields", the second for "remove this" or "change list item 0".

Common misunderstanding: "A strategic merge patch of containers: replaces the container list." For Kubernetes types it merges lists by their merge key (containers by name), so the patch's container named orders-api is merged into the existing one; a patch with a different name adds a second container. CRDs have no strategic merge metadata, so lists in custom resources are replaced; use JSON 6902 there.

Definition: "Patches (also called overlays) add or override fields on resources. They are provided using the patches Kustomization field." Each entry may be "either a strategic merge patch, or a JSON6902 patch", "either a file, or an inline string", and may "target a single resource or multiple resources" selected "by group, version, kind, name, namespace, labelSelector and annotationSelector"; name and namespace are "automatically anchored regular expressions". JSON 6902 operations come from RFC 6902: add, replace, copy, move, remove, test; paths use /, and a / inside a key is written ~1 (the helm-post overlay patches the annotation cluster-autoscaler.kubernetes.io~1safe-to-evict). For both patchesStrategicMerge and patchesJson6902 the reference says the "field was deprecated in v5.0.0"; kustomize edit fix migrates them to patches.

yaml
# overlays/dev: one strategic merge patch file and one inline JSON 6902 patch (full file below)
patches:
  - path: patch-dev-resources.yaml        # containers merge by name: only resources change
  - target:
      kind: Deployment
      name: orders-api
    patch: |-
      - op: add
        path: /spec/template/spec/containers/0/envFrom/-
        value:
          secretRef:
            name: orders-api-db
text
Same goal, two patch types: drop spec.replicas when an HPA takes over
strategic merge: "replicas: null" in a partial Deployment  (null deletes the field)
JSON 6902:       - op: remove, path: /spec/replicas          (components/hpa uses this)
1  JSON 6902 fails loudly if the path does not exist ("remove" of a missing field)
2  strategic merge silently does nothing if a field name is misspelled
3  JSON 6902 list indexes (/containers/0) break when someone reorders containers

Real scenarios: raising memory limits in prod with a five-line strategic merge patch; appending one env source with envFrom/- (JSON 6902 add to the end of a list); one patch applied to every Deployment by target: {kind: Deployment} to add a common annotation; a patch that targeted name: orders matching nothing because names are anchored (^orders$).

NeedPatch typeWhy
Change a few fields of a built-in typeStrategic mergeReadable, merges lists by key
Remove a field or list itemJSON 6902 removeExplicit; fails if absent
Append to a listJSON 6902 add .../-No merge key needed
Patch a CRD's listJSON 6902CRDs have no strategic merge keys
Same change on many objectsEither, with target selectorsRegex names, label selectors
Rename or change kindoptions: allowNameChange / allowKindChangeOff by default

Fix: strategic merge for additive tweaks, JSON 6902 for removals and appends, target for cross-cutting changes, and one small patch per concern (the reference: "Small patches that do one thing are best").

Transformers: images and newTag, replicas, namespace, namePrefix and nameSuffix, labels versus commonLabels Important ​

In plain words: These fields change things every object has: its image, its replica count, its namespace, its name and its labels, without writing patches.

Common misunderstanding: "commonLabels is the way to add a team label." It also adds the label to every selector, and selectors are immutable. The reference: "Selectors for resources such as Deployments and Services shouldn't be changed once the resource has been applied to a cluster. Changing commonLabels to live resources could result in failures." commonLabels "was deprecated in v5.0.0. Please use the [labels] field instead"; labels with includeSelectors: false (the default) adds labels without touching selectors.

Definition: images entries match the image name in the YAML (name: orders-api) and set newName, newTag or digest (this chapter's base turns the placeholder orders-api into ghcr.io/acme/orders-api:1.4.2, overlays change newTag or set a digest). replicas sets spec.replicas by name. namespace sets metadata.namespace on every namespaced object (and some references). namePrefix / nameSuffix rename every resource and update references Kustomize knows (Service selectors are labels, not names; configMapRef, secretRef, volume references, scaleTargetRef are names and are rewritten). labels takes pairs plus includeSelectors, includeTemplates and includeVolumeClaimTemplates (all false by default). commonAnnotations adds annotations.

text
overlays/dev: namePrefix dev- (real output, kubectl kustomize)
1  ConfigMap orders-api-config      -> dev-orders-api-config-f95gt5dfmk (prefix + hash)
2  Secret orders-api-db             -> dev-orders-api-db-gtfmg6gh7g
3  Service orders-api, Deployment orders-api -> dev-orders-api
4  envFrom configMapRef / secretRef in the Deployment rewritten to the new names
5  the string "http://placeholder" in the ConfigMap is NOT a reference: only replacements change it

Real scenarios: images: in an overlay bumped by an image-automation bot (kustomize edit set image ghcr.io/acme/orders-api:1.4.3); a namePrefix that makes two copies of an app coexist in one namespace for a preview; a team label added with commonLabels to a live app, and every Deployment apply rejected because spec.selector is immutable.

FieldTouches selectorsRewrites referencesDeprecated
labels (default)Non/aNo
labels + includeSelectors: trueYesn/aNo (use only in the base, once)
commonLabelsAlwaysn/aSince v5.0.0
namePrefix / nameSuffixNoYes (known name references)No
namespaceNoSome (e.g. RoleBinding subjects)No
imagesNon/aNo
replicasNon/aNo

Fix: labels with includeSelectors: true only in the base and never changed; environment labels without selectors in overlays; images and replicas through their fields rather than patches.

Generators: configMapGenerator, secretGenerator, hash suffix, behavior merge Must-know ​

In plain words: Instead of writing a ConfigMap by hand, you list its keys (from literals, .env files or files) and Kustomize builds it, appends a hash of the content to its name, and updates every reference. Change one value, and the name changes, the Deployment's pod template changes, and Kubernetes rolls out new pods.

Common misunderstanding: "secretGenerator keeps secrets safe." It base64-encodes what is in Git; it is only as secret as the repository. Use it for throwaway dev credentials (the dev overlay here does, and says so) and use External Secrets, SOPS or Sealed Secrets for real ones.

Definition: "Kustomize has secretGenerator and configMapGenerator, which generate Secret and ConfigMap from files or literals." "The generated ConfigMaps and Secrets have a content hash suffix appended. This ensures that a new ConfigMap or Secret is generated when the contents are changed. To disable the behavior of appending a suffix, one can use generatorOptions." Sources: literals, envs (.env files), files (one key per file). In an overlay, behavior: create (default), merge (add or override keys of the base's generator) or replace. generatorOptions sets disableNameSuffixHash, labels, annotations, immutable. Kustomize v5.0.0 removed a side effect where generators "loaded values from the local environment under some circumstances, breaking kustomize build's side-effect-free promise".

text
Change LOG_LEVEL in overlays/staging (generator behavior: merge)
1  old: orders-api-config-bfkd6m9m22 referenced by the Deployment's envFrom
2  new content -> new hash -> orders-api-config-<new hash>; envFrom rewritten
3  the pod template changed -> Deployment rollout -> new pods read the new values
4  the old ConfigMap stays until pruned (Argo CD prune / Flux prune / kubectl apply --prune)
   while old pods still run, they keep their old ConfigMap: rollback is clean

Real scenarios: a config change that "did nothing" because a hand-written ConfigMap kept its name and pods only read env at start; old hashed ConfigMaps piling up because the GitOps tool never prunes; an operator that expects a fixed ConfigMap name (disable the hash for that one generator); Helm's equivalent, the checksum/config annotation in the orders-api chart, which forces a rollout without renaming.

ApproachRolls out on changeOld version kept for rollbackName stable
Kustomize generator (hash suffix)YesYes, until prunedNo
Helm checksum/config annotationYesNo (same object updated)Yes
Plain ConfigMap, env varsNo (until pods restart)NoYes
Plain ConfigMap, mounted volumeFiles update in place, app must reloadNoYes
disableNameSuffixHash: trueNoNoYes

Fix: generate configuration with a hash suffix (or add the checksum annotation in Helm), enable pruning in the GitOps tool, and never put real secrets in a generator.

Components and replacements Important ​

In plain words: A component is a reusable optional feature (HPA on, monitoring on, external database on) that several overlays switch on with one line. A replacement copies a value from one object into another, for strings Kustomize does not understand as references.

Common misunderstanding: "Components are just bases." A base is a starting point loaded with resources:; a component (kind: Component, apiVersion: kustomize.config.k8s.io/v1alpha1) is applied on top of the including kustomization and can patch what the base produced, which is why the hpa component here can remove spec.replicas from the base's Deployment.

Definition: The components guide: components allow "one to define reusable pieces of configuration logic that can be included from multiple overlays". replacements take a source (by kind, name, fieldPath, optional options such as delimiter and index) and targets (select plus fieldPaths); they replaced the older vars. In this chapter's dev overlay, a replacement copies the Service's final name (after namePrefix) into the third /-separated segment of SELF_URL: the real output is SELF_URL: http://dev-orders-api.

yaml
# overlays/dev/kustomization.yaml (excerpt)
replacements:
  - source:
      kind: Service
      name: orders-api
      fieldPath: metadata.name
    targets:
      - select:
          kind: ConfigMap
          name: orders-api-config
        fieldPaths:
          - data.SELF_URL
        options:
          delimiter: "/"
          index: 2
text
Who includes components/hpa
1  dev:      no   -> Deployment keeps replicas: 1 (from replicas:), no HPA
2  staging:  yes  -> HPA added (min 2, max 4 after a JSON patch), spec.replicas removed
3  prod:     yes  -> HPA added (min 3, max 20), spec.replicas removed, PDB added by prod itself

Real scenarios: an external-db component that adds a Secret reference and removes a sidecar Postgres for staging and prod; a monitoring component adding ServiceMonitor objects for clusters that run Prometheus Operator; a replacement that copies the image tag into an APP_VERSION env var.

ToolScopeTypical use
Base (resources:)Starting pointThe app itself
Component (components:)Optional, reusable, patches the resultHPA, monitoring, external DB
OverlayOne environmentNamespace, tags, sizes
replacementsField-to-field copyNames inside strings, versions in env
PatchField editsSizes, probes, env

Fix: one component per optional feature, included only where needed; replacements instead of hard-coded prefixed names.

Helm vs Kustomize, and both: helm template piped to kustomize, post-renderers, Argo CD and Flux Must-know ​

In plain words: Helm is best when you distribute software to people who should only touch a few knobs (a values API) and when you want releases with rollback. Kustomize is best for your own manifests across a few environments, when everyone can read plain YAML. Many teams use Helm for third-party software and Kustomize for their apps, or render a chart and patch the result.

Common misunderstanding: "Argo CD runs Helm, so my releases show up in helm list." Argo CD's docs: "Helm is only used to inflate charts with helm template. The lifecycle of the application is handled by Argo CD instead of Helm." No release Secrets, no helm rollback; Helm hooks are mapped onto Argo CD sync hooks ("This is annotation compatibility, not a guarantee that hook lifecycle semantics are identical to Helm's"). Flux's helm-controller, by contrast, performs real Helm installs and upgrades, so the release exists and Flux adds drift detection and remediation.

Definition:

  • Helm alone: templates + values + releases; --post-renderer lets an external step modify the rendered manifests before apply (in Helm 4 a post-renderer must be a plugin: "it is no longer possible to pass an executable directly to helm render --post-renderer, but a plugin name must be passed").
  • Kustomize alone: plain YAML + overlays; no releases, no hooks (use Jobs and GitOps sync waves), no parameters.
  • helm template piped to kustomize: render the chart, then treat the output as a Kustomize resource (this chapter's kustomize/helm-post), or let Kustomize call Helm with the helmCharts field (kustomize build --enable-helm). You lose Helm's release and hooks; you gain last-mile patches the chart has no values for.
  • Argo CD: detects Helm (Chart.yaml) or Kustomize (kustomization.yaml) sources; Helm sources take valueFiles, values, valuesObject, parameters (precedence "parameters > valuesObject > values > valueFiles > helm repository values.yaml"); Kustomize sources take images, namePrefix, commonLabels and more in the Application.
  • Flux: HelmRelease (helm.toolkit.fluxcd.io/v2, chart from a HelmRepository or OCIRepository, install.remediation.retries, driftDetection) and Kustomization (kustomize.toolkit.fluxcd.io/v1, a Flux CRD that runs kustomize build on a Git path, with prune, wait, health checks); "Flux HelmRelease Kustomization" pairs are the usual Flux layout.
text
helm template piped to kustomize (real run: scripts/render-charts.sh, then kubectl kustomize helm-post)
1  helm template orders-api charts/orders-api -n shop-prod -f values-prod.yaml --skip-tests
     6 objects; note: no metadata.namespace in the output (0 "namespace:" lines)
2  kustomize/helm-post: resources [orders-api.rendered.yaml], labels cost-center, JSON patch adds
     the safe-to-evict annotation the chart does not expose
3  kubectl kustomize kustomize/helm-post -> 6 objects with the label and the annotation
4  apply with namespace set by the GitOps tool or a namespace: field; hooks are gone:
     a migration hook in such a chart would now be an ordinary Job (or must be dropped)

Real scenarios: an ingress controller installed from its upstream Helm chart, with two Kustomize patches for a node selector the chart lacks; the shop's own services as Kustomize overlays reconciled by Argo CD; a vendor chart rendered once into Git ("hydrated manifests") so reviewers see the actual YAML diff of every upgrade.

QuestionHelmKustomizeHelm + Kustomize
Distribute to other teams/companiesStrong (values API, versions, repos)Weak (patch anything)Helm
Your own app, 3 environmentsGoodStrong (plain YAML)Either
Readability of the sourceTemplatesPlain YAMLBoth
Release history, rollbackYesNo (Git is the history)No (when rendered)
Hooks (migrations)YesNo (Jobs, sync waves)Lost when rendered
Last-mile patch of a third-party chartOnly if the chart exposes itn/aYes
Argo CDRendered via helm templateNativePlugin or --enable-helm
FluxReal releases (helm-controller)Native (kustomize-controller)HelmRelease post-renderers (Kustomize patches)

Fix: pick per artefact, not per company: charts for things you publish or install from others, overlays for your own services, and the hybrid only when a chart lacks a knob you cannot get upstream.

Pitfalls: CRD upgrade pitfalls, immutable fields, selector immutability, big values files Important ​

In plain words: A few Kubernetes rules make packaging mistakes permanent: CRDs are global and Helm will not touch them after install, and some fields (Deployment selectors, Job templates, Service clusterIP) cannot be changed in place at all.

Common misunderstanding: "If an upgrade fails on an immutable field, --force fixes it." --force-replace (Helm 4; --force in Helm 3) deletes and recreates the object, which for a Deployment means downtime and for a Service a new cluster IP. The real fix is not changing the field.

Definition:

  • CRD upgrade pitfalls. "CRDs are never reinstalled", "never installed on upgrade or rollback", "never deleted. Deleting a CRD automatically deletes all of the CRD's contents across all namespaces in the cluster." Options: upgrade CRDs with kubectl apply --server-side -f crds/ as a separate pipeline step before helm upgrade; a separate CRD chart whose CRDs are in templates/ (then Helm does upgrade and could delete them: add helm.sh/resource-policy: keep); or let the operator manage its CRDs. Versioning rules for CRDs are in Extending Kubernetes.
  • Immutable fields. spec.selector of Deployments, StatefulSets and DaemonSets; spec.template of a Job; StatefulSet volumeClaimTemplates and serviceName; a Service's clusterIP; most PVC specs. An upgrade that changes them fails with field is immutable.
  • Selector immutability. Never put a changing label (app.kubernetes.io/version, helm.sh/chart) into a selector; never add commonLabels to a live app. The charts here split selectorLabels from labels, and manifestcheck fails a render that puts a version into a selector.
  • Big values files. Every field exposed as a value is a public API you must keep; a 2,000-line values.yaml usually means the chart is a template for raw YAML. Prefer a small surface, extraEnv/extraVolumes style escape hatches, and a schema.
  • Replicas versus HPA. If the chart renders spec.replicas, every upgrade resets the HPA's choice (with client-side apply). Omit replicas when autoscaling is enabled (both charts and the hpa component do).
text
Upgrade that adds app.kubernetes.io/version to the Deployment selector
1  helm upgrade renders spec.selector.matchLabels with version "1.4.3"
2  patch sent to the API server -> 422: spec.selector: Invalid value ... field is immutable
3  --rollback-on-failure: nothing changed (the patch was rejected) -> revision failed
4  only ways forward: revert the template, or delete the Deployment (--force-replace) and accept
   a gap in serving, or create a NEW Deployment name and move traffic (Deployment Strategies)

Real scenarios: an operator chart upgraded for months while its CRDs stayed at the first installed version; a Job hook renamed per revision (migrate-{revision}) to dodge "field is immutable" on its template, piling up Jobs; a values refactor that renames image.tag to image.version and silently ignores everyone's old values (the schema with additionalProperties: false turns that into an error).

PitfallSymptomPrevention
CRD in crds/ changedNew fields ignored by the API serverSeparate CRD upgrade step or CRD chart with resource-policy: keep
Version label in selectorfield is immutable on upgradeselectorLabels without version; unit test; manifestcheck
commonLabels added laterSamelabels without includeSelectors
Job template changedfield is immutable for JobsHook with before-hook-creation
Replicas + HPAScale drops on every deployOmit replicas when autoscaling
Huge values fileUnreviewable diffs, broken overridesSmall API + schema + escape hatches
Release Secret > 1 MBInstall failsFewer embedded files; SQL backend

Mechanics ​

What helm template and helm install do, step by step ​

The order below follows Install.RunWithContext in the saved Helm v4.0.5 source (src-v4.0.5-pkg_action_install.go.txt, line numbers in brackets), plus pkg/engine and kind_sorter.go. The CLI (pkg/cmd/install.go) has already loaded the chart, refused type: library and merged the user's -f / --set values before this runs.

text
helm install shop ./shop-laravel -n shop-prod -f values-prod.yaml
1  [286] ProcessDependencies: apply condition/tags, drop disabled subcharts
2  [290-299] install CRDs from crds/ FIRST, "before Helm contacts the upstream server and builds
   the capabilities object" (skipped with --skip-crds; on a client-only dry run only a warning)
3  [305-325] capabilities: from the cluster, or the compiled-in default (+ --kube-version) for
   helm template; kubeVersion of Chart.yaml is checked against them
4  [339] ToRenderValuesWithSchemaValidation: coalesce chart defaults <- parent values <- user values
   (null deletes), build .Values .Release .Chart .Capabilities, validate values.schema.json
5  [348] create the release object (status pending-install)
6  [351] renderResources, which returns hooks, manifest AND rel.Info.Notes in one pass:
   all templates of chart + subcharts in one set (define names are global), non-underscore files
   executed, "<no value>" stripped, required/fail abort here; NOTES.txt rendered here too;
   split by helm.sh/hook; manifests sorted by kind (InstallOrder: PriorityClass, Namespace,
   NetworkPolicy, ResourceQuota, LimitRange, PodSecurityPolicy, PodDisruptionBudget, ...)
7  [483] pre-install hooks by weight, each Job/Pod waited for
8  [492-503] create the manifest objects (Helm 4: server-side apply for a new release)
9  [509-518] --wait / --wait-for-jobs per strategy
10 [524] post-install hooks; [530] status deployed, release Secret stored; the CLI prints the
   already-rendered notes
helm template = the same path as a client-only dry run: no CRD install, no hooks executed; it prints
manifests, then hooks (unless --skip-tests / --no-hooks)

What helm upgrade does ​

text
helm upgrade shop ./shop-laravel -f values-prod.yaml --rollback-on-failure --wait --timeout 5m
1  find the last release; refuse if one is pending ("another operation (install/upgrade/rollback) is in
   progress"); with --install and no release, run an install instead
2  values: new values given -> use only them (plus chart defaults); none given -> copy the last
   release's values; --reuse-values / --reset-values / --reset-then-reuse-values override this
3  render as above; create revision N+1 with status pending-upgrade
4  pre-upgrade hooks by weight; each Job must complete
5  for each object: client-side apply = three-way strategic merge (old manifest, live, new);
   server-side apply = send the new object, field ownership decides conflicts (--force-conflicts)
6  delete objects that were in the old manifest and are not in the new one (unless resource-policy keep)
7  wait; post-upgrade hooks; old revision -> superseded, new -> deployed; prune to --history-max
8  any failure: new revision -> failed; with --rollback-on-failure: rollback to the last
   successful revision, recorded as revision N+2 "Rollback to N"

How Kustomize builds an overlay ​

text
kubectl kustomize overlays/staging
1  read kustomization.yaml; recursively build every entry of resources (../../base is built first,
   with the base's own labels, generators and images applied to the base's own objects)
2  run the overlay's generators (configMapGenerator behavior: merge combines with the base's)
3  apply components (components/hpa: add hpa.yaml, apply its patches to the accumulated objects)
4  apply the overlay's transformers: namespace, namePrefix/nameSuffix, labels, images, replicas, patches
5  apply replacements
6  fix up name references (configMapRef, secretRef, scaleTargetRef, volumes) to final, hashed names
7  print, sorted in Kustomize's default kind order (observed: ConfigMap, Secret, Service, Deployment,
   PodDisruptionBudget, HorizontalPodAutoscaler)

Knobs ​

KnobWhereDefaultNotes
--timeoutinstall / upgrade / rollback / test5m0sPer Kubernetes operation, hooks included
--waitinstall / upgradeHelm 4: hookOnly when omitted; watcher when given alone--rollback-on-failure defaults it to watcher
--history-maxupgrade100 = unlimited
--server-sideinstall / upgradeinstall: true for new releases; upgrade: autoHelm 4
HELM_DRIVERenvsecretconfigmap, sql (beta), memory
--kube-versiontemplate / lintcompiled-in (client-go major+1, minor)A module build without ldflags says v1.20.0
--skip-tests / --no-hookstemplateoffUse before piping to kubectl or kustomize
--strictlintoffWarnings fail; required still only warns
helm.sh/hook-weightannotation"0"Strings; ascending
helm.sh/hook-delete-policyannotationbefore-hook-creationPlus hook-succeeded, hook-failed
helm.sh/resource-policy: keepannotationunsetHelm will not delete the object
generatorOptions.disableNameSuffixHashkustomizationfalseStable names, no automatic rollout
labels[].includeSelectorskustomizationfalsetrue only in the base
kustomize build --enable-helmCLIoffEnables the helmCharts field
--load-restrictorkustomize CLILoadRestrictionsRootOnlyFiles outside the root need LoadRestrictionsNone

Error messages you will actually see ​

MessageMeaningFix
Error: execution error at (orders-api/templates/deployment.yaml:25:28): config.databaseHost is required: ... (real, this chapter)A required failed; the position is where the template was included (the checksum annotation)Supply the value in the environment's file
values don't meet the specifications of the schema(s) ... - at '/config/appEnv': value must be one of 'dev', 'staging', 'prod' (real)Schema validationFix the value; the message names the path
Error: library charts are not installable (real)type: libraryUse it as a dependency
chart requires kubeVersion: >=1.30.0-0 which is incompatible with Kubernetes v1.20.0 (real, module build without ldflags)kubeVersion constraint vs target version--kube-version, or build Helm with its release ldflags
UPGRADE FAILED: another operation (install/upgrade/rollback) is in progressA previous run died with the release pending-*helm history, then helm rollback to the last good revision
UPGRADE FAILED: "x" has no deployed releasesOnly failed revisions existhelm upgrade --install handles first installs; otherwise uninstall/rollback
cannot reuse a name that is still in usehelm install of an existing releasehelm upgrade --install
... exists and cannot be imported into the current release: invalid ownership metadata; ...Object exists without Helm's labels/annotationsDelete it, annotate it, or Helm 4 --take-ownership
spec.selector: Invalid value: ... field is immutableSelector or Job template changedRevert; never version selectors
UPGRADE FAILED: ... resource mapping not found ... ensure CRDs are installed firstA CR rendered before its CRD exists (CRD in templates or not installed)CRDs in crds/ or a separate step
accumulating resources from '/etc/hosts': security; file '/etc/hosts' is not in or below '.../ov' (real, Kustomize)Resource outside the kustomization rootMove it in, or --load-restrictor LoadRestrictionsNone knowingly
no resource matches strategic merge patch "Deployment.v1.apps/orders.[noNs]": no matches for Id ...; failed to find unique target for patch ... (real, Kustomize)Patch names orders, the base has orders-apiMatch the base's names; check kubectl kustomize of the base

Go ​

The Go side has three parts: the orders-api chart (the Go service from Images & Dockerfiles, packaged with an HPA, PDB, ConfigMap and ServiceAccount), the application code that consumes what the chart renders, and Go tests that run the real Helm 4 CLI code against both charts, because the build host has no helm binary.

Before ​

Three copies of the same Deployment, one per environment, kept in sync by hand. The diff between them is what a chart or an overlay makes explicit:

yaml
# k8s/prod/deployment.yaml (copied from k8s/staging/, which was copied from k8s/dev/)
apiVersion: apps/v1
kind: Deployment
metadata:
  name: orders-api
  labels:
    app: orders-api
    version: "1.4.2"          # changes every release
spec:
  replicas: 3                 # fights the HPA that someone added later in prod only
  selector:
    matchLabels:
      app: orders-api
      version: "1.4.2"        # immutable: the next release cannot be applied
  template:
    metadata:
      labels:
        app: orders-api
        version: "1.4.2"
    spec:
      containers:
        - name: orders-api
          image: ghcr.io/acme/orders-api:latest   # dev was fixed to a tag; prod was not
          env:
            - name: DATABASE_HOST
              value: orders-db.prod.internal
            - name: DATABASE_PASSWORD
              value: hunter2                      # a secret in Git, in three copies

After ​

The chart's identity, defaults, schema and per-environment values:

yaml
# Chart.yaml: identity and metadata of the chart (apiVersion v2 = Helm 3 and Helm 4 charts)
apiVersion: v2
name: orders-api
description: The shop's orders API, a stdlib Go HTTP service (see Images & Dockerfiles)
type: application
# version = the chart's own SemVer; bump it on every change to templates or defaults
version: 1.3.0
# appVersion = the application version the chart deploys by default (image tag fallback)
appVersion: "1.4.2"
kubeVersion: ">=1.30.0-0"
home: https://github.com/acme/orders-api
sources:
  - https://github.com/acme/orders-api
maintainers:
  - name: platform-team
    email: platform@example.test
keywords:
  - orders
  - go
annotations:
  artifacthub.io/license: Apache-2.0
  artifacthub.io/changes: |
    - kind: changed
      description: HPA behavior block made configurable
yaml
# Default values for orders-api. Every key here is documented and has a safe default;
# per-environment files (values-dev.yaml, values-staging.yaml, values-prod.yaml) override them.

nameOverride: ""
fullnameOverride: ""

# replicaCount is ignored when autoscaling.enabled is true (the HPA owns spec.replicas)
replicaCount: 2

image:
  repository: ghcr.io/acme/orders-api
  # tag defaults to .Chart.AppVersion; quote it so YAML never turns 1.10 into the float 1.1
  tag: ""
  # digest wins over tag when set (sha256:...); deploy digests, read tags
  digest: ""
  pullPolicy: IfNotPresent

serviceAccount:
  create: true
  name: ""
  annotations: {}

podAnnotations: {}
podLabels: {}

service:
  type: ClusterIP
  port: 80
  targetPort: 8080

# Non-secret configuration, rendered into a ConfigMap and loaded with envFrom.
# Secrets never go here: reference a Secret created outside the chart (existingSecret).
config:
  appEnv: dev
  logLevel: info
  # required: the template fails the render if this stays empty
  databaseHost: ""
  shutdownTimeout: 8s
  extra: {}

# Name of a Secret that already exists in the namespace (External Secrets Operator, SOPS, Vault)
existingSecret: ""

# Extra env vars; values may contain templates, rendered with tpl (for example the namespace)
extraEnv: {}

terminationGracePeriodSeconds: 30

resources:
  requests:
    cpu: 100m
    memory: 64Mi
  limits:
    memory: 128Mi

autoscaling:
  enabled: false
  minReplicas: 2
  maxReplicas: 10
  targetCPUUtilizationPercentage: 70
  # scale-down stabilisation (seconds) so a short dip does not remove pods
  scaleDownStabilizationSeconds: 300

podDisruptionBudget:
  enabled: false
  maxUnavailable: 1

nodeSelector: {}
tolerations: []
topologySpreadConstraints: []
yaml
# values-prod.yaml: production deploys pin the image by digest (written by CI or a GitOps bot)
image:
  tag: "1.4.2"
  # placeholder digest for the example; CI writes the real one after the push
  digest: "sha256:0b7e2a3c5d9f41e6a8b1c2d3e4f5a6b7c8d9e0f1a2b3c4d5e6f7a8b9c0d1e2f3"
config:
  appEnv: prod
  logLevel: info
  databaseHost: orders-db.prod.internal
existingSecret: orders-api-db
extraEnv:
  # tpl renders this string as a template: the value becomes the release namespace
  OTEL_RESOURCE_ATTRIBUTES: "deployment.environment=prod,k8s.namespace.name={{ .Release.Namespace }}"
resources:
  requests:
    cpu: 250m
    memory: 128Mi
  limits:
    memory: 256Mi
autoscaling:
  enabled: true
  minReplicas: 3
  maxReplicas: 20
  targetCPUUtilizationPercentage: 65
podDisruptionBudget:
  enabled: true
  maxUnavailable: 1
topologySpreadConstraints:
  - maxSkew: 1
    topologyKey: topology.kubernetes.io/zone
    whenUnsatisfiable: ScheduleAnyway
json
{
  "$schema": "https://json-schema.org/draft-07/schema#",
  "title": "orders-api values",
  "type": "object",
  "required": ["image", "service", "config", "resources"],
  "properties": {
    "replicaCount": { "type": "integer", "minimum": 1 },
    "image": {
      "type": "object",
      "required": ["repository"],
      "properties": {
        "repository": { "type": "string", "minLength": 1 },
        "tag": { "type": "string" },
        "digest": { "type": "string", "pattern": "^(sha256:[a-f0-9]{64})?$" },
        "pullPolicy": { "enum": ["Always", "IfNotPresent", "Never"] }
      },
      "additionalProperties": false
    },
    "service": {
      "type": "object",
      "properties": {
        "type": { "enum": ["ClusterIP", "NodePort", "LoadBalancer"] },
        "port": { "type": "integer", "minimum": 1, "maximum": 65535 },
        "targetPort": { "type": "integer", "minimum": 1024, "maximum": 65535 }
      }
    },
    "config": {
      "type": "object",
      "required": ["appEnv"],
      "properties": {
        "appEnv": { "enum": ["dev", "staging", "prod"] },
        "logLevel": { "enum": ["debug", "info", "warn", "error"] },
        "databaseHost": { "type": "string" },
        "shutdownTimeout": { "type": "string", "pattern": "^[0-9]+(ms|s|m)$" },
        "extra": { "type": "object", "additionalProperties": { "type": "string" } }
      },
      "not": {
        "anyOf": [
          { "required": ["databasePassword"] },
          { "required": ["password"] }
        ]
      }
    },
    "existingSecret": { "type": "string" },
    "extraEnv": { "type": "object", "additionalProperties": { "type": "string" } },
    "resources": {
      "type": "object",
      "required": ["requests"],
      "properties": {
        "requests": { "type": "object", "required": ["cpu", "memory"] },
        "limits": { "type": "object" }
      }
    },
    "autoscaling": {
      "type": "object",
      "properties": {
        "enabled": { "type": "boolean" },
        "minReplicas": { "type": "integer", "minimum": 1 },
        "maxReplicas": { "type": "integer", "minimum": 1 },
        "targetCPUUtilizationPercentage": { "type": "integer", "minimum": 1, "maximum": 100 },
        "scaleDownStabilizationSeconds": { "type": "integer", "minimum": 0 }
      }
    }
  }
}

The named templates (selector labels kept apart from the full label set; digest beats tag; required on the repository):

text
{{/*
Named templates for orders-api. Files starting with an underscore render no manifest;
they only hold "define" blocks that other templates call with include.
*/}}

{{/* Chart name, overridable, cut to the 63-character DNS label limit. */}}
{{- define "orders-api.name" -}}
{{- default .Chart.Name .Values.nameOverride | trunc 63 | trimSuffix "-" }}
{{- end }}

{{/*
Fully qualified app name: release name + chart name, unless the release name already
contains the chart name ("orders-api" installed as "orders-api" stays "orders-api").
*/}}
{{- define "orders-api.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 }}

{{/* "orders-api-1.3.0", with "+" (SemVer build metadata) made label-safe. */}}
{{- define "orders-api.chart" -}}
{{- printf "%s-%s" .Chart.Name .Chart.Version | replace "+" "_" | trunc 63 | trimSuffix "-" }}
{{- end }}

{{/*
Selector labels: the ONLY labels used in spec.selector. They never contain a version,
because Deployment selectors are immutable after creation.
*/}}
{{- define "orders-api.selectorLabels" -}}
app.kubernetes.io/name: {{ include "orders-api.name" . }}
app.kubernetes.io/instance: {{ .Release.Name }}
{{- end }}

{{/* Full label set for metadata.labels (may change on every upgrade). */}}
{{- define "orders-api.labels" -}}
helm.sh/chart: {{ include "orders-api.chart" . }}
{{ include "orders-api.selectorLabels" . }}
app.kubernetes.io/version: {{ .Values.image.tag | default .Chart.AppVersion | quote }}
app.kubernetes.io/managed-by: {{ .Release.Service }}
app.kubernetes.io/part-of: shop
{{- end }}

{{/* Image reference: digest beats tag; an empty repository fails the render. */}}
{{- define "orders-api.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) -}}
{{- end -}}
{{- end }}

{{- define "orders-api.serviceAccountName" -}}
{{- if .Values.serviceAccount.create }}
{{- default (include "orders-api.fullname" .) .Values.serviceAccount.name }}
{{- else }}
{{- default "default" .Values.serviceAccount.name }}
{{- end }}
{{- end }}

The Deployment (no replicas when the HPA is on, checksum annotation for config rollouts, tpl for templated env values, with blocks for optional maps), the ConfigMap with its required database host, and the HPA:

yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: {{ include "orders-api.fullname" . }}
  labels:
    {{- include "orders-api.labels" . | nindent 4 }}
spec:
  {{- if not .Values.autoscaling.enabled }}
  {{- /* With an HPA, spec.replicas is left out so an upgrade never resets the scaled count. */}}
  replicas: {{ .Values.replicaCount }}
  {{- end }}
  revisionHistoryLimit: 5
  strategy:
    type: RollingUpdate
    rollingUpdate:
      maxSurge: 25%
      maxUnavailable: 0
  selector:
    matchLabels:
      {{- include "orders-api.selectorLabels" . | nindent 6 }}
  template:
    metadata:
      annotations:
        {{- /* A changed ConfigMap changes this hash, so the pod template changes: a rollout. */}}
        checksum/config: {{ include (print $.Template.BasePath "/configmap.yaml") . | sha256sum }}
        {{- with .Values.podAnnotations }}
        {{- toYaml . | nindent 8 }}
        {{- end }}
      labels:
        {{- include "orders-api.labels" . | nindent 8 }}
        {{- with .Values.podLabels }}
        {{- toYaml . | nindent 8 }}
        {{- end }}
    spec:
      serviceAccountName: {{ include "orders-api.serviceAccountName" . }}
      automountServiceAccountToken: false
      terminationGracePeriodSeconds: {{ .Values.terminationGracePeriodSeconds }}
      securityContext:
        runAsNonRoot: true
        runAsUser: 65532
        runAsGroup: 65532
        seccompProfile:
          type: RuntimeDefault
      containers:
        - name: orders-api
          image: {{ include "orders-api.image" . | quote }}
          imagePullPolicy: {{ .Values.image.pullPolicy }}
          ports:
            - name: http
              containerPort: {{ .Values.service.targetPort }}
              protocol: TCP
          envFrom:
            - configMapRef:
                name: {{ include "orders-api.fullname" . }}
            {{- with .Values.existingSecret }}
            - secretRef:
                name: {{ . }}
            {{- end }}
          env:
            - name: PORT
              value: {{ .Values.service.targetPort | quote }}
            - name: APP_VERSION
              value: {{ .Values.image.tag | default .Chart.AppVersion | quote }}
            {{- range $name, $value := .Values.extraEnv }}
            - name: {{ $name }}
              value: {{ tpl $value $ | quote }}
            {{- end }}
          startupProbe:
            httpGet:
              path: /healthz
              port: http
            periodSeconds: 2
            failureThreshold: 15
          readinessProbe:
            httpGet:
              path: /readyz
              port: http
            periodSeconds: 5
          livenessProbe:
            httpGet:
              path: /healthz
              port: http
            periodSeconds: 10
          resources:
            {{- toYaml .Values.resources | nindent 12 }}
          securityContext:
            allowPrivilegeEscalation: false
            readOnlyRootFilesystem: true
            capabilities:
              drop: ["ALL"]
      {{- with .Values.nodeSelector }}
      nodeSelector:
        {{- toYaml . | nindent 8 }}
      {{- end }}
      {{- with .Values.tolerations }}
      tolerations:
        {{- toYaml . | nindent 8 }}
      {{- end }}
      {{- with .Values.topologySpreadConstraints }}
      topologySpreadConstraints:
        {{- range . }}
        - labelSelector:
            matchLabels:
              {{- include "orders-api.selectorLabels" $ | nindent 14 }}
          {{- toYaml . | nindent 10 }}
        {{- end }}
      {{- end }}
yaml
{{- /* Non-secret settings, loaded into the container with envFrom. */ -}}
apiVersion: v1
kind: ConfigMap
metadata:
  name: {{ include "orders-api.fullname" . }}
  labels:
    {{- include "orders-api.labels" . | nindent 4 }}
data:
  APP_ENV: {{ .Values.config.appEnv | quote }}
  LOG_LEVEL: {{ .Values.config.logLevel | default "info" | quote }}
  DATABASE_HOST: {{ required "config.databaseHost is required: set it in the environment's values file" .Values.config.databaseHost | quote }}
  SHUTDOWN_TIMEOUT: {{ .Values.config.shutdownTimeout | quote }}
  {{- range $key, $value := .Values.config.extra }}
  {{ $key }}: {{ $value | quote }}
  {{- end }}
yaml
{{- if .Values.autoscaling.enabled }}
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
  name: {{ include "orders-api.fullname" . }}
  labels:
    {{- include "orders-api.labels" . | nindent 4 }}
spec:
  scaleTargetRef:
    apiVersion: apps/v1
    kind: Deployment
    name: {{ include "orders-api.fullname" . }}
  minReplicas: {{ .Values.autoscaling.minReplicas }}
  maxReplicas: {{ .Values.autoscaling.maxReplicas }}
  metrics:
    - type: Resource
      resource:
        name: cpu
        target:
          type: Utilization
          averageUtilization: {{ .Values.autoscaling.targetCPUUtilizationPercentage }}
  behavior:
    scaleDown:
      stabilizationWindowSeconds: {{ .Values.autoscaling.scaleDownStabilizationSeconds }}
{{- end }}

The Service, PDB and ServiceAccount are in the same directory (service.yaml, pdb.yaml, serviceaccount.yaml). The user-facing notes, the helm test Pod, the .helmignore with the anchored /tests/, and the helm-unittest suite:

text
{{ include "orders-api.fullname" . }} {{ .Values.image.tag | default .Chart.AppVersion }} is {{ if .Release.IsInstall }}installed{{ else }}upgraded (revision {{ .Release.Revision }}){{ end }} in namespace {{ .Release.Namespace }}.

Image: {{ include "orders-api.image" . }}
{{- if .Values.autoscaling.enabled }}
Replicas: managed by the HPA ({{ .Values.autoscaling.minReplicas }}-{{ .Values.autoscaling.maxReplicas }}).
{{- else }}
Replicas: {{ .Values.replicaCount }}.
{{- end }}
{{- if not .Values.existingSecret }}

WARNING: existingSecret is empty, so the pods start without database credentials.
{{- end }}

Try it:
  kubectl -n {{ .Release.Namespace }} port-forward svc/{{ include "orders-api.fullname" . }} 8080:{{ .Values.service.port }}
  curl -s localhost:8080/version
  helm test {{ .Release.Name }} -n {{ .Release.Namespace }}
yaml
{{- /* Run with: helm test <release>. A Pod that exits 0 = pass. */ -}}
apiVersion: v1
kind: Pod
metadata:
  name: {{ include "orders-api.fullname" . }}-test-readyz
  labels:
    {{- include "orders-api.labels" . | nindent 4 }}
  annotations:
    "helm.sh/hook": test
    "helm.sh/hook-delete-policy": before-hook-creation,hook-succeeded
spec:
  restartPolicy: Never
  securityContext:
    runAsNonRoot: true
    runAsUser: 65532
  containers:
    - name: wget
      image: busybox:1.37
      command: ["wget", "-q", "-O-", "http://{{ include "orders-api.fullname" . }}:{{ .Values.service.port }}/readyz"]
text
# Paths Helm skips when it loads the chart (package, install, template). filepath.Match globs:
# like .gitignore, but no "**"
.git/
*.swp
*.bak
*.tmp
.idea/
.vscode/
# helm-unittest suites stay out of the package. The leading slash matters: a bare "tests/"
# also matches templates/tests/ and silently drops the helm test Pods from every render.
/tests/
yaml
# helm-unittest suite: helm unittest charts/orders-api  (renders locally, no cluster)
suite: orders-api deployment
templates:
  - templates/deployment.yaml
  - templates/configmap.yaml
set:
  config.databaseHost: db.test
tests:
  - it: uses the chart appVersion as the default tag
    template: templates/deployment.yaml
    asserts:
      - isKind:
          of: Deployment
      - equal:
          path: spec.template.spec.containers[0].image
          value: ghcr.io/acme/orders-api:1.4.2
  - it: prefers the digest over the tag
    template: templates/deployment.yaml
    set:
      image.digest: sha256:0000000000000000000000000000000000000000000000000000000000000000
    asserts:
      - matchRegex:
          path: spec.template.spec.containers[0].image
          pattern: "@sha256:0{64}$"
  - it: leaves replicas to the HPA when autoscaling is on
    template: templates/deployment.yaml
    set:
      autoscaling.enabled: true
    asserts:
      - notExists:
          path: spec.replicas
  - it: keeps the version out of the selector
    template: templates/deployment.yaml
    asserts:
      - notExists:
          path: spec.selector.matchLabels["app.kubernetes.io/version"]
  - it: fails without a database host
    template: templates/configmap.yaml
    set:
      config.databaseHost: ""
    asserts:
      - failedTemplate:
          errorPattern: "config.databaseHost is required"

The application side: the service loads the ConfigMap and Secret values, reports every missing key at once, and checks that its drain fits the chart's grace period. The chart's required stops a bad render; this stops a bad pod.

go
// Package appconfig is the application side of the chart: orders-api reads the settings the
// chart renders into its ConfigMap (envFrom) and the Secret it references, and refuses to
// start when something is missing. The chart's `required` stops a bad render; this stops a
// bad pod (a hand-edited ConfigMap, a Secret that External Secrets has not synced yet).
package appconfig

import (
	"errors"
	"fmt"
	"strconv"
	"strings"
	"time"
)

// Config is everything the service needs at start-up.
type Config struct {
	Env             string // APP_ENV: dev, staging, prod
	LogLevel        string // LOG_LEVEL
	Port            int    // PORT, set by the Deployment from service.targetPort
	Version         string // APP_VERSION, the image tag the chart deployed
	DatabaseHost    string // DATABASE_HOST, from the ConfigMap
	DatabasePass    string // DATABASE_PASSWORD, from the existing Secret
	ShutdownTimeout time.Duration
}

// Load reads configuration through getenv (os.Getenv in main, a map in tests) and returns
// every problem at once, so one failed rollout shows the whole list in the pod log.
func Load(getenv func(string) string) (Config, error) {
	var errs []error
	get := func(key, def string) string {
		if v := strings.TrimSpace(getenv(key)); v != "" {
			return v
		}
		return def
	}
	must := func(key string) string {
		v := get(key, "")
		if v == "" {
			errs = append(errs, fmt.Errorf("%s is required", key))
		}
		return v
	}

	c := Config{
		Env:          must("APP_ENV"),
		LogLevel:     get("LOG_LEVEL", "info"),
		Version:      get("APP_VERSION", "dev"),
		DatabaseHost: must("DATABASE_HOST"),
		DatabasePass: must("DATABASE_PASSWORD"),
	}
	switch c.Env {
	case "", "dev", "staging", "prod":
	default:
		errs = append(errs, fmt.Errorf("APP_ENV=%q: want dev, staging or prod", c.Env))
	}

	port, err := strconv.Atoi(get("PORT", "8080"))
	if err != nil || port < 1 || port > 65535 {
		errs = append(errs, fmt.Errorf("PORT=%q: want 1-65535", get("PORT", "")))
	}
	c.Port = port

	d, err := time.ParseDuration(get("SHUTDOWN_TIMEOUT", "8s"))
	switch {
	case err != nil:
		errs = append(errs, fmt.Errorf("SHUTDOWN_TIMEOUT: %w", err))
	case d <= 0:
		errs = append(errs, fmt.Errorf("SHUTDOWN_TIMEOUT=%s: must be positive", d))
	}
	c.ShutdownTimeout = d

	return c, errors.Join(errs...)
}

// FitsGracePeriod reports whether the drain fits inside the pod's terminationGracePeriodSeconds
// with a margin for the endpoint removal that runs in parallel with SIGTERM.
func (c Config) FitsGracePeriod(gracePeriodSeconds int, margin time.Duration) bool {
	return c.ShutdownTimeout+margin <= time.Duration(gracePeriodSeconds)*time.Second
}
go
package appconfig

import (
	"strings"
	"testing"
	"time"
)

func env(m map[string]string) func(string) string { return func(k string) string { return m[k] } }

// What the orders-api chart renders for values-prod.yaml plus the existing Secret.
var prod = map[string]string{
	"APP_ENV":           "prod",
	"LOG_LEVEL":         "info",
	"DATABASE_HOST":     "orders-db.prod.internal",
	"SHUTDOWN_TIMEOUT":  "8s",
	"PORT":              "8080",
	"APP_VERSION":       "1.4.2",
	"DATABASE_PASSWORD": "from-the-secret",
}

func TestLoadProd(t *testing.T) {
	c, err := Load(env(prod))
	if err != nil {
		t.Fatalf("Load: %v", err)
	}
	if c.Port != 8080 || c.ShutdownTimeout != 8*time.Second || c.Version != "1.4.2" {
		t.Fatalf("got %+v", c)
	}
	if !c.FitsGracePeriod(30, 5*time.Second) {
		t.Fatal("8s drain + 5s margin must fit the chart's 30s grace period")
	}
	if c.FitsGracePeriod(10, 5*time.Second) {
		t.Fatal("8s + 5s must not fit a 10s grace period")
	}
}

func TestLoadReportsEverythingAtOnce(t *testing.T) {
	m := map[string]string{"APP_ENV": "qa", "PORT": "http", "SHUTDOWN_TIMEOUT": "soon"}
	_, err := Load(env(m))
	if err == nil {
		t.Fatal("want an error")
	}
	for _, want := range []string{"DATABASE_HOST is required", "DATABASE_PASSWORD is required", `APP_ENV="qa"`, `PORT="http"`, "SHUTDOWN_TIMEOUT"} {
		if !strings.Contains(err.Error(), want) {
			t.Errorf("error %q lacks %q", err, want)
		}
	}
}

func TestDefaults(t *testing.T) {
	m := map[string]string{"APP_ENV": "dev", "DATABASE_HOST": "db", "DATABASE_PASSWORD": "x"}
	c, err := Load(env(m))
	if err != nil {
		t.Fatal(err)
	}
	if c.Port != 8080 || c.LogLevel != "info" || c.ShutdownTimeout != 8*time.Second || c.Version != "dev" {
		t.Fatalf("defaults: %+v", c)
	}
}

A checker for rendered output (Helm or Kustomize): selectors that do not match their template, versions in selectors, unpinned images, replicas next to an HPA, empty PDB selectors and dangling ConfigMap references. Its last test reads the real kubectl kustomize output of every overlay.

go
// Package manifestcheck checks rendered Kubernetes manifests (the output of helm template or
// kustomize build) for the packaging mistakes that only show up after the first deploy:
// selectors that do not match their pod template, version labels inside immutable selectors,
// unpinned images, replicas fighting an HPA, PodDisruptionBudgets whose empty selector covers
// the whole namespace, and references to ConfigMaps that are not there (the classic symptom
// of a renamed, hash-suffixed generator output).
package manifestcheck

import (
	"bytes"
	"errors"
	"fmt"
	"io"
	"sort"
	"strings"

	"gopkg.in/yaml.v3"
)

// Object is the subset of a manifest the checks need.
type Object struct {
	APIVersion string         `yaml:"apiVersion"`
	Kind       string         `yaml:"kind"`
	Metadata   Meta           `yaml:"metadata"`
	Spec       map[string]any `yaml:"spec"`
}

// Meta holds name, namespace, labels and annotations.
type Meta struct {
	Name        string            `yaml:"name"`
	Namespace   string            `yaml:"namespace"`
	Labels      map[string]string `yaml:"labels"`
	Annotations map[string]string `yaml:"annotations"`
}

// Finding is one problem in one object.
type Finding struct {
	Object string // Kind/name
	Rule   string
	Detail string
}

func (f Finding) String() string { return f.Object + ": " + f.Rule + ": " + f.Detail }

// Parse splits a multi-document YAML stream into objects, skipping empty documents.
func Parse(stream []byte) ([]Object, error) {
	dec := yaml.NewDecoder(bytes.NewReader(stream))
	var out []Object
	for {
		var o Object
		err := dec.Decode(&o)
		if errors.Is(err, io.EOF) {
			return out, nil
		}
		if err != nil {
			return nil, fmt.Errorf("document %d: %w", len(out)+1, err)
		}
		if o.Kind == "" {
			continue
		}
		out = append(out, o)
	}
}

// Labels that change between releases and therefore must never be in a selector.
var volatileLabels = []string{"helm.sh/chart", "app.kubernetes.io/version"}

var workloadKinds = map[string]bool{"Deployment": true, "StatefulSet": true, "DaemonSet": true}

// Check runs every rule over the set and returns findings sorted by object and rule.
func Check(objs []Object) []Finding {
	var fs []Finding
	configMaps := map[string]bool{}
	hpaTargets := map[string]bool{}
	for _, o := range objs {
		switch o.Kind {
		case "ConfigMap":
			configMaps[o.Metadata.Name] = true
		case "HorizontalPodAutoscaler":
			if ref, ok := o.Spec["scaleTargetRef"].(map[string]any); ok {
				hpaTargets[fmt.Sprint(ref["kind"], "/", ref["name"])] = true
			}
		}
	}
	for _, o := range objs {
		id := o.Kind + "/" + o.Metadata.Name
		pod := podSpec(o)
		if workloadKinds[o.Kind] {
			fs = append(fs, checkSelector(id, o)...)
			if _, has := o.Spec["replicas"]; has && hpaTargets[id] {
				fs = append(fs, Finding{id, "replicas-with-hpa", "spec.replicas is set although an HPA scales this workload; every apply resets the HPA's count"})
			}
		}
		if o.Kind == "PodDisruptionBudget" {
			labels, _ := dig(o.Spec, "selector", "matchLabels").(map[string]any)
			exprs, _ := dig(o.Spec, "selector", "matchExpressions").([]any)
			if len(labels) == 0 && len(exprs) == 0 {
				fs = append(fs, Finding{id, "pdb-selector", "empty selector: a policy/v1 PDB with {} matches every pod in the namespace"})
			}
		}
		if pod == nil {
			continue
		}
		for _, img := range images(pod) {
			if f, bad := checkImage(img); bad {
				fs = append(fs, Finding{id, "image-pinning", f})
			}
		}
		for _, name := range configMapRefs(pod) {
			if !configMaps[name] {
				fs = append(fs, Finding{id, "missing-configmap", fmt.Sprintf("references ConfigMap %q, which is not in the rendered set", name)})
			}
		}
	}
	sort.Slice(fs, func(i, j int) bool {
		if fs[i].Object != fs[j].Object {
			return fs[i].Object < fs[j].Object
		}
		return fs[i].Rule < fs[j].Rule
	})
	return fs
}

func checkSelector(id string, o Object) []Finding {
	var fs []Finding
	sel, _ := dig(o.Spec, "selector", "matchLabels").(map[string]any)
	if len(sel) == 0 {
		return []Finding{{id, "selector", "spec.selector.matchLabels is empty"}}
	}
	tmpl, _ := dig(o.Spec, "template", "metadata", "labels").(map[string]any)
	keys := make([]string, 0, len(sel))
	for k := range sel {
		keys = append(keys, k)
	}
	sort.Strings(keys)
	for _, k := range keys {
		if fmt.Sprint(tmpl[k]) != fmt.Sprint(sel[k]) {
			fs = append(fs, Finding{id, "selector", fmt.Sprintf("selector label %s=%v is not on the pod template", k, sel[k])})
		}
		for _, v := range volatileLabels {
			if k == v {
				fs = append(fs, Finding{id, "selector-volatile", fmt.Sprintf("selector contains %s, which changes on upgrade, but selectors are immutable", k)})
			}
		}
	}
	return fs
}

func checkImage(img string) (string, bool) {
	if strings.Contains(img, "@sha256:") {
		return "", false
	}
	slash := strings.LastIndex(img, "/")
	colon := strings.LastIndex(img, ":")
	switch {
	case colon <= slash:
		return fmt.Sprintf("image %q has no tag or digest (implicit :latest)", img), true
	case strings.HasSuffix(img, ":latest"):
		return fmt.Sprintf("image %q uses :latest", img), true
	}
	return "", false
}

// podSpec returns the pod spec of a workload, a Job, a CronJob or a Pod.
func podSpec(o Object) map[string]any {
	switch o.Kind {
	case "Pod":
		return o.Spec
	case "CronJob":
		p, _ := dig(o.Spec, "jobTemplate", "spec", "template", "spec").(map[string]any)
		return p
	case "Deployment", "StatefulSet", "DaemonSet", "Job", "ReplicaSet":
		p, _ := dig(o.Spec, "template", "spec").(map[string]any)
		return p
	}
	return nil
}

func containers(pod map[string]any) []map[string]any {
	var cs []map[string]any
	for _, key := range []string{"initContainers", "containers"} {
		list, _ := pod[key].([]any)
		for _, c := range list {
			if m, ok := c.(map[string]any); ok {
				cs = append(cs, m)
			}
		}
	}
	return cs
}

func images(pod map[string]any) []string {
	var out []string
	for _, c := range containers(pod) {
		if s, ok := c["image"].(string); ok {
			out = append(out, s)
		}
	}
	return out
}

func configMapRefs(pod map[string]any) []string {
	seen := map[string]bool{}
	var out []string
	add := func(v any) {
		if s, ok := v.(string); ok && !seen[s] {
			seen[s] = true
			out = append(out, s)
		}
	}
	for _, c := range containers(pod) {
		ef, _ := c["envFrom"].([]any)
		for _, e := range ef {
			add(dig(e, "configMapRef", "name"))
		}
		env, _ := c["env"].([]any)
		for _, e := range env {
			add(dig(e, "valueFrom", "configMapKeyRef", "name"))
		}
	}
	vols, _ := pod["volumes"].([]any)
	for _, v := range vols {
		add(dig(v, "configMap", "name"))
	}
	return out
}

func dig(v any, path ...string) any {
	for _, p := range path {
		m, ok := v.(map[string]any)
		if !ok {
			return nil
		}
		v = m[p]
	}
	return v
}
go
package manifestcheck

import (
	"os"
	"path/filepath"
	"strings"
	"testing"
)

const bad = `
apiVersion: apps/v1
kind: Deployment
metadata:
  name: web
spec:
  replicas: 3
  selector:
    matchLabels:
      app.kubernetes.io/name: web
      app.kubernetes.io/version: "1.4.2"
  template:
    metadata:
      labels:
        app.kubernetes.io/name: web
        app.kubernetes.io/version: "1.4.2"
    spec:
      containers:
        - name: web
          image: nginx
          envFrom:
            - configMapRef:
                name: web-config
        - name: sidecar
          image: ghcr.io/acme/agent:latest
---
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
  name: web
spec:
  scaleTargetRef: {apiVersion: apps/v1, kind: Deployment, name: web}
  minReplicas: 2
  maxReplicas: 5
---
apiVersion: v1
kind: ConfigMap
metadata:
  name: web-config-5k7h9t2b8m
`

func TestCheckFindsEveryMistake(t *testing.T) {
	objs, err := Parse([]byte(bad))
	if err != nil {
		t.Fatal(err)
	}
	got := Check(objs)
	want := []string{
		`Deployment/web: image-pinning: image "nginx" has no tag or digest (implicit :latest)`,
		`Deployment/web: image-pinning: image "ghcr.io/acme/agent:latest" uses :latest`,
		`Deployment/web: missing-configmap: references ConfigMap "web-config", which is not in the rendered set`,
		`Deployment/web: replicas-with-hpa: spec.replicas is set although an HPA scales this workload; every apply resets the HPA's count`,
		`Deployment/web: selector-volatile: selector contains app.kubernetes.io/version, which changes on upgrade, but selectors are immutable`,
	}
	if len(got) != len(want) {
		t.Fatalf("got %d findings:\n%v", len(got), got)
	}
	for i := range want {
		if got[i].String() != want[i] {
			t.Errorf("finding %d:\n got  %s\n want %s", i, got[i], want[i])
		}
	}
}

func TestSelectorMismatch(t *testing.T) {
	objs, _ := Parse([]byte(`
apiVersion: apps/v1
kind: Deployment
metadata: {name: api}
spec:
  selector: {matchLabels: {app: api, tier: backend}}
  template:
    metadata: {labels: {app: api}}
    spec: {containers: [{name: api, image: "ghcr.io/acme/api@sha256:aa"}]}
`))
	got := Check(objs)
	if len(got) != 1 || got[0].Rule != "selector" || !strings.Contains(got[0].Detail, "tier=backend") {
		t.Fatalf("got %v", got)
	}
}

// The first version of overlays/prod/pdb.yaml: Kustomize gave it the overlay's labels but
// no selector, because only the base's own resources get the base's selector labels.
func TestEmptyPDBSelector(t *testing.T) {
	objs, _ := Parse([]byte(`
apiVersion: policy/v1
kind: PodDisruptionBudget
metadata: {name: orders-api, namespace: shop-prod}
spec:
  maxUnavailable: 1
  selector:
    matchLabels: {}
`))
	got := Check(objs)
	if len(got) != 1 || got[0].Rule != "pdb-selector" {
		t.Fatalf("got %v", got)
	}
}

// A selector written only with matchExpressions is not empty.
func TestPDBSelectorWithExpressions(t *testing.T) {
	objs, _ := Parse([]byte(`
apiVersion: policy/v1
kind: PodDisruptionBudget
metadata: {name: orders-api}
spec:
  maxUnavailable: 1
  selector:
    matchExpressions:
      - {key: app.kubernetes.io/name, operator: In, values: [orders-api]}
`))
	if got := Check(objs); len(got) != 0 {
		t.Fatalf("got %v", got)
	}
}

func TestPortsAndRegistriesAreNotTags(t *testing.T) {
	for img, bad := range map[string]bool{
		"registry.example.test:5000/acme/api":       true, // the colon belongs to the port
		"registry.example.test:5000/acme/api:1.4.2": false,
		"ghcr.io/acme/api@sha256:abc":               false,
		"busybox:1.37":                              false,
	} {
		if _, got := checkImage(img); got != bad {
			t.Errorf("%s: bad=%v, want %v", img, got, bad)
		}
	}
}

// The overlays' real output (kubectl kustomize, saved by scripts/kustomize-build-all.sh)
// must be clean: generated ConfigMap names resolve, the HPA overlays drop replicas.
func TestKustomizeOutputsAreClean(t *testing.T) {
	files, _ := filepath.Glob("testdata/*.yaml")
	if len(files) < 4 {
		t.Fatalf("want the dev, staging, prod and helm-post outputs in testdata, got %v", files)
	}
	for _, f := range files {
		b, err := os.ReadFile(f)
		if err != nil {
			t.Fatal(err)
		}
		objs, err := Parse(b)
		if err != nil {
			t.Fatalf("%s: %v", f, err)
		}
		if len(objs) < 3 {
			t.Fatalf("%s: only %d objects", f, len(objs))
		}
		if fs := Check(objs); len(fs) > 0 {
			t.Errorf("%s:\n%v", f, fs)
		}
	}
}

The chart tests. cmd/helm4 is Helm's own main compiled from helm.sh/helm/v4 v4.0.5 (the last v4 line whose go.mod declares Go 1.24), built with the same -X flags as Helm's release Makefile so the default Kubernetes version is 1.34 rather than 1.20. The tests lint every environment, render prod and dev, prove that required and the schema stop bad values, that lint does not enforce required, that a library chart is not installable, build the Laravel chart's dependency, and pin down the --set and values-file typing rules with Helm's own strvals and ReadValues.

go
// Command helm4 is the Helm 4 CLI compiled from its own Go module (helm.sh/helm/v4, pinned in
// go.mod). The book's build host has no helm binary, so the chapter's charts are linted and
// rendered with this: same code path as the released CLI's cmd/helm/helm.go, nothing added.
//
//	go run ./cmd/helm4 lint ../charts/orders-api -f ../charts/orders-api/values-prod.yaml
//	go run ./cmd/helm4 template orders-api ../charts/orders-api -n shop-prod -f ...
package main

import (
	"log/slog"
	"os"

	helmcmd "helm.sh/helm/v4/pkg/cmd"
	"helm.sh/helm/v4/pkg/kube"
)

func main() {
	kube.ManagedFieldsManager = "helm"

	cmd, err := helmcmd.NewRootCmd(os.Stdout, os.Args[1:], helmcmd.SetupLogging)
	if err != nil {
		slog.Warn("command failed", slog.Any("error", err))
		os.Exit(1)
	}
	if err := cmd.Execute(); err != nil {
		if cerr, ok := err.(helmcmd.CommandError); ok {
			os.Exit(cerr.ExitCode)
		}
		os.Exit(1)
	}
}
go
// Package chartcheck holds the chapter's chart tests. They run the real Helm 4 CLI code
// (./cmd/helm4, built once per test run) against ../charts and assert on what helm lint and
// helm template print, then feed the rendered manifests through manifestcheck.
package chartcheck

import (
	"bytes"
	"os/exec"
)

// LDFlags mirrors the release Makefile of Helm v4.0.5: the version string, and the default
// Kubernetes version for client-only renders derived from k8s.io/client-go v0.34.1 (0+1 = 1,
// minor 34). Without them a module build reports "v4.0" and renders for Kubernetes v1.20.0.
const LDFlags = "-X helm.sh/helm/v4/internal/version.version=v4.0.5" +
	" -X helm.sh/helm/v4/pkg/chart/common.k8sVersionMajor=1" +
	" -X helm.sh/helm/v4/pkg/chart/common.k8sVersionMinor=34" +
	" -X helm.sh/helm/v4/pkg/chart/v2/lint/rules.k8sVersionMajor=1" +
	" -X helm.sh/helm/v4/pkg/chart/v2/lint/rules.k8sVersionMinor=34" +
	" -X helm.sh/helm/v4/internal/version.kubeClientVersionMajor=1" +
	" -X helm.sh/helm/v4/internal/version.kubeClientVersionMinor=34"

// Run executes the helm binary at bin with args and returns stdout, stderr and the error.
func Run(bin string, args ...string) (string, string, error) {
	var out, errOut bytes.Buffer
	cmd := exec.Command(bin, args...)
	cmd.Stdout, cmd.Stderr = &out, &errOut
	err := cmd.Run()
	return out.String(), errOut.String(), err
}
go
package chartcheck

import (
	"fmt"
	"os"
	"os/exec"
	"path/filepath"
	"strings"
	"testing"

	"academy/helm-kustomize-packaging/manifestcheck"

	"helm.sh/helm/v4/pkg/chart/common"
	"helm.sh/helm/v4/pkg/strvals"
)

var helm string // path to the helm4 binary built in TestMain

const charts = "../../charts"

func TestMain(m *testing.M) {
	dir, err := os.MkdirTemp("", "helm4")
	if err != nil {
		panic(err)
	}
	helm = filepath.Join(dir, "helm")
	build := exec.Command("go", "build", "-ldflags", LDFlags, "-o", helm, "../cmd/helm4")
	build.Stdout, build.Stderr = os.Stdout, os.Stderr
	if err := build.Run(); err != nil {
		panic(err)
	}
	// Keep Helm's config, cache and data out of the developer's home directory.
	for _, k := range []string{"HELM_CONFIG_HOME", "HELM_CACHE_HOME", "HELM_DATA_HOME"} {
		os.Setenv(k, filepath.Join(dir, strings.ToLower(k)))
	}
	code := m.Run()
	os.RemoveAll(dir)
	os.Exit(code)
}

func render(t *testing.T, args ...string) []manifestcheck.Object {
	t.Helper()
	out, stderr, err := Run(helm, append([]string{"template"}, args...)...)
	if err != nil {
		t.Fatalf("helm template %v: %v\n%s", args, err, stderr)
	}
	objs, err := manifestcheck.Parse([]byte(out))
	if err != nil {
		t.Fatalf("rendered YAML does not parse: %v", err)
	}
	return objs
}

func find(objs []manifestcheck.Object, kind, name string) *manifestcheck.Object {
	for i := range objs {
		if objs[i].Kind == kind && objs[i].Metadata.Name == name {
			return &objs[i]
		}
	}
	return nil
}

func TestOrdersAPILintsInEveryEnvironment(t *testing.T) {
	for _, env := range []string{"dev", "staging", "prod"} {
		out, stderr, err := Run(helm, "lint", "--strict", charts+"/orders-api", "-f", charts+"/orders-api/values-"+env+".yaml")
		if err != nil || !strings.Contains(out, "1 chart(s) linted, 0 chart(s) failed") {
			t.Errorf("%s: err=%v\n%s%s", env, err, out, stderr)
		}
	}
}

func TestOrdersAPIProd(t *testing.T) {
	objs := render(t, "orders-api", charts+"/orders-api", "-n", "shop-prod", "-f", charts+"/orders-api/values-prod.yaml")
	if fs := manifestcheck.Check(objs); len(fs) > 0 {
		t.Fatalf("manifestcheck: %v", fs)
	}
	d := find(objs, "Deployment", "orders-api")
	if d == nil {
		t.Fatal("no Deployment orders-api")
	}
	if _, ok := d.Spec["replicas"]; ok {
		t.Error("replicas must be omitted when the HPA is enabled")
	}
	podYAML := fmt.Sprint(d.Spec["template"])
	for _, want := range []string{
		"ghcr.io/acme/orders-api@sha256:0b7e", // digest beats tag
		"k8s.namespace.name=shop-prod",        // tpl rendered the namespace into extraEnv
		"topology.kubernetes.io/zone",
	} {
		if !strings.Contains(podYAML, want) {
			t.Errorf("pod template lacks %q", want)
		}
	}
	for _, kind := range []string{"HorizontalPodAutoscaler", "PodDisruptionBudget", "Service", "ServiceAccount", "ConfigMap"} {
		if find(objs, kind, "orders-api") == nil {
			t.Errorf("no %s", kind)
		}
	}
	if p := find(objs, "Pod", "orders-api-test-readyz"); p == nil || p.Metadata.Annotations["helm.sh/hook"] != "test" {
		t.Error("helm template must include the test hook Pod")
	}
}

func TestOrdersAPIDevKeepsReplicas(t *testing.T) {
	objs := render(t, "orders-api", charts+"/orders-api", "-n", "shop-dev", "-f", charts+"/orders-api/values-dev.yaml")
	d := find(objs, "Deployment", "orders-api")
	if d == nil || fmt.Sprint(d.Spec["replicas"]) != "1" {
		t.Fatalf("dev: want replicas 1, got %v", d)
	}
	if find(objs, "HorizontalPodAutoscaler", "orders-api") != nil {
		t.Error("dev must not render an HPA")
	}
}

func TestRequiredAndSchemaStopBadRenders(t *testing.T) {
	cases := []struct {
		name string
		args []string
		want string
	}{
		{"required", nil, "config.databaseHost is required"},
		{"schema enum", []string{"--set", "config.databaseHost=db", "--set", "config.appEnv=qa"}, "appEnv"},
		{"schema digest", []string{"--set", "config.databaseHost=db", "--set", "image.digest=latest"}, "digest"},
		{"schema no secrets in values", []string{"--set", "config.databaseHost=db", "--set", "config.databasePassword=hunter2"}, "config"},
	}
	for _, c := range cases {
		_, stderr, err := Run(helm, append([]string{"template", "orders-api", charts + "/orders-api"}, c.args...)...)
		if err == nil || !strings.Contains(stderr, c.want) {
			t.Errorf("%s: want failure mentioning %q, got err=%v\n%s", c.name, c.want, err, stderr)
		}
	}
}

// helm lint runs the engine in lint mode, where `required` only logs a warning: lint passes
// for a values set that helm template (and helm install) refuses.
func TestLintDoesNotEnforceRequired(t *testing.T) {
	out, stderr, err := Run(helm, "lint", "--strict", charts+"/orders-api")
	if err != nil || !strings.Contains(out, "0 chart(s) failed") || !strings.Contains(stderr, "missing required value") {
		t.Fatalf("lint: err=%v\n%s%s", err, out, stderr)
	}
	if _, _, err := Run(helm, "template", "orders-api", charts+"/orders-api"); err == nil {
		t.Fatal("template must fail without config.databaseHost")
	}
}

func TestLibraryChartIsNotInstallable(t *testing.T) {
	_, stderr, err := Run(helm, "template", "lib", charts+"/acme-lib")
	if err == nil || !strings.Contains(stderr, "library charts are not installable") {
		t.Fatalf("err=%v\n%s", err, stderr)
	}
}

// copyChart copies a chart directory so dependency build does not write into the book's tree.
func copyChart(t *testing.T, src, dst string) {
	t.Helper()
	err := filepath.Walk(src, func(p string, info os.FileInfo, err error) error {
		if err != nil {
			return err
		}
		rel, _ := filepath.Rel(src, p)
		target := filepath.Join(dst, rel)
		if info.IsDir() {
			return os.MkdirAll(target, 0o755)
		}
		b, err := os.ReadFile(p)
		if err != nil {
			return err
		}
		return os.WriteFile(target, b, 0o644)
	})
	if err != nil {
		t.Fatal(err)
	}
}

func TestShopLaravel(t *testing.T) {
	work := t.TempDir()
	copyChart(t, charts+"/acme-lib", filepath.Join(work, "acme-lib"))
	copyChart(t, charts+"/shop-laravel", filepath.Join(work, "shop-laravel"))
	chart := filepath.Join(work, "shop-laravel")

	if out, stderr, err := Run(helm, "dependency", "build", chart); err != nil {
		t.Fatalf("dependency build: %v\n%s%s", err, out, stderr)
	}
	if _, err := os.Stat(filepath.Join(chart, "charts", "acme-lib-0.2.0.tgz")); err != nil {
		t.Fatalf("library not vendored: %v", err)
	}
	prod := filepath.Join(chart, "values-prod.yaml")
	if out, stderr, err := Run(helm, "lint", "--strict", chart, "-f", prod); err != nil {
		t.Fatalf("lint: %v\n%s%s", err, out, stderr)
	}

	objs := render(t, "shop", chart, "-n", "shop-prod", "-f", prod)
	if fs := manifestcheck.Check(objs); len(fs) > 0 {
		t.Fatalf("manifestcheck: %v", fs)
	}
	web := find(objs, "Deployment", "shop-shop-laravel-web")
	if web == nil {
		t.Fatalf("no web Deployment; got %d objects", len(objs))
	}
	if _, ok := web.Spec["replicas"]; ok {
		t.Error("web replicas must be left to the HPA in prod")
	}
	cs, _ := web.Spec["template"].(map[string]any)["spec"].(map[string]any)["containers"].([]any)
	if len(cs) != 2 {
		t.Errorf("web pod: want php-fpm + nginx, got %d containers", len(cs))
	}
	worker := find(objs, "Deployment", "shop-shop-laravel-worker")
	if worker == nil || !strings.Contains(fmt.Sprint(worker.Spec), "--max-time=3600") {
		t.Errorf("worker command: %v", worker)
	}
	if find(objs, "CronJob", "shop-shop-laravel-scheduler") == nil {
		t.Error("no scheduler CronJob")
	}
	job := find(objs, "Job", "shop-shop-laravel-migrate")
	if job == nil {
		t.Fatal("no migrate Job")
	}
	if got := job.Metadata.Annotations["helm.sh/hook"]; got != "pre-install,pre-upgrade" {
		t.Errorf("hook = %q", got)
	}
	if got := job.Metadata.Annotations["helm.sh/hook-delete-policy"]; got != "before-hook-creation,hook-succeeded" {
		t.Errorf("delete policy = %q", got)
	}

	// No Secret name: the render stops. A secret in values: the schema stops it.
	_, stderr, err := Run(helm, "template", "shop", chart, "--set", "env.DB_HOST=db")
	if err == nil || !strings.Contains(stderr, "existingSecret is required") {
		t.Errorf("missing existingSecret: err=%v\n%s", err, stderr)
	}
	_, stderr, err = Run(helm, "template", "shop", chart, "-f", prod, "--set", "env.APP_KEY=base64:abc")
	if err == nil || !strings.Contains(stderr, "APP_KEY") {
		t.Errorf("APP_KEY in values: err=%v\n%s", err, stderr)
	}
}

// --set and values files are typed differently; both surprise people.
func TestValueTypingPitfalls(t *testing.T) {
	set, err := strvals.Parse("image.tag=1.10,replicaCount=3,port=08080,debug=true,nodeSelector=null")
	if err != nil {
		t.Fatal(err)
	}
	img := set["image"].(map[string]any)
	checks := []struct {
		name string
		got  any
		want string
	}{
		{"--set image.tag=1.10 stays a string", img["tag"], "string 1.10"},
		{"--set replicaCount=3 becomes int64", set["replicaCount"], "int64 3"},
		{"--set port=08080 (leading zero) stays a string", set["port"], "string 08080"},
		{"--set debug=true becomes a bool", set["debug"], "bool true"},
		{"--set nodeSelector=null becomes nil (deletes the default)", set["nodeSelector"], "<nil> <nil>"},
	}
	for _, c := range checks {
		if got := fmt.Sprintf("%T %v", c.got, c.got); got != c.want {
			t.Errorf("%s: got %s", c.name, got)
		}
	}
	if _, err := strvals.Parse("annotations.team=a,b"); err == nil {
		t.Error("an unescaped comma in --set must be a parse error")
	}

	// A values FILE goes YAML -> JSON -> Go: numbers become float64, so tag: 1.10 is 1.1.
	vals, err := common.ReadValues([]byte("image:\n  tag: 1.10\nbig: 1000000\n"))
	if err != nil {
		t.Fatal(err)
	}
	tag := vals["image"].(map[string]any)["tag"]
	if got := fmt.Sprintf("%T %v", tag, tag); got != "float64 1.1" {
		t.Errorf("unquoted tag: got %s", got)
	}
	if got := fmt.Sprint(vals["big"]); got != "1e+06" {
		t.Errorf("1000000 from a values file prints as %s", got)
	}
}
text
module academy/helm-kustomize-packaging

go 1.24.0

require (
	gopkg.in/yaml.v3 v3.0.1
	helm.sh/helm/v4 v4.0.5
)

require (
	dario.cat/mergo v1.0.1 // indirect
	github.com/Azure/go-ansiterm v0.0.0-20250102033503-faa5f7b0171c // indirect
	github.com/BurntSushi/toml v1.5.0 // indirect
	github.com/MakeNowJust/heredoc v1.0.0 // indirect
	github.com/Masterminds/goutils v1.1.1 // indirect
	github.com/Masterminds/semver/v3 v3.4.0 // indirect
	github.com/Masterminds/sprig/v3 v3.3.0 // indirect
	github.com/Masterminds/squirrel v1.5.4 // indirect
	github.com/Masterminds/vcs v1.13.3 // indirect
	github.com/ProtonMail/go-crypto v1.3.0 // indirect
	github.com/asaskevich/govalidator v0.0.0-20230301143203-a9d515a09cc2 // indirect
	github.com/blang/semver/v4 v4.0.0 // indirect
	github.com/chai2010/gettext-go v1.0.2 // indirect
	github.com/cloudflare/circl v1.6.1 // indirect
	github.com/cpuguy83/go-md2man/v2 v2.0.6 // indirect
	github.com/cyphar/filepath-securejoin v0.5.0 // indirect
	github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect
	github.com/dylibso/observe-sdk/go v0.0.0-20240819160327-2d926c5d788a // indirect
	github.com/emicklei/go-restful/v3 v3.12.2 // indirect
	github.com/evanphx/json-patch/v5 v5.9.11 // indirect
	github.com/exponent-io/jsonpath v0.0.0-20210407135951-1de76d718b3f // indirect
	github.com/extism/go-sdk v1.7.1 // indirect
	github.com/fatih/color v1.18.0 // indirect
	github.com/fluxcd/cli-utils v0.36.0-flux.14 // indirect
	github.com/fxamacker/cbor/v2 v2.9.0 // indirect
	github.com/go-errors/errors v1.5.1 // indirect
	github.com/go-gorp/gorp/v3 v3.1.0 // indirect
	github.com/go-logr/logr v1.4.3 // indirect
	github.com/go-openapi/jsonpointer v0.21.1 // indirect
	github.com/go-openapi/jsonreference v0.21.0 // indirect
	github.com/go-openapi/swag v0.23.1 // indirect
	github.com/gobwas/glob v0.2.3 // indirect
	github.com/gofrs/flock v0.13.0 // indirect
	github.com/gogo/protobuf v1.3.2 // indirect
	github.com/google/btree v1.1.3 // indirect
	github.com/google/gnostic-models v0.7.0 // indirect
	github.com/google/go-cmp v0.7.0 // indirect
	github.com/google/uuid v1.6.0 // indirect
	github.com/gorilla/websocket v1.5.4-0.20250319132907-e064f32e3674 // indirect
	github.com/gosuri/uitable v0.0.4 // indirect
	github.com/gregjones/httpcache v0.0.0-20190611155906-901d90724c79 // indirect
	github.com/huandu/xstrings v1.5.0 // indirect
	github.com/ianlancetaylor/demangle v0.0.0-20240805132620-81f5be970eca // indirect
	github.com/inconshreveable/mousetrap v1.1.0 // indirect
	github.com/jmoiron/sqlx v1.4.0 // indirect
	github.com/josharian/intern v1.0.0 // indirect
	github.com/json-iterator/go v1.1.12 // indirect
	github.com/lann/builder v0.0.0-20180802200727-47ae307949d0 // indirect
	github.com/lann/ps v0.0.0-20150810152359-62de8c46ede0 // indirect
	github.com/lib/pq v1.10.9 // indirect
	github.com/liggitt/tabwriter v0.0.0-20181228230101-89fcab3d43de // indirect
	github.com/mailru/easyjson v0.9.0 // indirect
	github.com/mattn/go-colorable v0.1.13 // indirect
	github.com/mattn/go-isatty v0.0.20 // indirect
	github.com/mattn/go-runewidth v0.0.9 // indirect
	github.com/mitchellh/copystructure v1.2.0 // indirect
	github.com/mitchellh/go-wordwrap v1.0.1 // indirect
	github.com/mitchellh/reflectwalk v1.0.2 // indirect
	github.com/moby/spdystream v0.5.0 // indirect
	github.com/moby/term v0.5.2 // indirect
	github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
	github.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee // indirect
	github.com/monochromegane/go-gitignore v0.0.0-20200626010858-205db1a8cc00 // indirect
	github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect
	github.com/mxk/go-flowrate v0.0.0-20140419014527-cca7078d478f // indirect
	github.com/opencontainers/go-digest v1.0.0 // indirect
	github.com/opencontainers/image-spec v1.1.1 // indirect
	github.com/peterbourgon/diskv v2.0.1+incompatible // indirect
	github.com/pkg/errors v0.9.1 // indirect
	github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect
	github.com/rubenv/sql-migrate v1.8.0 // indirect
	github.com/russross/blackfriday/v2 v2.1.0 // indirect
	github.com/santhosh-tekuri/jsonschema/v6 v6.0.2 // indirect
	github.com/shopspring/decimal v1.4.0 // indirect
	github.com/spf13/cast v1.7.0 // indirect
	github.com/spf13/cobra v1.10.1 // indirect
	github.com/spf13/pflag v1.0.10 // indirect
	github.com/tetratelabs/wabin v0.0.0-20230304001439-f6f874872834 // indirect
	github.com/tetratelabs/wazero v1.9.0 // indirect
	github.com/x448/float16 v0.8.4 // indirect
	github.com/xlab/treeprint v1.2.0 // indirect
	go.opentelemetry.io/proto/otlp v1.5.0 // indirect
	go.yaml.in/yaml/v2 v2.4.2 // indirect
	go.yaml.in/yaml/v3 v3.0.4 // indirect
	golang.org/x/crypto v0.45.0 // indirect
	golang.org/x/net v0.47.0 // indirect
	golang.org/x/oauth2 v0.30.0 // indirect
	golang.org/x/sync v0.18.0 // indirect
	golang.org/x/sys v0.39.0 // indirect
	golang.org/x/term v0.37.0 // indirect
	golang.org/x/text v0.31.0 // indirect
	golang.org/x/time v0.12.0 // indirect
	google.golang.org/protobuf v1.36.6 // indirect
	gopkg.in/evanphx/json-patch.v4 v4.12.0 // indirect
	gopkg.in/inf.v0 v0.9.1 // indirect
	k8s.io/api v0.34.1 // indirect
	k8s.io/apiextensions-apiserver v0.34.1 // indirect
	k8s.io/apimachinery v0.34.1 // indirect
	k8s.io/apiserver v0.34.1 // indirect
	k8s.io/cli-runtime v0.34.1 // indirect
	k8s.io/client-go v0.34.1 // indirect
	k8s.io/component-base v0.34.1 // indirect
	k8s.io/klog/v2 v2.130.1 // indirect
	k8s.io/kube-openapi v0.0.0-20250710124328-f3f2b991d03b // indirect
	k8s.io/kubectl v0.34.1 // indirect
	k8s.io/utils v0.0.0-20250604170112-4c0f3b243397 // indirect
	oras.land/oras-go/v2 v2.6.0 // indirect
	sigs.k8s.io/controller-runtime v0.22.3 // indirect
	sigs.k8s.io/json v0.0.0-20241014173422-cfa47c3a1cc8 // indirect
	sigs.k8s.io/kustomize/api v0.20.1 // indirect
	sigs.k8s.io/kustomize/kyaml v0.20.1 // indirect
	sigs.k8s.io/randfill v1.0.0 // indirect
	sigs.k8s.io/structured-merge-diff/v6 v6.3.0 // indirect
	sigs.k8s.io/yaml v1.6.0 // indirect
)

The Go angle ​

  • Helm templates are Go templates. Everything from html/template about actions, pipelines, define and block, dot and $ applies, minus HTML escaping (text/template does none: YAML injection through values is possible, which is one more reason for a schema). Helm sets missingkey=zero (or error with --strict rendering in the SDK) and strips the <no value> text Go prints for missing map keys.
  • YAML numbers are float64. Helm reads values with sigs.k8s.io/yaml (YAML -> JSON -> encoding/json), so in Go terms every number is a float64: printf "%d" on one prints %!d(float64=3600). The Laravel chart wraps int around maxTime and tries for exactly this reason; the test TestValueTypingPitfalls shows 1000000 becoming 1e+06.
  • The SDK is the CLI. helm.sh/helm/v4/pkg/action (NewInstall with a client-only dry run, NewUpgrade, NewLint), pkg/chart/v2/loader and pkg/engine are what Argo CD-style tools, Terraform's Helm provider and Flux's helm-controller embed. Pin a version whose go directive your toolchain supports: v4.0.x declares Go 1.24, v4.1 needs 1.25 and v4.2+ need 1.26.
  • Release metadata from ldflags. A Go module build of Helm without -X helm.sh/helm/v4/pkg/chart/common.k8sVersionMajor/Minor renders for "Kubernetes v1.20.0", which failed this chapter's kubeVersion: >=1.30.0-0 on the first test run. go version -m shows which flags a binary was built with; the same mechanism stamps orders-api's own version.
  • Config at start, not at render. appconfig.Load reads env once, joins all errors with errors.Join, and exits before serving; Kubernetes then shows CrashLoopBackOff with the full list in kubectl logs, and --rollback-on-failure undoes the upgrade. FitsGracePeriod checks SHUTDOWN_TIMEOUT plus a margin against terminationGracePeriodSeconds (30 s in the chart), the drain budget from Kubernetes Workloads.
  • Testing manifests in Go. gopkg.in/yaml.v3 with a multi-document Decoder is enough for policy checks like manifestcheck; for full schema validation, kubeconform (a Go program) uses the Kubernetes OpenAPI schemas, and for policies at admission time, Kyverno or Gatekeeper (Security & RBAC).

Laravel ​

Before ​

The Laravel deployment many teams start with: one Deployment that runs migrations from the container's entrypoint on every pod start, a queue worker as a second process in the same container, and the scheduler as a cron daemon inside the image.

yaml
# k8s/shop.yaml - one object doing four jobs
apiVersion: apps/v1
kind: Deployment
metadata:
  name: shop
spec:
  replicas: 3
  selector:
    matchLabels: {app: shop}
  template:
    metadata:
      labels: {app: shop}
    spec:
      containers:
        - name: app
          image: ghcr.io/acme/shop-app:latest
          # three replicas start at once: three concurrent "php artisan migrate" runs, then
          # supervisord starts php-fpm + queue:work + cron; SIGTERM goes to supervisord only
          command: ["sh", "-c", "php artisan migrate --force && exec supervisord"]
          env:
            - name: APP_KEY
              value: base64:...            # the encryption key in Git

After ​

A chart with one release and five workloads. The library chart acme-lib supplies labels, image strings and security contexts; shop-laravel declares it as a file:// dependency (CI runs helm dependency build, which wrote the Chart.lock below on the build host):

yaml
# A library chart: only named templates, never installed on its own (helm install refuses it)
apiVersion: v2
name: acme-lib
description: Shared label, image and security-context helpers for the shop's charts
type: library
version: 0.2.0
text
{{/*
acme-lib: helpers shared by every application chart of the platform team.
All helpers take a dict so the caller can pass its own root context and a component:
  include "acme-lib.labels" (dict "ctx" $ "component" "web")
*/}}

{{- define "acme-lib.fullname" -}}
{{- $ctx := .ctx -}}
{{- if $ctx.Values.fullnameOverride -}}
{{- $ctx.Values.fullnameOverride | trunc 63 | trimSuffix "-" -}}
{{- else if contains $ctx.Chart.Name $ctx.Release.Name -}}
{{- $ctx.Release.Name | trunc 63 | trimSuffix "-" -}}
{{- else -}}
{{- printf "%s-%s" $ctx.Release.Name $ctx.Chart.Name | trunc 63 | trimSuffix "-" -}}
{{- end -}}
{{- end }}

{{/* Immutable selector labels: name, instance, component. No versions. */}}
{{- define "acme-lib.selectorLabels" -}}
app.kubernetes.io/name: {{ .ctx.Chart.Name }}
app.kubernetes.io/instance: {{ .ctx.Release.Name }}
{{- with .component }}
app.kubernetes.io/component: {{ . }}
{{- end }}
{{- end }}

{{- define "acme-lib.labels" -}}
helm.sh/chart: {{ printf "%s-%s" .ctx.Chart.Name .ctx.Chart.Version | replace "+" "_" | trunc 63 | trimSuffix "-" }}
{{ include "acme-lib.selectorLabels" . }}
app.kubernetes.io/version: {{ .ctx.Chart.AppVersion | quote }}
app.kubernetes.io/managed-by: {{ .ctx.Release.Service }}
app.kubernetes.io/part-of: shop
{{- end }}

{{/* image: dict "image" <repository/tag/digest map> "ctx" $ ; digest beats tag. */}}
{{- define "acme-lib.image" -}}
{{- $repo := required "image.repository is required" .image.repository -}}
{{- if .image.digest -}}
{{- printf "%s@%s" $repo .image.digest -}}
{{- else -}}
{{- printf "%s:%s" $repo (.image.tag | default .ctx.Chart.AppVersion) -}}
{{- end -}}
{{- end }}

{{/* Restricted-profile pod security context for a numeric non-root UID. */}}
{{- define "acme-lib.podSecurityContext" -}}
runAsNonRoot: true
runAsUser: {{ .uid | default 65532 }}
runAsGroup: {{ .uid | default 65532 }}
fsGroup: {{ .uid | default 65532 }}
seccompProfile:
  type: RuntimeDefault
{{- end }}

{{/* Container-level context; pass dict "uid" <n> to also pin a numeric non-root user. */}}
{{- define "acme-lib.containerSecurityContext" -}}
{{- with .uid -}}
runAsNonRoot: true
runAsUser: {{ . }}
runAsGroup: {{ . }}
{{ end -}}
allowPrivilegeEscalation: false
capabilities:
  drop: ["ALL"]
{{- end }}
yaml
apiVersion: v2
name: shop-laravel
description: The shop's Laravel app on Kubernetes - Nginx + php-fpm pods, queue workers, scheduler, migration hook
type: application
version: 2.1.0
appVersion: "3.8.0"
kubeVersion: ">=1.30.0-0"
dependencies:
  # helm dependency build copies the library into charts/ and writes Chart.lock
  - name: acme-lib
    version: 0.2.0
    repository: file://../acme-lib
yaml
dependencies:
- name: acme-lib
  repository: file://../acme-lib
  version: 0.2.0
digest: sha256:e22c2f79285419a409e5096a9396e37aa7ecad462443a80d4e33bf4d9a0c4809
generated: "2026-11-29T14:32:37.663556+03:30"
yaml
# shop-laravel defaults. One app image (php-fpm) runs as web, worker, scheduler and migrator;
# one web image (Nginx with public/ baked in) fronts php-fpm inside each web pod.

fullnameOverride: ""

image:
  repository: ghcr.io/acme/shop-app
  tag: ""
  digest: ""
  pullPolicy: IfNotPresent

# UID of www-data in the app image (php:8.4-fpm-trixie, Debian base-passwd): 33
phpUid: 33

webImage:
  repository: ghcr.io/acme/shop-web
  tag: ""
  digest: ""

# Plain settings rendered as env on every Laravel container (web, worker, scheduler, migrate)
env:
  APP_ENV: production
  APP_DEBUG: "false"
  APP_URL: https://shop.example.test
  LOG_CHANNEL: stderr
  DB_CONNECTION: pgsql
  DB_HOST: ""
  DB_PORT: "5432"
  DB_DATABASE: shop
  CACHE_STORE: redis
  QUEUE_CONNECTION: redis
  SESSION_DRIVER: redis
  REDIS_HOST: ""

# Secret values (APP_KEY, DB_PASSWORD, REDIS_PASSWORD) live in a Secret the chart does NOT create:
# External Secrets Operator, Sealed Secrets or SOPS put it there before the release is installed.
existingSecret: ""

web:
  replicaCount: 2
  resources:
    php:
      requests: { cpu: 200m, memory: 192Mi }
      limits: { memory: 384Mi }
    nginx:
      requests: { cpu: 50m, memory: 32Mi }
      limits: { memory: 64Mi }
  autoscaling:
    enabled: false
    minReplicas: 2
    maxReplicas: 8
    targetCPUUtilizationPercentage: 70

worker:
  enabled: true
  replicaCount: 1
  queues: default
  # the worker exits after maxTime seconds and Kubernetes restarts it (frees leaked memory)
  maxTime: 3600
  tries: 3
  # must exceed the longest job, or SIGKILL interrupts it on every rollout
  terminationGracePeriodSeconds: 120
  resources:
    requests: { cpu: 100m, memory: 192Mi }
    limits: { memory: 384Mi }

scheduler:
  enabled: true
  # schedule:run every minute, exactly as Laravel's documented cron entry
  schedule: "* * * * *"
  resources:
    requests: { cpu: 50m, memory: 128Mi }
    limits: { memory: 256Mi }

migrations:
  enabled: true
  # Job runs before install and before every upgrade; a failure stops the release
  hooks: pre-install,pre-upgrade
  # no automatic retry of a half-applied migration; a failed Job is kept for its logs
  backoffLimit: 0
  activeDeadlineSeconds: 600

service:
  port: 80
json
{
  "$schema": "https://json-schema.org/draft-07/schema#",
  "title": "shop-laravel values",
  "type": "object",
  "required": ["image", "webImage", "env", "existingSecret"],
  "properties": {
    "image": {
      "type": "object",
      "required": ["repository"],
      "properties": {
        "repository": { "type": "string", "minLength": 1 },
        "tag": { "type": "string" },
        "digest": { "type": "string", "pattern": "^(sha256:[a-f0-9]{64})?$" }
      }
    },
    "existingSecret": { "type": "string" },
    "env": {
      "type": "object",
      "additionalProperties": { "type": "string" },
      "propertyNames": {
        "not": { "enum": ["APP_KEY", "DB_PASSWORD", "REDIS_PASSWORD", "AWS_SECRET_ACCESS_KEY"] }
      }
    },
    "worker": {
      "type": "object",
      "properties": {
        "maxTime": { "type": "integer", "minimum": 60 },
        "terminationGracePeriodSeconds": { "type": "integer", "minimum": 30 }
      }
    },
    "scheduler": {
      "type": "object",
      "properties": { "schedule": { "type": "string", "minLength": 9 } }
    }
  }
}

The helpers render the Laravel environment inline from a named template, so every container (including the migration hook, which runs before any chart object exists) gets the same settings, and fail the render when the externally managed Secret is not named:

text
{{/* shop-laravel helpers; labels and images come from the acme-lib library chart. */}}

{{- define "shop-laravel.fullname" -}}
{{- include "acme-lib.fullname" (dict "ctx" .) -}}
{{- end }}

{{/*
Environment shared by every Laravel container. Rendered inline (not from a ConfigMap) so the
pre-install migration hook, which runs before any release resource exists, sees the same values.
*/}}
{{- define "shop-laravel.env" -}}
{{- range $name, $value := .Values.env }}
- name: {{ $name }}
  value: {{ $value | quote }}
{{- end }}
{{- end }}

{{/* Credentials: a Secret created outside the chart. An empty name fails the render. */}}
{{- define "shop-laravel.envFrom" -}}
- secretRef:
    name: {{ required "existingSecret is required: create the Secret with External Secrets, SOPS or Sealed Secrets first" .Values.existingSecret }}
{{- end }}

{{/*
The php-fpm container spec shared by web, worker, scheduler and migrate. The role is set with
args, not command: the image's ENTRYPOINT (app-entrypoint: php artisan optimize, then
exec docker-php-entrypoint "$@") must still run, so every role caches config from this env.
*/}}
{{- define "shop-laravel.appContainer" -}}
{{- $root := .root -}}
- name: {{ .name }}
  image: {{ include "acme-lib.image" (dict "image" $root.Values.image "ctx" $root) | quote }}
  imagePullPolicy: {{ $root.Values.image.pullPolicy }}
  {{- with .args }}
  args:
    {{- toYaml . | nindent 4 }}
  {{- end }}
  env:
    {{- /* trim: the range in shop-laravel.env starts with a newline */}}
    {{- include "shop-laravel.env" $root | trim | nindent 4 }}
  envFrom:
    {{- include "shop-laravel.envFrom" $root | nindent 4 }}
  resources:
    {{- toYaml .resources | nindent 4 }}
  securityContext:
    {{- /* www-data in the Debian-based php:8.4-fpm-trixie image is UID 33 */}}
    {{- include "acme-lib.containerSecurityContext" (dict "uid" $root.Values.phpUid) | nindent 4 }}
{{- end }}

The php-fpm + nginx chart part: one web pod with both containers (FastCGI stays on 127.0.0.1:9000 inside the pod; readiness is Laravel's /up through Nginx), and the Nginx config as a ConfigMap whose checksum rolls the pods:

yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: {{ include "shop-laravel.fullname" . }}-web
  labels:
    {{- include "acme-lib.labels" (dict "ctx" . "component" "web") | nindent 4 }}
spec:
  {{- if not .Values.web.autoscaling.enabled }}
  replicas: {{ .Values.web.replicaCount }}
  {{- end }}
  selector:
    matchLabels:
      {{- include "acme-lib.selectorLabels" (dict "ctx" . "component" "web") | nindent 6 }}
  template:
    metadata:
      annotations:
        checksum/nginx: {{ include (print $.Template.BasePath "/configmap-nginx.yaml") . | sha256sum }}
      labels:
        {{- include "acme-lib.labels" (dict "ctx" . "component" "web") | nindent 8 }}
    spec:
      automountServiceAccountToken: false
      # Pod level: only seccomp. php-fpm pins UID 33 in its container context; the web image
      # (nginx:1.28-alpine from Images & Dockerfiles) starts its master as root, so the pod
      # cannot force runAsNonRoot. Switch to an unprivileged Nginx image to harden it.
      securityContext:
        seccompProfile:
          type: RuntimeDefault
      containers:
        {{- include "shop-laravel.appContainer" (dict "root" . "name" "php-fpm" "resources" .Values.web.resources.php) | nindent 8 }}
          ports:
            - name: fastcgi
              containerPort: 9000
          livenessProbe:
            tcpSocket:
              port: fastcgi
            periodSeconds: 10
        - name: nginx
          image: {{ include "acme-lib.image" (dict "image" .Values.webImage "ctx" .) | quote }}
          ports:
            - name: http
              containerPort: 8080
          readinessProbe:
            # /up is Laravel's health route: Nginx -> php-fpm -> app booted
            httpGet:
              path: /up
              port: http
            periodSeconds: 5
          volumeMounts:
            - name: nginx-conf
              mountPath: /etc/nginx/conf.d
              readOnly: true
          resources:
            {{- toYaml .Values.web.resources.nginx | nindent 12 }}
      volumes:
        - name: nginx-conf
          configMap:
            name: {{ include "shop-laravel.fullname" . }}-nginx
yaml
apiVersion: v1
kind: ConfigMap
metadata:
  name: {{ include "shop-laravel.fullname" . }}-nginx
  labels:
    {{- include "acme-lib.labels" (dict "ctx" . "component" "web") | nindent 4 }}
data:
  # php-fpm runs in the same pod, so FastCGI goes to localhost and never leaves the pod
  default.conf: |
    server {
        listen 8080;
        root /var/www/html/public;
        index index.php;
        charset utf-8;
        location / {
            try_files $uri $uri/ /index.php?$query_string;
        }
        location = /favicon.ico { access_log off; log_not_found off; }
        location ~ ^/index\.php(/|$) {
            fastcgi_pass 127.0.0.1:9000;
            fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
            include fastcgi_params;
            fastcgi_hide_header X-Powered-By;
        }
        location ~ /\.(?!well-known).* { deny all; }
    }

The queue worker (queue:work as exec-form args with --max-time, a grace period longer than the longest job), the scheduler CronJob (schedule:run every minute, concurrencyPolicy: Forbid) and the Laravel migrate hook Job:

yaml
{{- if .Values.worker.enabled }}
apiVersion: apps/v1
kind: Deployment
metadata:
  name: {{ include "shop-laravel.fullname" . }}-worker
  labels:
    {{- include "acme-lib.labels" (dict "ctx" . "component" "worker") | nindent 4 }}
spec:
  replicas: {{ .Values.worker.replicaCount }}
  selector:
    matchLabels:
      {{- include "acme-lib.selectorLabels" (dict "ctx" . "component" "worker") | nindent 6 }}
  template:
    metadata:
      labels:
        {{- include "acme-lib.labels" (dict "ctx" . "component" "worker") | nindent 8 }}
    spec:
      automountServiceAccountToken: false
      # SIGTERM -> the worker finishes the current job, then exits; SIGKILL only after this
      terminationGracePeriodSeconds: {{ .Values.worker.terminationGracePeriodSeconds }}
      securityContext:
        {{- include "acme-lib.podSecurityContext" (dict "uid" .Values.phpUid) | nindent 8 }}
      containers:
        {{- $cmd := list "php" "artisan" "queue:work" (printf "--queue=%s" .Values.worker.queues) (printf "--max-time=%d" (int .Values.worker.maxTime)) (printf "--tries=%d" (int .Values.worker.tries)) }}
        {{- include "shop-laravel.appContainer" (dict "root" . "name" "worker" "args" $cmd "resources" .Values.worker.resources) | nindent 8 }}
{{- end }}
yaml
{{- if .Values.scheduler.enabled }}
apiVersion: batch/v1
kind: CronJob
metadata:
  name: {{ include "shop-laravel.fullname" . }}-scheduler
  labels:
    {{- include "acme-lib.labels" (dict "ctx" . "component" "scheduler") | nindent 4 }}
spec:
  schedule: {{ .Values.scheduler.schedule | quote }}
  # never two schedule:run at once; a late run is skipped rather than piled up
  concurrencyPolicy: Forbid
  startingDeadlineSeconds: 30
  successfulJobsHistoryLimit: 1
  failedJobsHistoryLimit: 3
  jobTemplate:
    spec:
      backoffLimit: 0
      template:
        metadata:
          labels:
            {{- include "acme-lib.labels" (dict "ctx" . "component" "scheduler") | nindent 12 }}
        spec:
          restartPolicy: Never
          automountServiceAccountToken: false
          securityContext:
            {{- include "acme-lib.podSecurityContext" (dict "uid" .Values.phpUid) | nindent 12 }}
          containers:
            {{- include "shop-laravel.appContainer" (dict "root" . "name" "schedule-run" "args" (list "php" "artisan" "schedule:run") "resources" .Values.scheduler.resources) | nindent 12 }}
{{- end }}
yaml
{{- if .Values.migrations.enabled }}
{{- /*
A hook Job: not part of the release manifest. Helm creates it before install/upgrade,
waits for it to complete and aborts the release if it fails, so new code never starts on an
old schema. A Job is NOT exactly-once (Kubernetes may start its program twice even with
completions 1 and restartPolicy Never), so migrate runs with --isolated: a second concurrent
run waits for nothing and exits 0 while the cache lock (CACHE_STORE=redis) is held. It uses only the image, inline env and the externally created Secret, because
on the first install nothing else from this chart exists yet.
*/}}
apiVersion: batch/v1
kind: Job
metadata:
  name: {{ include "shop-laravel.fullname" . }}-migrate
  labels:
    {{- include "acme-lib.labels" (dict "ctx" . "component" "migrate") | nindent 4 }}
  annotations:
    "helm.sh/hook": {{ .Values.migrations.hooks }}
    "helm.sh/hook-weight": "-5"
    # delete the old Job before creating the new one; delete it on success, keep it (and its logs) on failure
    "helm.sh/hook-delete-policy": before-hook-creation,hook-succeeded
spec:
  backoffLimit: {{ .Values.migrations.backoffLimit }}
  activeDeadlineSeconds: {{ .Values.migrations.activeDeadlineSeconds }}
  template:
    metadata:
      labels:
        {{- include "acme-lib.labels" (dict "ctx" . "component" "migrate") | nindent 8 }}
    spec:
      restartPolicy: Never
      automountServiceAccountToken: false
      securityContext:
        {{- include "acme-lib.podSecurityContext" (dict "uid" .Values.phpUid) | nindent 8 }}
      containers:
        {{- include "shop-laravel.appContainer" (dict "root" . "name" "migrate" "args" (list "php" "artisan" "migrate" "--force" "--isolated") "resources" .Values.worker.resources) | nindent 8 }}
{{- end }}

The Service, HPA, notes and helm test Pod (service.yaml, hpa.yaml, NOTES.txt, tests/test-up.yaml) are in the same directory; the test fetches /up through the Service.

yaml
apiVersion: v1
kind: Pod
metadata:
  name: {{ include "shop-laravel.fullname" . }}-test-up
  labels:
    {{- include "acme-lib.labels" (dict "ctx" . "component" "test") | nindent 4 }}
  annotations:
    "helm.sh/hook": test
    "helm.sh/hook-delete-policy": before-hook-creation,hook-succeeded
spec:
  restartPolicy: Never
  securityContext:
    runAsNonRoot: true
    runAsUser: 65532
  containers:
    - name: up
      image: busybox:1.37
      # GET /up through the Service: Nginx -> php-fpm -> Laravel must answer 200
      command: ["wget", "-q", "-O-", "http://{{ include "shop-laravel.fullname" . }}:{{ .Values.service.port }}/up"]

The Laravel angle ​

  • Migrations before the code, serialised by a lock. A hook Job is not exactly-once: the Jobs docs warn that "even if you specify .spec.parallelism = 1 and .spec.completions = 1 and .spec.template.spec.restartPolicy = "Never", the same program may sometimes be started twice". The chart therefore runs php artisan migrate --force --isolated: --force skips the production prompt ("To force the commands to run without a prompt, use the --force flag") and --isolated makes Laravel "acquire an atomic lock using your application's cache driver before attempting to run your migrations", so a second concurrent run "will not execute; however, the command will still exit with a successful exit status code" (the lock needs a shared cache store; the chart uses CACHE_STORE: redis). backoffLimit: 0 avoids automatic retries of a half-applied migration. What you get is "before the new code, at most one migrator at a time", not "exactly once": a migration that died halfway is re-run on the next release, so each migration must be safe to re-run. Under Argo CD the hook runs on every sync, which is harmless for already-applied migrations.
  • Expand, then contract. The hook runs while old pods still serve. A migration that drops or renames a column breaks the old code during the rollout and makes --rollback-on-failure useless (the rollback restores old code, not the old schema). Two releases per breaking change; see Zero-Downtime Schema Migrations.
  • The scheduler is a CronJob, not a daemon. Laravel's documented setup is to "add a single cron configuration entry to our server that runs the schedule:run command every minute"; the CronJob is that entry. With sub-minute tasks, "the schedule:run command will continue running until the end of the current minute", which fits concurrencyPolicy: Forbid. The alternative is one schedule:work Deployment with a single replica.
  • Workers drain on SIGTERM. queue:work finishes the current job on SIGTERM; terminationGracePeriodSeconds (120 s here) must exceed the longest job, and --max-time=3600 makes each worker exit hourly ("process jobs for the given number of seconds and then exit"), which Kubernetes restarts, releasing leaked memory. Note Laravel's warning that block_for of 0 "will also prevent signals such as SIGTERM from being handled until the next job has been processed".
  • Config caching at start, in every role. The image's entrypoint (app-entrypoint from Images & Dockerfiles) runs php artisan optimize and then exec docker-php-entrypoint "$@", so the cache sees the env the chart rendered; never config:cache at build time. That is why the chart sets each role with args: (php artisan queue:work ...) and never command:: a Kubernetes command replaces the image's ENTRYPOINT, and the worker, scheduler and migration would skip the entrypoint.
  • Users. The php:8.4-fpm-trixie image is built FROM debian:trixie-slim and runs FPM as www-data (--with-fpm-user=www-data in its Dockerfile); Debian's base-passwd fixes www-data:*:33:33, so phpUid: 33 pins every PHP container with runAsNonRoot. The web image from the same chapter is nginx:1.28-alpine, whose master process starts as root; the web pod therefore sets only seccomp at pod level, and an unprivileged Nginx image is the hardening step (Container Security).
  • APP_KEY is a Secret, not a value. The schema's propertyNames rule rejects APP_KEY, DB_PASSWORD, REDIS_PASSWORD under env; the test TestShopLaravel proves the render fails. The Secret comes from External Secrets (Configuration, Secrets & Storage).
  • Health route. Readiness goes through Nginx to /up, which Laravel serves when the app boots; a listener on DiagnosingHealth can add a database check, but keep liveness local (php-fpm's TCP socket) so a database blip does not restart every pod:
php
<?php
// app/Providers/AppServiceProvider.php (excerpt): make /up fail when the database is unreachable,
// so the web pod leaves the Service during an outage but is not restarted by liveness.
namespace App\Providers;

use Illuminate\Foundation\Events\DiagnosingHealth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Event;
use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    public function boot(): void
    {
        Event::listen(DiagnosingHealth::class, function (): void {
            DB::connection()->getPdo(); // throws -> /up answers 500 -> readiness fails
        });
    }
}

Kustomize overlay set: dev, staging, prod ​

The same orders-api as plain YAML: a base, a reusable HPA component, and three overlays. All three were rendered with kubectl kustomize on the build host; the outputs live in go/manifestcheck/testdata/ and are checked by TestKustomizeOutputsAreClean.

yaml
# Base: the environment-neutral orders-api. Overlays reference this directory; it never knows them.
apiVersion: kustomize.config.k8s.io/v1beta1
kind: Kustomization
resources:
  - deployment.yaml
  - service.yaml
# labels (not the deprecated commonLabels). includeSelectors: true adds them to selectors too,
# so set them ONCE in the base and never change them: selectors are immutable.
labels:
  - pairs:
      app.kubernetes.io/name: orders-api
      app.kubernetes.io/part-of: shop
    includeSelectors: true
configMapGenerator:
  - name: orders-api-config
    envs:
      - app.env
images:
  - name: orders-api
    newName: ghcr.io/acme/orders-api
    newTag: "1.4.2"
yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: orders-api
spec:
  replicas: 2
  selector:
    matchLabels: {}
  template:
    metadata:
      labels: {}
    spec:
      automountServiceAccountToken: false
      terminationGracePeriodSeconds: 30
      securityContext:
        runAsNonRoot: true
        runAsUser: 65532
        runAsGroup: 65532
        seccompProfile:
          type: RuntimeDefault
      containers:
        - name: orders-api
          # placeholder name; the images: field in kustomization.yaml sets the real reference
          image: orders-api
          ports:
            - name: http
              containerPort: 8080
          envFrom:
            # the generator's output is renamed orders-api-config-<hash>; Kustomize rewrites this
            - configMapRef:
                name: orders-api-config
          readinessProbe:
            httpGet:
              path: /readyz
              port: http
          livenessProbe:
            httpGet:
              path: /healthz
              port: http
          resources:
            requests:
              cpu: 100m
              memory: 64Mi
            limits:
              memory: 128Mi
          securityContext:
            allowPrivilegeEscalation: false
            readOnlyRootFilesystem: true
            capabilities:
              drop: ["ALL"]
text
APP_ENV=dev
LOG_LEVEL=info
SHUTDOWN_TIMEOUT=8s
DATABASE_HOST=postgres.shop-dev.svc.cluster.local
yaml
# A Component: an opt-in feature that several overlays (staging, prod) include.
apiVersion: kustomize.config.k8s.io/v1alpha1
kind: Component
resources:
  - hpa.yaml
patches:
  # the HPA owns the replica count from now on: drop spec.replicas from the Deployment
  - target:
      kind: Deployment
      name: orders-api
    patch: |-
      - op: remove
        path: /spec/replicas
yaml
# dev: kubectl apply -k overlays/dev   (or: kustomize build overlays/dev | kubectl apply -f -)
apiVersion: kustomize.config.k8s.io/v1beta1
kind: Kustomization
namespace: shop-dev
namePrefix: dev-
resources:
  - ../../base
# extra labels WITHOUT selectors: safe to change later
labels:
  - pairs:
      app.kubernetes.io/environment: dev
images:
  - name: ghcr.io/acme/orders-api
    newTag: "1.5.0-rc.1"
replicas:
  - name: orders-api
    count: 1
configMapGenerator:
  - name: orders-api-config
    behavior: merge
    literals:
      - LOG_LEVEL=debug
      - SELF_URL=http://placeholder
# A generated Secret is fine for a throwaway dev database only; real environments reference a
# Secret that External Secrets (or SOPS/Sealed Secrets) creates. Values here end up in Git.
secretGenerator:
  - name: orders-api-db
    literals:
      - DATABASE_PASSWORD=dev-only-not-a-secret
patches:
  - path: patch-dev-resources.yaml
  - target:
      kind: Deployment
      name: orders-api
    patch: |-
      - op: add
        path: /spec/template/spec/containers/0/envFrom/-
        value:
          secretRef:
            name: orders-api-db
# namePrefix renamed the Service to dev-orders-api; copy the final name into the config
replacements:
  - source:
      kind: Service
      name: orders-api
      fieldPath: metadata.name
    targets:
      - select:
          kind: ConfigMap
          name: orders-api-config
        fieldPaths:
          - data.SELF_URL
        options:
          delimiter: "/"
          index: 2
yaml
# strategic merge patch: containers merge by name, so only the listed fields change
apiVersion: apps/v1
kind: Deployment
metadata:
  name: orders-api
spec:
  template:
    spec:
      containers:
        - name: orders-api
          imagePullPolicy: Always
          resources:
            requests:
              cpu: 50m
              memory: 32Mi
            limits:
              memory: 96Mi
yaml
apiVersion: kustomize.config.k8s.io/v1beta1
kind: Kustomization
namespace: shop-staging
resources:
  - ../../base
components:
  - ../../components/hpa
labels:
  - pairs:
      app.kubernetes.io/environment: staging
images:
  - name: ghcr.io/acme/orders-api
    newTag: "1.4.2"
configMapGenerator:
  - name: orders-api-config
    behavior: merge
    literals:
      - APP_ENV=staging
      - DATABASE_HOST=orders-db.staging.internal
patches:
  # the Secret is created by External Secrets in this namespace; the overlay only references it
  - target:
      kind: Deployment
      name: orders-api
    patch: |-
      - op: add
        path: /spec/template/spec/containers/0/envFrom/-
        value:
          secretRef:
            name: orders-api-db
  - target:
      kind: HorizontalPodAutoscaler
      name: orders-api
    patch: |-
      - op: replace
        path: /spec/maxReplicas
        value: 4
yaml
apiVersion: kustomize.config.k8s.io/v1beta1
kind: Kustomization
namespace: shop-prod
resources:
  - ../../base
  - pdb.yaml
components:
  - ../../components/hpa
labels:
  - pairs:
      app.kubernetes.io/environment: prod
images:
  # prod is pinned by digest (placeholder value; CI or an image-automation bot writes the real one)
  - name: ghcr.io/acme/orders-api
    digest: sha256:0b7e2a3c5d9f41e6a8b1c2d3e4f5a6b7c8d9e0f1a2b3c4d5e6f7a8b9c0d1e2f3
configMapGenerator:
  - name: orders-api-config
    behavior: merge
    literals:
      - APP_ENV=prod
      - DATABASE_HOST=orders-db.prod.internal
patches:
  - path: patch-prod-spread.yaml
  - target:
      kind: Deployment
      name: orders-api
    patch: |-
      - op: add
        path: /spec/template/spec/containers/0/envFrom/-
        value:
          secretRef:
            name: orders-api-db
  - target:
      kind: HorizontalPodAutoscaler
      name: orders-api
    patch: |-
      - op: replace
        path: /spec/minReplicas
        value: 3
      - op: replace
        path: /spec/maxReplicas
        value: 20
yaml
# Only the base's own resources receive the base's labels (and selectors). A resource added
# here gets the overlay's labels only, so the selector is written out by hand: an EMPTY
# policy/v1 PDB selector would select every pod in the namespace.
apiVersion: policy/v1
kind: PodDisruptionBudget
metadata:
  name: orders-api
spec:
  maxUnavailable: 1
  selector:
    matchLabels:
      app.kubernetes.io/name: orders-api
      app.kubernetes.io/part-of: shop

The hybrid: the chart's real rendered output (--skip-tests) as a Kustomize resource, plus the last-mile changes the chart has no values for:

yaml
# "helm template | kustomize": the chart renders, Kustomize applies the last-mile changes the
# chart has no value for. orders-api.rendered.yaml is the real output of
#   go run ./cmd/helm4 template orders-api ../charts/orders-api -n shop-prod -f .../values-prod.yaml
# (scripts/render-charts.sh). In Argo CD or Flux the same split is a post-renderer or a
# Kustomization pointing at rendered output.
apiVersion: kustomize.config.k8s.io/v1beta1
kind: Kustomization
resources:
  - orders-api.rendered.yaml
labels:
  - pairs:
      cost-center: cc-4711
patches:
  # the platform team's sidecar policy: a fixed annotation the chart does not expose
  - target:
      kind: Deployment
      name: orders-api
    patch: |-
      - op: add
        path: /spec/template/metadata/annotations/cluster-autoscaler.kubernetes.io~1safe-to-evict
        value: "true"

The scripts that produced the real outputs, and the deploy script (cluster needed, expected, not run):

bash
#!/usr/bin/env bash
# Render every Kustomize overlay with the Kustomize built into kubectl (no cluster needed) and
# save the output where the Go tests (go/manifestcheck) read it. Standalone: kustomize build <dir>.
set -euo pipefail
cd "$(dirname "$0")/.."
out=go/manifestcheck/testdata
mkdir -p "$out"
kubectl version --client
for env in dev staging prod; do
  kubectl kustomize "kustomize/orders-api/overlays/$env" > "$out/kustomize-$env.yaml"
  printf '%-8s %3d objects  %s\n' "$env" "$(grep -c '^kind:' "$out/kustomize-$env.yaml")" \
    "$(grep -E '^  name: ' "$out/kustomize-$env.yaml" | awk '{print $2}' | tr '\n' ' ')"
done
# helm template piped to kustomize: post-process the chart's output with a last-mile overlay
kubectl kustomize kustomize/helm-post > "$out/helm-post.yaml"
echo "helm-post $(grep -c '^kind:' "$out/helm-post.yaml") objects"
bash
#!/usr/bin/env bash
# Lint and render both charts with the Helm 4 CLI code. On a machine with helm installed, replace
# "$HELM" with helm; here no helm binary exists, so ./go/cmd/helm4 is built from helm.sh/helm/v4.
set -euo pipefail
cd "$(dirname "$0")/.."
work=$(mktemp -d)
export HELM_CONFIG_HOME=$work/config HELM_CACHE_HOME=$work/cache HELM_DATA_HOME=$work/data
# HELM_BIN=/some/path keeps the built binary for later commands (the Lab uses /tmp/helm4)
HELM=${HELM_BIN:-$work/helm}
(cd go && go build -ldflags "$(sed -n '/^const LDFlags = /,/Minor=34"$/p' chartcheck/doc.go | grep -o '"[^"]*"' | tr -d '"' | tr '\n' ' ')" -o "$HELM" ./cmd/helm4)
"$HELM" version --short

for env in dev staging prod; do
  "$HELM" lint --strict charts/orders-api -f "charts/orders-api/values-$env.yaml"
done
# the values ct install uses must render too
"$HELM" template orders-api charts/orders-api -f charts/orders-api/ci/kind-values.yaml > /dev/null
echo "orders-api ci/kind-values.yaml renders"
# --skip-tests: a "helm test" Pod in rendered output would be applied as an ordinary Pod
"$HELM" template orders-api charts/orders-api -n shop-prod -f charts/orders-api/values-prod.yaml \
  --skip-tests > kustomize/helm-post/orders-api.rendered.yaml

# the Laravel chart vendors its library dependency first (writes charts/ and Chart.lock in a copy)
cp -R charts/acme-lib charts/shop-laravel "$work/"
"$HELM" dependency build "$work/shop-laravel"
"$HELM" lint --strict "$work/shop-laravel" -f "$work/shop-laravel/values-prod.yaml"
"$HELM" template shop "$work/shop-laravel" -n shop-prod -f "$work/shop-laravel/values-prod.yaml" \
  > "$work/shop-laravel.rendered.yaml"
grep -c '^kind:' "$work/shop-laravel.rendered.yaml"
"$HELM" template shop "$work/shop-laravel" -f "$work/shop-laravel/ci/kind-values.yaml" > /dev/null
echo "shop-laravel ci/kind-values.yaml renders"
bash
#!/usr/bin/env bash
# Deploy one environment of orders-api from the OCI registry. Needs a cluster (expected, not run).
# usage: scripts/release.sh prod 1.3.0
set -euo pipefail
env=${1:?env}; version=${2:?chart version}
ns=shop-$env
chart=oci://ghcr.io/acme/charts/orders-api
values=charts/orders-api/values-$env.yaml

helm version --short   # v4.x expected; on Helm 3 use --atomic instead of --rollback-on-failure

# 1. What would change? (helm-diff plugin; three-way so kubectl edits in the cluster show up).
#    --allow-unreleased: on the first deploy there is no release yet; without it the diff fails
#    and set -e stops the script before the install. Exit code 2 = changes found (expected).
rc=0
helm diff upgrade orders-api "$chart" --version "$version" -n "$ns" -f "$values" \
  --allow-unreleased --three-way-merge --detailed-exitcode || rc=$?
[ "$rc" -eq 0 ] || [ "$rc" -eq 2 ] || exit "$rc"

# 2. Install or upgrade, wait for readiness, roll back automatically on failure or timeout
helm upgrade --install orders-api "$chart" --version "$version" \
  --namespace "$ns" --create-namespace \
  -f "$values" \
  --rollback-on-failure --wait --timeout 5m \
  --history-max 10

# 3. Smoke test and record
helm test orders-api -n "$ns" --logs
helm history orders-api -n "$ns" --max 5
# Manual rollback to the previous revision if a problem shows up later:
#   helm rollback orders-api 0 -n "$ns" --wait

The CI workflow (GitHub Actions; the same stages map onto a GitLab CI pipeline with helm, ct and kubeconform in a job image): ct lint, helm unittest, kubeconform for every environment of both the chart and the overlays, ct install in kind, then package, push to an OCI registry and sign by digest. ct install uses each chart's ci/*-values.yaml (without one it installs with the defaults, which fail here on the required database host), so both charts ship ci/kind-values.yaml, and the workflow first creates a ct namespace with a throwaway Postgres, Redis and the two Secrets the charts expect (scripts/render-charts.sh checks that both CI values files render; the images must also be pullable from kind):

yaml
# .github/workflows/chart-ci.yml - lint, unit-test, schema-validate, install-test, then publish
# the chart to an OCI registry and sign it. Versions are the ones the actions' READMEs show
# (2026-11-29); pin them by commit SHA in real use.
name: chart-ci
on:
  pull_request:
    paths: ["charts/**", "kustomize/**"]
  push:
    tags: ["orders-api-*"]

permissions:
  contents: read

jobs:
  lint-test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v7
        with:
          fetch-depth: 0 # ct compares against the target branch to find changed charts
      - uses: azure/setup-helm@v5
        with:
          version: v4.3.1
      - uses: actions/setup-python@v6.0.0
        with:
          python-version: "3.x"
      - uses: helm/chart-testing-action@v2.8.0
      - name: ct lint (version bump, schema of Chart.yaml, helm lint)
        run: ct lint --target-branch ${{ github.event.repository.default_branch }} --chart-dirs charts --check-version-increment
      - name: helm-unittest
        run: |
          helm plugin install https://github.com/helm-unittest/helm-unittest.git
          helm unittest charts/orders-api
      - name: render and validate against the Kubernetes OpenAPI schemas
        run: |
          go install github.com/yannh/kubeconform/cmd/kubeconform@latest
          for env in dev staging prod; do
            helm template orders-api charts/orders-api -f charts/orders-api/values-$env.yaml \
              | "$(go env GOPATH)/bin/kubeconform" -strict -summary -kubernetes-version 1.35.0
            kubectl kustomize kustomize/orders-api/overlays/$env \
              | "$(go env GOPATH)/bin/kubeconform" -strict -summary -kubernetes-version 1.35.0
          done
      - uses: helm/kind-action@v1.15.1
        if: github.event_name == 'pull_request'
      # ct installs each chart once per charts/<chart>/ci/*-values.yaml. Those files point at the
      # throwaway Postgres/Redis and Secrets created here; the images must be pullable by kind
      # (load them with `kind load docker-image` after building, or pull from the registry).
      - name: pre-provision dependencies for ct install
        if: github.event_name == 'pull_request'
        run: |
          kubectl create namespace ct
          kubectl -n ct create deployment postgres --image=postgres:18 --port=5432
          kubectl -n ct set env deployment/postgres POSTGRES_PASSWORD=ci-only POSTGRES_DB=shop
          kubectl -n ct expose deployment postgres --port=5432
          kubectl -n ct create deployment redis --image=redis:8 --port=6379
          kubectl -n ct expose deployment redis --port=6379
          kubectl -n ct create secret generic orders-api-db --from-literal=DATABASE_PASSWORD=ci-only
          kubectl -n ct create secret generic shop-laravel-secrets \
            --from-literal=APP_KEY="base64:$(openssl rand -base64 32)" --from-literal=DB_PASSWORD=ci-only
          kubectl -n ct rollout status deployment/postgres deployment/redis --timeout=120s
      - name: ct install (real install + helm test in a throwaway kind cluster)
        if: github.event_name == 'pull_request'
        run: ct install --target-branch ${{ github.event.repository.default_branch }} --chart-dirs charts --namespace ct

  publish:
    needs: lint-test
    if: startsWith(github.ref, 'refs/tags/')
    runs-on: ubuntu-latest
    permissions:
      contents: read
      packages: write
      id-token: write # keyless cosign signing via the workflow's OIDC identity
    steps:
      - uses: actions/checkout@v7
      - uses: azure/setup-helm@v5
        with:
          version: v4.3.1
      - uses: sigstore/cosign-installer@v4.1.4
      - name: package and push to ghcr.io (OCI)
        run: |
          echo "${{ secrets.GITHUB_TOKEN }}" | helm registry login ghcr.io -u "${{ github.actor }}" --password-stdin
          helm package charts/orders-api --destination dist
          helm push dist/orders-api-*.tgz oci://ghcr.io/${{ github.repository_owner }}/charts 2>&1 | tee push.log
          grep '^Digest:' push.log | awk '{print $2}' > digest.txt
      - name: sign the chart by digest
        run: cosign sign --yes "ghcr.io/${{ github.repository_owner }}/charts/orders-api@$(cat digest.txt)"

GitOps: the chart from an OCI registry and the staging overlay as Argo CD Applications, and the same pair as a Flux HelmRelease (real Helm releases, drift detection) and a Flux Kustomization. The controllers themselves are taught in GitOps.

yaml
# Argo CD renders the chart with `helm template` and applies the result itself: the release is
# NOT visible to `helm list`, and Helm hooks are mapped onto Argo CD sync hooks.
apiVersion: argoproj.io/v1alpha1
kind: Application
metadata:
  name: orders-api-prod
  namespace: argocd
spec:
  project: shop
  source:
    # an OCI chart repository: repoURL without oci://, chart = the repository basename
    repoURL: ghcr.io/acme/charts
    chart: orders-api
    targetRevision: 1.3.0
    helm:
      releaseName: orders-api
      valueFiles:
        - values-prod.yaml
      # a value that differs per cluster, kept out of the chart's files
      valuesObject:
        image:
          digest: sha256:0b7e2a3c5d9f41e6a8b1c2d3e4f5a6b7c8d9e0f1a2b3c4d5e6f7a8b9c0d1e2f3
  destination:
    server: https://kubernetes.default.svc
    namespace: shop-prod
  syncPolicy:
    automated:
      prune: true
      selfHeal: true
    syncOptions:
      - CreateNamespace=true
      - ServerSideApply=true
yaml
# The same app from the Kustomize overlay: Argo CD runs kustomize build on the path.
apiVersion: argoproj.io/v1alpha1
kind: Application
metadata:
  name: orders-api-staging
  namespace: argocd
spec:
  project: shop
  source:
    repoURL: https://github.com/acme/shop-deploy.git
    targetRevision: main
    path: kustomize/orders-api/overlays/staging
    kustomize:
      # Argo CD can set the image without a commit; image automation usually commits instead
      images:
        - ghcr.io/acme/orders-api:1.4.2
  destination:
    server: https://kubernetes.default.svc
    namespace: shop-staging
  syncPolicy:
    automated:
      prune: true
      selfHeal: true
yaml
# Flux: the source-controller fetches the chart from OCI, the helm-controller runs a real Helm
# install/upgrade (the release IS in `helm list`) and keeps remediating it.
apiVersion: source.toolkit.fluxcd.io/v1
kind: OCIRepository
metadata:
  name: orders-api-chart
  namespace: flux-system
spec:
  interval: 10m
  url: oci://ghcr.io/acme/charts/orders-api
  ref:
    semver: "1.3.x"
  layerSelector:
    mediaType: application/vnd.cncf.helm.chart.content.v1.tar+gzip
    operation: copy
---
apiVersion: helm.toolkit.fluxcd.io/v2
kind: HelmRelease
metadata:
  name: orders-api
  namespace: shop-prod
spec:
  interval: 10m
  releaseName: orders-api
  chartRef:
    kind: OCIRepository
    name: orders-api-chart
    namespace: flux-system
  install:
    remediation:
      retries: 3
  upgrade:
    remediation:
      retries: 3
      remediateLastFailure: true
    cleanupOnFail: true
  driftDetection:
    mode: enabled
  valuesFrom:
    # per-cluster values live in a ConfigMap next to the HelmRelease, not in the chart
    - kind: ConfigMap
      name: orders-api-values
      valuesKey: values.yaml
---
# Flux Kustomization (a Flux CRD, not kustomize.config.k8s.io): builds and applies an overlay.
apiVersion: kustomize.toolkit.fluxcd.io/v1
kind: Kustomization
metadata:
  name: orders-api-staging
  namespace: flux-system
spec:
  interval: 5m
  path: ./kustomize/orders-api/overlays/staging
  prune: true
  wait: true
  timeout: 3m
  sourceRef:
    kind: GitRepository
    name: shop-deploy
  targetNamespace: shop-staging

Solving the classic problems ​

ProblemSolutionHowAdvantageCost / limit
Copies per environment driftChart + values, or base + overlaysOne template/base; differences in values files or overlaysSmall, reviewable diffsA tool and its rules to learn
Upgrade resets the HPA's replicasOmit replicas when autoscalingif not .Values.autoscaling.enabled / component removes /spec/replicasHPA keeps controlInitial count comes from the HPA min
Config change does not reach podsChecksum annotation / generator hashsha256sum of the rendered ConfigMap; configMapGeneratorAutomatic rolloutOld hashed ConfigMaps need pruning
Bad values reach the clusterSchema + requiredvalues.schema.json with enums/patterns; required messagesFails in CI, with the pathSchema maintenance
Secrets in values or GitexistingSecret + External SecretsChart references a Secret it does not createNothing secret in Git or release SecretsSecret must exist before install
Migrations race the rolloutPre-upgrade hook Jobpre-install,pre-upgrade, weight, delete policyOnce per release, before new codeMust be backwards compatible
Failed deploy leaves a half-upgraded app--rollback-on-failure --wait --timeoutHelm 4 (Helm 3: --atomic)Automatic undoHides failing pods: log events first
Selector change blocks upgradesStable selector labelsselectorLabels without versions; labels not commonLabelsUpgrades never hit immutable fieldsLabel scheme fixed forever
CRD changes never appliedSeparate CRD stepkubectl apply --server-side -f crds/ before helm upgrade, or a CRD chart with resource-policy: keepCRDs actually upgradeOrdering in the pipeline
Third-party chart lacks a knobPost-render with Kustomizehelm template piped to kustomize, or Flux postRenderersNo fork of the chartHooks and releases lost when rendered

Every environment from one source ​

Charts: values.yaml holds defaults safe for dev, values-staging.yaml and values-prod.yaml hold only differences, and CI renders all three. Overlays: the base is the common version, each overlay sets namespace, image and sizes. Either way the "what differs" list should fit on one screen; if it does not, the values surface is too large.

Upgrades that keep autoscaling intact ​

With client-side apply, every upgrade that renders spec.replicas sets it back. The orders-api chart renders replicas only when autoscaling.enabled is false; the Kustomize hpa component deletes the field; manifestcheck fails any render that contains both a replicas and an HPA for the same Deployment.

Configuration rollouts ​

Pods read env vars at start, so a changed ConfigMap does nothing until pods restart. Helm: put checksum/config (the sha256sum of the rendered ConfigMap) into the pod template. Kustomize: generated ConfigMaps get a new name on every change. Both change the pod template, which is what triggers a Deployment rollout.

Secrets without values ​

Charts take existingSecret and fail the render without it (required); schemas reject password-like keys. The Secret is created by External Secrets from Vault or a cloud secret manager, or decrypted by SOPS in the GitOps controller. Never --set password=... in CI: it is stored in the release Secret and visible in helm get values.

Migrations once per release, one at a time ​

One hook Job before install and upgrade, weight -5, delete policy before-hook-creation,hook-succeeded, backoffLimit: 0, activeDeadlineSeconds below Helm's --timeout, using only objects that exist before the release, running migrate --force --isolated so a duplicate start of the Job (which Kubernetes does not rule out) finds the cache lock held and exits successfully without migrating, instead of migrating twice. That is at-most-one-concurrent, not exactly-once: migrations must tolerate a re-run after a crash. In Kustomize-only setups the equivalent is an Argo CD PreSync hook or a Flux Kustomization that depends on (dependsOn) a migration Kustomization.

Last-mile changes to someone else's chart ​

Render with helm template --skip-tests (and --no-hooks if hooks must not become ordinary objects), treat the output as a Kustomize resource and patch it (this chapter's helm-post), or use Flux's HelmRelease postRenderers with Kustomize patches, which keeps the real Helm release. Upstream the knob when you can.

Choosing ​

Helm, Kustomize, or both ​

SituationChooseReason
Software installed by other teams or customersHelm chart in an OCI registryValues API, versions, schema, signatures, Artifact Hub
Your own services, a few environments, one teamKustomize overlaysPlain YAML, small diffs, no template language
Your own services, many near-identical servicesHelm (one shared chart or a library chart)One chart, values per service
Need migrations or other ordered stepsHelm hooks (or GitOps sync hooks)Lifecycle ordering built in
Third-party chart plus local policyHelm + Kustomize (post-render)No fork
GitOps with Argo CDEither; know Helm is rendered, not releasedArgo CD owns the lifecycle
GitOps with Flux, want helm historyHelmReleaseReal Helm releases with remediation

Values layout ​

OptionWhenTrade-off
values.yaml defaults + one file per environmentMost chartsSimple; files may repeat shared settings
Defaults + values-common.yaml + per-env fileSeveral clusters per environmentOrder of -f matters (right-most wins)
Values in the GitOps repo (Argo CD valueFiles, Flux valuesFrom)Chart published separatelyChart and config versioned apart
--set in CIOnly for the image digestTyped by strvals; easy to drop other values

Distribution ​

NeedChooseWhy
Internal charts, images already in GHCR/ECR/HarborOCI registryOne auth model, digests, cosign
Public chartsOCI registry or classic repo + Artifact Hub listingDiscoverability
Air-gapped clustersHarbor (OCI) with replicationProxy and replicate charts with images
Charts only used by one GitOps repoPath in GitNo publish step (no versioning either)

GitOps tool support ​

CapabilityArgo CDFlux
Helm chartsRendered with helm template; hooks mapped to sync hookshelm-controller runs real install/upgrade, helm list shows them
KustomizeNative (kustomization.yaml detected), images override in the Applicationkustomize-controller (Kustomization CRD), prune, wait, health checks
OCI chartsrepoURL without oci:// plus chartOCIRepository or HelmRepository type oci
DriftSelf-heal (selfHeal: true)driftDetection for HelmRelease; Kustomization re-applies on interval
Post-renderingConfig management pluginsHelmRelease postRenderers (Kustomize patches, images)

In architecture: from a single process to a distributed system ​

A package is the unit that crosses the boundary between "built" and "running": CI produces an image and a chart (or an overlay change), a registry or Git stores it, a GitOps controller applies it per cluster. The architecture questions are how many charts, who owns the values, and how a release moves through environments.

Monolith: one app, one chart ​

The Laravel shop as one chart: web (php-fpm + Nginx), worker, scheduler, migration hook, one values file per environment. The chart is the deployment contract between the team and the cluster; helm upgrade --install --rollback-on-failure from CI is enough, and helm history is the deployment log. The traps at this size are the ones in this chapter: migrations racing the rollout, replicas fighting the HPA, secrets in values.

Modular monolith: one chart, several components ​

The same codebase grows a Go PDF renderer and an admin frontend. Options: one chart with pdf.enabled / admin.enabled toggles (one release, one rollback for everything), or subcharts per module under an umbrella chart (charts/pdf, charts/admin, condition: pdf.enabled), which keeps each module's templates separate but still releases them together. A library chart keeps labels and security contexts identical across modules.

Microservices: many charts, a golden path ​

Twenty services cannot each invent a chart. The usual platform setup is a library chart (or one generic "service" chart) maintained by the platform team, each service's repository holding only values.yaml, and a GitOps repository with per-cluster values. A typical flow for orders-api 1.4.3:

text
1  merge to main -> CI builds and signs the image (digest D) and, if the chart changed, ct lint/install
2  CI opens a PR in the GitOps repo: values-prod.yaml image.digest = D   (or Kustomize images: digest D)
3  review shows only the digest line; merge
4  Argo CD renders the chart (or Flux upgrades the HelmRelease) for each prod cluster
5  rollout watched by the controller; failure -> previous Git revision (Argo CD) or remediation (Flux)

Infrastructure around it (the clusters, the registry, IAM for CI) is usually Terraform (Infrastructure as Code); progressive delivery on top is Deployment Strategies.

Distributed data: charts, registries and clusters in many regions ​

With several clusters per region, the chart becomes shared code and the values become the per-cluster configuration database. Patterns: an OCI registry replicated to every region (Harbor replication, ECR cross-region replication) so helm pull and image pulls stay local; charts deployed by digest (Helm 4 oci://...@sha256:...) so every region runs identical bytes; signatures replicated with the artefacts so admission policies can verify them; values layered as values.yaml < region.yaml < cluster.yaml, rendered per cluster by Argo CD ApplicationSets or Flux Kustomizations with postBuild substitution; and "hydrated" manifests (the rendered output committed to Git per cluster) when reviewers must see exact YAML. Release state is per cluster: a Helm release Secret in one cluster says nothing about another, so the source of truth for "what runs where" is Git, not helm list.

Scaling path: 1x, 10x, 100x ​

ScalePackagingDistributionDeploys
1x (one team, one cluster)One chart or one base + overlays in the app repoGit path or GHCRhelm upgrade --install / kubectl apply -k from CI
10x (several teams, a few clusters)Library chart, schema, unit tests, ct in CIOCI registry, signed charts, semantic versionsArgo CD or Flux per cluster, values in a GitOps repo
100x (many clusters and regions)Golden-path chart versions with deprecation policy, Kustomize components for cluster featuresReplicated registries, deploy by digest, signature verificationApplicationSets / Flux per fleet, hydrated manifests, progressive delivery

Lab ​

Label: no Kubernetes cluster may be started in this build environment, and there is no helm, kustomize, kubeconform or ct binary on the host. Steps marked ran on the host were executed on macOS (Go 1.27.4 darwin/arm64, kubectl v1.36.1 with Kustomize v5.8.1) and show real output. For Helm, the chapter compiles Helm's own CLI from its Go module (helm.sh/helm/v4 v4.0.5, go/cmd/helm4, release ldflags mirrored): its lint and template output is the CLI code's real output, not a reimplementation, but it is a module build, not the released binary. Every step that needs a cluster or a plugin is expected, not run; its output is a shape with placeholders, never invented values.

1. Go tests: application config, manifest checks, charts through the Helm 4 CLI code (ran on the host) ​

bash
cd docs/snippets/platform/helm-kustomize-packaging/go
gofmt -l . ; go vet ./... ; go test -race -count=1 -v ./... | grep -E '^(--- |ok)'
# (literal output; timings vary per run)
# --- PASS: TestLoadProd (0.00s)
# --- PASS: TestLoadReportsEverythingAtOnce (0.00s)
# --- PASS: TestDefaults (0.00s)
# ok  	academy/helm-kustomize-packaging/appconfig	1.408s
# --- PASS: TestOrdersAPILintsInEveryEnvironment (0.95s)
# --- PASS: TestOrdersAPIProd (0.03s)
# --- PASS: TestOrdersAPIDevKeepsReplicas (0.02s)
# --- PASS: TestRequiredAndSchemaStopBadRenders (0.09s)
# --- PASS: TestLintDoesNotEnforceRequired (0.05s)
# --- PASS: TestLibraryChartIsNotInstallable (0.02s)
# --- PASS: TestShopLaravel (0.13s)
# --- PASS: TestValueTypingPitfalls (0.00s)
# ok  	academy/helm-kustomize-packaging/chartcheck	7.429s
# --- PASS: TestCheckFindsEveryMistake (0.00s)
# --- PASS: TestSelectorMismatch (0.00s)
# --- PASS: TestEmptyPDBSelector (0.00s)
# --- PASS: TestPortsAndRegistriesAreNotTags (0.00s)
# --- PASS: TestKustomizeOutputsAreClean (0.01s)
# ok  	academy/helm-kustomize-packaging/manifestcheck	1.341s

Two of these tests exist because the first run failed: TestOrdersAPIProd found no helm test Pod in the render (the .helmignore line tests/ also matched templates/tests/; fixed with /tests/), and every helm template call failed with chart requires kubeVersion: >=1.30.0-0 which is incompatible with Kubernetes v1.20.0 until the build used Helm's release ldflags.

2. Lint and render both charts (ran on the host, Helm v4.0.5 CLI code) ​

bash
cd docs/snippets/platform/helm-kustomize-packaging
HELM_BIN=/tmp/helm4 ./scripts/render-charts.sh     # keeps the built Helm 4 CLI at /tmp/helm4
# (the lint block below is printed three times, for dev, staging and prod; shown once)
# v4.0.5
# ==> Linting charts/orders-api
# [INFO] Chart.yaml: icon is recommended
#
# 1 chart(s) linted, 0 chart(s) failed
# Saving 1 charts
# Deleting outdated charts
#   ^ helm dependency build of shop-laravel (annotation, not output)
# ==> Linting $WORK/shop-laravel
# [INFO] Chart.yaml: icon is recommended
#
# 1 chart(s) linted, 0 chart(s) failed
# 8
#   ^ grep -c '^kind:' of the shop-laravel prod render (annotation, not output)

The Laravel prod render contains, in order: the Nginx ConfigMap, the Service, the web Deployment (two containers), the worker Deployment, the HPA, the scheduler CronJob, then the hooks: the helm test Pod and the migrate Job with "helm.sh/hook": pre-install,pre-upgrade, "helm.sh/hook-weight": "-5" and "helm.sh/hook-delete-policy": before-hook-creation,hook-succeeded.

3. What stops a bad render, and what does not (ran on the host, from the snippet root, with the binary step 2 kept) ​

bash
/tmp/helm4 template orders-api charts/orders-api
# Error: execution error at (orders-api/templates/deployment.yaml:25:28): config.databaseHost is required: set it in the environment's values file
#
# Use --debug flag to render out invalid YAML
/tmp/helm4 template orders-api charts/orders-api --set config.databaseHost=db --set config.appEnv=qa
# Error: values don't meet the specifications of the schema(s) in the following chart(s):
# orders-api:
# - at '/config/appEnv': value must be one of 'dev', 'staging', 'prod'
/tmp/helm4 template orders-api charts/orders-api --set config.databaseHost=db --set config.databasePassword=hunter2
# Error: values don't meet the specifications of the schema(s) in the following chart(s):
# orders-api:
# - at '/config': 'not' failed
/tmp/helm4 template lib charts/acme-lib
# Error: library charts are not installable
/tmp/helm4 lint --strict charts/orders-api    # no environment file: lint PASSES
# level=WARN msg="missing required values" message="config.databaseHost is required: set it in the environment's values file"
# level=WARN msg="missing required values" message="config.databaseHost is required: set it in the environment's values file"
# ==> Linting charts/orders-api
# [INFO] Chart.yaml: icon is recommended
#
# 1 chart(s) linted, 0 chart(s) failed

The required error is reported at deployment.yaml:25:28, the include of configmap.yaml for the checksum annotation, because that is where the ConfigMap template was first executed.

4. Value typing (ran on the host, asserted in TestValueTypingPitfalls with Helm's own packages) ​

text
--set image.tag=1.10,replicaCount=3,port=08080,debug=true,nodeSelector=null   (pkg/strvals)
  image.tag     string 1.10       (not an integer, so it stays a string)
  replicaCount  int64 3
  port          string 08080      (leading zero: never parsed as a number)
  debug         bool true
  nodeSelector  <nil>             (null: deletes the chart default when coalesced)
--set annotations.team=a,b        parse error (the comma starts a new assignment)
values file "image:\n  tag: 1.10\nbig: 1000000"   (pkg/chart/common.ReadValues)
  image.tag     float64 1.1
  big           prints as 1e+06

5. The overlays (ran on the host) ​

bash
./scripts/kustomize-build-all.sh
# Client Version: v1.36.1
# Kustomize Version: v5.8.1
# dev        4 objects  dev-orders-api-config-f95gt5dfmk dev-orders-api-db-gtfmg6gh7g dev-orders-api dev-orders-api
# staging    4 objects  orders-api-config-bfkd6m9m22 orders-api orders-api orders-api
# prod       5 objects  orders-api-config-gdb27m5gh9 orders-api orders-api orders-api orders-api
# helm-post 6 objects
kubectl kustomize kustomize/orders-api/overlays/dev | head -15
# ("<-" marks an annotation, "..." marks lines cut from the real output)
# apiVersion: v1
# data:
#   APP_ENV: dev
#   DATABASE_HOST: postgres.shop-dev.svc.cluster.local
#   LOG_LEVEL: debug
#   SELF_URL: http://dev-orders-api         <- replacements, after namePrefix
#   SHUTDOWN_TIMEOUT: 8s
# kind: ConfigMap
# metadata:
#   ...
#   name: dev-orders-api-config-f95gt5dfmk  <- prefix + content hash
#   namespace: shop-dev

Images per overlay in the real output: dev ghcr.io/acme/orders-api:1.5.0-rc.1 with replicas: 1; staging ghcr.io/acme/orders-api:1.4.2 and no replicas (HPA component); prod ghcr.io/acme/orders-api@sha256:0b7e... (placeholder digest) and no replicas. The first version of overlays/prod/pdb.yaml rendered selector: matchLabels: {}, which TestEmptyPDBSelector now catches; a patch aimed at the wrong name fails with no resource matches strategic merge patch "Deployment.v1.apps/orders.[noNs]".

6. Install, upgrade, hooks, rollback (expected, not run: needs a cluster) ​

bash
kind create cluster --name shop
kubectl create namespace shop-prod
kubectl -n shop-prod create secret generic shop-laravel-secrets \
  --from-literal=APP_KEY=base64:<generated> --from-literal=DB_PASSWORD=<generated>
helm dependency build charts/shop-laravel
helm upgrade --install shop charts/shop-laravel -n shop-prod -f charts/shop-laravel/values-prod.yaml \
  --rollback-on-failure --wait --timeout 10m
# Release "shop" does not exist. Installing it now.
# NAME: shop
# LAST DEPLOYED: <date>
# NAMESPACE: shop-prod
# STATUS: deployed
# REVISION: 1
# NOTES: shop-laravel 3.8.0 -> release shop, revision 1, namespace shop-prod. ...
kubectl -n shop-prod get secrets -l owner=helm
# NAME                         TYPE                 DATA   AGE
# sh.helm.release.v1.shop.v1   helm.sh/release.v1   1      <age>
helm upgrade shop charts/shop-laravel -n shop-prod -f charts/shop-laravel/values-prod.yaml \
  --set image.tag=3.9.0-broken --rollback-on-failure --wait --timeout 3m
# expected: the migrate Job runs first, then the web pods never become ready, then
# Error: UPGRADE FAILED: ... (timeout or readiness)  and an automatic rollback
helm history shop -n shop-prod
# REVISION  UPDATED  STATUS      CHART               APP VERSION  DESCRIPTION
# 1         <date>   superseded  shop-laravel-2.1.0  3.8.0        Install complete
# 2         <date>   failed      shop-laravel-2.1.0  3.8.0        Upgrade "shop" failed: <reason>
# 3         <date>   deployed    shop-laravel-2.1.0  3.8.0        Rollback to 1
helm test shop -n shop-prod --logs        # the /up Pod: exit 0 = Phase: Succeeded

7. Diff, schema validation, unit tests, chart-testing, publish (expected, not run: plugins, registry and a cluster) ​

bash
helm plugin install https://github.com/databus23/helm-diff
helm diff upgrade orders-api charts/orders-api -n shop-prod -f charts/orders-api/values-prod.yaml \
  --three-way-merge --detailed-exitcode ; echo "exit=$?"     # 2 when there are changes
helm template orders-api charts/orders-api -f charts/orders-api/values-prod.yaml \
  | kubeconform -strict -summary -kubernetes-version 1.35.0
# Summary: <n> resources found parsing stdin - Valid: <n>, Invalid: 0, Errors: 0, Skipped: 0
helm plugin install https://github.com/helm-unittest/helm-unittest.git
helm unittest charts/orders-api          # 5 tests in tests/deployment_test.yaml
ct lint --chart-dirs charts --target-branch main
ct install --chart-dirs charts --target-branch main
helm package charts/orders-api && helm push orders-api-1.3.0.tgz oci://ghcr.io/acme/charts
# Pushed: ghcr.io/acme/charts/orders-api:1.3.0
# Digest: sha256:<digest>
cosign sign --yes ghcr.io/acme/charts/orders-api@sha256:<digest>
helm install orders-api oci://ghcr.io/acme/charts/orders-api@sha256:<digest> -n shop-prod -f ...   # Helm 4

Common misconceptions ​

BeliefReality
helm upgrade --set x=y changes only xAny new values make Helm drop the last release's values; pass every -f again
helm lint passing means install will renderLint turns required into warnings; lint with each environment's values and run helm template
Helm upgrades CRDs in crds/Only installs them, once; never upgrades or deletes them
Hooks are cleaned up with the releaseHook resources are not part of the release; use hook-delete-policy
Argo CD releases show up in helm listArgo CD runs helm template and applies itself; Flux's HelmRelease creates real releases
--set image.tag=1.10 and tag: 1.10 in a file are the same--set keeps the string 1.10; a file gives the float 1.1; quote tags
A Helm template knows YAMLIt prints text; indentation is nindent's job, and errors appear only when the result is parsed
commonLabels is a harmless way to add a labelIt edits selectors, which are immutable; use labels (default: no selectors)
Labels set in the base with includeSelectors also fill selectors of resources an overlay addsA kustomization's labels apply only to the resources it loads; the overlay's PDB keeps its empty selector unless you write it (or the overlay itself sets selector labels)
secretGenerator makes secrets safe in GitIt base64-encodes them; use External Secrets, SOPS or Sealed Secrets
Kustomize is a template engineNo variables, loops or conditionals by design; bases stay valid YAML
--atomic is gone in Helm 4It is a deprecated alias of --rollback-on-failure
A rollback restores the databaseIt restores manifests; migrations that ran stay applied
helm template output can be applied as isIt has no metadata.namespace and includes test hooks unless --skip-tests
.helmignore works like .gitignorefilepath.Match globs, no **; an unanchored tests/ also matches templates/tests/

Cheat sheet ​

TopicRemember
Chart identityapiVersion: v2; version = chart SemVer (bump on every change); appVersion = app; type: application or library
Directorytemplates/ rendered; _*.tpl helpers only; NOTES.txt printed; crds/ plain YAML, install only; charts/ dependencies
Templatinginclude + nindent, toYaml, default, quote, required, tpl; $ inside with/range; trim left with a dash
LabelsselectorLabels (name, instance) never change; full labels may; never a version in a selector
Valuesdefaults < parent < -f (right-most wins) < --set (last wins); maps merge, lists replace, null deletes
Typing--set ints are int64, files give float64; --set-string for tags; quote tags in files
Schemavalues.schema.json runs on install, upgrade, template, lint; enums, patterns, not for forbidden keys
SecretsexistingSecret + External Secrets; never in values, --set or release Secrets
ReleasesSecrets sh.helm.release.v1.<name>.v<rev>, type helm.sh/release.v1; --history-max 10
Patch strategyHelm 3: three-way strategic merge; Helm 4: SSA for new releases, previous method for existing ones
Deployhelm upgrade --install -f ... --rollback-on-failure --wait --timeout (Helm 3: --atomic); helm test; helm history
Hookspre-install,pre-upgrade migrate Job, weight as a string, before-hook-creation,hook-succeeded; Argo CD runs them every sync
Testinghelm lint --strict -f env, helm template | kubeconform -strict, helm unittest, ct lint/ct install, helm diff
DistributionOCI: helm push x.tgz oci://reg/path, helm pull oci://reg/path/x --version; sign by digest; Artifact Hub annotations
Kustomizeresources (bases), patches (SMP or JSON 6902), images (newTag/digest), generators with hash suffix, labels, components, replacements
Run Kustomizekubectl kustomize dir / kustomize build dir render; kubectl apply -k dir applies
ChooseHelm to distribute and for releases/hooks; Kustomize for your own YAML; both via post-render when a chart lacks a knob

Self-check: questions & answers ​

Show:
  • Must-know asked in almost every interview
  • Important frequent; expected at senior level
  • Good to know extra depth that sets you apart

1 — A pipeline runs helm upgrade orders-api ./orders-api --set image.tag=$SHA and production suddenly has 2 replicas and the dev database host. What happened, and how do you fix the pipeline? Must-know ​

Answer

Answer: When an upgrade receives any new values, Helm builds the release from the chart's defaults plus only those values; it copies the previous release's values only when no new values are given. The -f values-prod.yaml from the previous deploy was therefore dropped, and the defaults (replicaCount: 2, dev settings) came back. Pass the full set every time (-f values.yaml -f values-prod.yaml --set-string image.tag=$SHA), or write the tag into the values file in Git (GitOps); --reuse-values exists but carries old mistakes forward. See Values design.

2 — Why does a chart need separate selectorLabels and labels helpers, and what breaks if the version label goes into the selector? Must-know ​

Answer

Answer: A Deployment's spec.selector is immutable after creation, and the version label changes on every release. If it is in the selector, the next upgrade's patch is rejected with field is immutable, and the only ways out are reverting the template or deleting and recreating the Deployment. selectorLabels contains only stable keys (name, instance, component) and is used in selectors and Service selectors; labels adds the chart, version and managed-by labels for metadata. See Pitfalls.

3 — Explain the three-way strategic merge with the "kubectl scale to zero, then helm rollback" example, and what Helm 4 changes. Must-know ​

Answer

Answer: Helm 2 diffed only the old and new manifests; after kubectl scale --replicas=0, a rollback to the same manifest found no difference and left zero replicas. Helm 3 computes the patch from the old manifest, the live state and the new manifest, sees that live (0) differs from the desired (3), and patches it back, while leaving fields the chart never set (an injected sidecar) alone. Helm 4 uses server-side apply for new releases and keeps the previous apply method for existing ones, so Helm 3 releases continue with client-side three-way merges until --server-side is set. See Releases.

4 — Where does Helm keep release state, what is in it, and why does that matter for security? Must-know ​

Answer

Answer: By default in Secrets in the release namespace, one per revision, named sh.helm.release.v1.<release>.v<revision>, type helm.sh/release.v1, labelled owner=helm, name, status, version; the data is the base64-encoded, gzipped release: chart, values and rendered manifest. Anyone who can read Secrets in that namespace can read every value ever passed, so secrets must never be values, and get on Secrets must be restricted. See Releases.

5 — Design the Laravel migration step for a Helm chart. Which annotations, what may the Job reference, and what must the migration itself guarantee? Must-know ​

Answer

Answer: A Job annotated helm.sh/hook: pre-install,pre-upgrade, a weight such as "-5", and helm.sh/hook-delete-policy: before-hook-creation,hook-succeeded, running php artisan migrate --force --isolated in the new image with backoffLimit: 0 and activeDeadlineSeconds below Helm's --timeout. A Job can start its program twice, so the guarantee is "before the new code, one migrator at a time" (the --isolated cache lock), not exactly-once; migrations must be safe to re-run. It may reference only things that exist before the release: the image, env rendered inline from a named template, and a Secret created outside the chart (on first install no chart object exists yet). The migration must be backwards compatible with the old code, which serves until the rollout finishes and comes back on rollback. See Hooks.

6 — helm lint --strict passes in CI, but helm install fails with "config.databaseHost is required". How is that possible, and what should CI run instead? Important ​

Answer

Answer: The engine runs in lint mode during helm lint, where required (and fail) only log warnings; this chapter's run showed level=WARN msg="missing required values" followed by 0 chart(s) failed. CI should lint with each environment's values file (-f values-prod.yaml), run helm template for each environment (which enforces required and the schema), pipe the output to kubeconform -strict, and run unit tests. See Testing charts.

7 — When would you choose Kustomize over Helm, and when both? Important ​

Answer

Answer: Kustomize for your own services across a few environments when the team prefers plain, always-valid YAML and small patch diffs, and when Git (with Argo CD or Flux) is the release history. Helm when you distribute software to others (a values API with a schema, versions, signatures), need lifecycle hooks such as migrations, or want helm history/rollback. Both when a third-party chart lacks a knob: render it (helm template piped to kustomize) or post-render it (Flux postRenderers) instead of forking. See Helm vs Kustomize.

8 — What does configMapGenerator do that a hand-written ConfigMap does not, and what is the Helm equivalent? Important ​

Answer

Answer: It appends a content hash to the generated name (orders-api-config-gdb27m5gh9) and rewrites every reference, so any content change produces a new name, a changed pod template and therefore a rollout, while the old ConfigMap stays for pods still running and for rollback (until pruned). A hand-written ConfigMap keeps its name, and pods reading env vars never see the change. In Helm the usual equivalent is a checksum/config annotation computed with sha256sum over the rendered ConfigMap. See Generators.

9 — Your Deployment has an HPA, and after every helm upgrade the pod count drops to 2 for a minute. Why, and what are the chart and Kustomize fixes? Important ​

Answer

Answer: The chart renders spec.replicas: 2; each upgrade (with client-side apply) sets it back, and the HPA needs a few cycles to scale up again. Omit replicas when autoscaling is enabled (if not .Values.autoscaling.enabled around the field); in Kustomize, a component that adds the HPA also removes /spec/replicas with a JSON 6902 patch. Server-side apply avoids the conflict only if the field is not in the applied manifest at all, so the fix is the same. See Solving the classic problems.

10 — How do you publish a chart to an OCI registry, install it, and make the installation verifiable? Important ​

Answer

Answer: helm registry login ghcr.io (Helm 4: domain only), helm package charts/orders-api, then helm push orders-api-1.3.0.tgz oci://ghcr.io/acme/charts; the reference must not contain the chart name or tag, which come from Chart.yaml, and the push prints the digest. Sign that digest with cosign (keyless in CI) or use the helm-sigstore plugin; classic repositories use .prov files from helm package --sign and helm install --verify. Install with oci://ghcr.io/acme/charts/orders-api --version 1.3.0, or in Helm 4 by digest, which refuses non-matching content. See Distributing charts.

11 — Why are commonLabels, bases, patchesStrategicMerge and patchesJson6902 still accepted by Kustomize, and what should a new kustomization use? Good to know ​

Answer

Answer: They are deprecated (bases in v2.1.0, the others in v5.0.0) but "will never be removed from the kustomize.config.k8s.io/v1beta1 Kustomization API"; they will not be in a future v1 API. Use resources for directories, patches for both patch types (with optional target), and labels (with includeSelectors only where intended) instead of commonLabels. kustomize edit fix converts old files. See Kustomize.

12 — A chart ships a CRD in crds/. Version 2 of the chart adds a field to the CRD, and after helm upgrade the field is rejected. Explain and give two fixes. Good to know ​

Answer

Answer: Helm installs crds/ only on install and never upgrades or deletes those CRDs, so the cluster still has version 1 of the schema. Fix: apply the new CRDs as a separate pipeline step before the upgrade (kubectl apply --server-side -f crds/), or move CRDs into their own chart's templates/ (so Helm upgrades them) with helm.sh/resource-policy: keep so an uninstall can never delete them and all custom resources with them. See Pitfalls.

13 — Argo CD syncs your Helm chart, and the migration hook runs on every sync, even when nothing changed. Why, and is it a problem? Must-know ​

Answer

Answer: Argo CD renders charts with helm template and maps Helm hooks to its own sync hooks; it cannot tell an install from an upgrade (every operation is a sync, in its docs' words), so pre-install and pre-upgrade hooks run on each sync. Laravel migrations are idempotent (already-run migrations are skipped), so it is usually harmless; add --isolated if anything else can migrate concurrently, and keep the delete policy so old Jobs do not accumulate. With Flux's HelmRelease, real Helm upgrades run the hooks only on install and upgrade. See Hooks.

Glossary ​

TermMeaning
HelmThe Kubernetes package manager: charts, values, releases; CLI only since Helm 3 (no Tiller); Helm 4 since Nov 2025
ChartA directory or .tgz of templates, default values and metadata describing one application
Chart.yamlThe chart's metadata: apiVersion, name, version, appVersion, type, kubeVersion, dependencies, annotations
apiVersion v2Chart API for Helm 3+ charts: dependencies in Chart.yaml and the type field (v1 = Helm 2 charts)
version vs appVersionThe chart's own SemVer vs the version of the application it deploys
values.yamlThe chart's documented default values
templatesThe templates/ directory of Go-template files that render Kubernetes manifests
_helpers.tplConventional file of named templates (define blocks); underscore files render nothing
NOTES.txtTemplate rendered and printed after install/upgrade
crds directorycrds/: plain-YAML CRDs installed once before templates; never upgraded or deleted by Helm
dependenciesCharts listed in Chart.yaml and vendored into charts/ by helm dependency update/build
subchartsDependent charts rendered with their own values scope (.Values.<subchart> in the parent)
global values.Values.global, shared between a parent and all its subcharts
library charttype: library: only named templates, cannot be installed
Chart.lockResolved dependency versions and a digest, written by helm dependency update
.helmignorePatterns of paths Helm skips when loading a chart; filepath.Match globs, no **
Go templatesGo's text/template language: actions, pipelines, functions, define/template/block
sprig functionsThe Sprig template-function library Helm includes (minus env/expandenv)
includeHelm function: execute a named template and return a string that can be piped
tplHelm function: render a string as a template with a given context
requiredHelm function: fail the render with a message if a value is nil or empty (lint only warns)
defaultSprig function: a fallback when the value is empty (nil, "", 0, false, empty collection)
toYamlHelm function: marshal a value to YAML (without the trailing newline)
nindent / indentSprig: prefix a newline plus N spaces / N spaces to every line
if else withTemplate conditionals; with also sets dot to the value
rangeTemplate loop over lists and maps (maps in sorted key order)
named templatesReusable define blocks, global across a chart and its subcharts
defineDeclares a named template
whitespace controlA dash just inside the opening or closing braces trims whitespace before or after the action
values precedenceChart defaults < parent values < -f files (right-most wins) < --set (last wins)
--set / --valuesCommand-line value assignment (strvals typing) / values file (-f)
values.schema.jsonJSON Schema the merged values must satisfy on install, upgrade, template and lint
strvalsHelm's --set parser: int64, bool, nil, string rules
releaseA named, namespaced installation of a chart, with numbered revisions
release secretSecret sh.helm.release.v1.<name>.v<revision> (type helm.sh/release.v1) holding one revision
revision historyThe list of revisions of a release (helm history), pruned by --history-max
TillerHelm 2's in-cluster server component, removed in Helm 3
three-way strategic mergeHelm 3's patch from old manifest, live state and new manifest
server-side applyAPI-server-side merge with field ownership; Helm 4's default for new releases
helm installCreate a release (revision 1)
helm upgrade --installUpgrade a release, or install it when it does not exist
--atomic / --rollback-on-failureUndo a failed install/upgrade; --atomic is the Helm 3 name and a deprecated alias in Helm 4
--waitWait for readiness (Helm 4 strategies watcher, hookOnly, legacy)
--timeoutMaximum time per Kubernetes operation, hooks included (default 5m0s)
helm rollbackReturn to a previous revision, recorded as a new revision
helm historyList a release's revisions with status and description
helm uninstallDelete the release's objects and its history (unless --keep-history)
hooksResources annotated helm.sh/hook, run at lifecycle points and not part of the release
pre-install post-upgradeTwo of the hook points (also post-install, pre-upgrade, pre/post-delete, pre/post-rollback, test)
hook weightshelm.sh/hook-weight: string integers, ascending order
hook-delete-policybefore-hook-creation (default), hook-succeeded, hook-failed
helm testRuns the chart's test hooks against a release; exit 0 = pass
helm lintStatic checks plus a lint-mode render of a chart
helm templateClient-side render of a chart to stdout
kubeconformFast Go validator of manifests against Kubernetes OpenAPI schemas
helm unittestPlugin running YAML test suites against rendered templates without a cluster
chart-testing ctct lint / ct install: CI tool that lints and installs changed charts
helm diff pluginhelm diff upgrade: shows what an upgrade would change, optionally three-way
helm repoCommands for classic chart repositories (add, update, index)
index.yamlThe catalogue file of a classic chart repository
OCI registryA container registry storing charts as OCI artefacts (oci://...); GA since Helm 3.8.0
helm push / helm pullUpload a packaged chart to / download it from an OCI registry or repository
provenance.prov file signed with PGP at helm package --sign, checked by --verify
chart signingProving a chart's publisher: .prov (PGP) or cosign / helm-sigstore for OCI charts
Artifact HubCNCF web catalogue of Helm charts and other cloud-native packages
post-rendererA step that modifies Helm's rendered manifests before apply (a plugin in Helm 4)
KustomizeTemplate-free tool that builds Kubernetes YAML from bases, overlays, patches and generators; in kubectl since 1.14
kustomization.yamlThe file that lists resources and transformations for one Kustomize directory
resourcesKustomize field listing files and directories (bases) to load
basesKustomization directories reused by others; the bases: field is deprecated (use resources)
overlaysKustomization directories that reference a base and change it per environment
environment overlays dev staging prodThe usual overlay set: one directory per environment over one base
patchesKustomize field holding strategic merge or JSON 6902 patches with optional targets
strategic merge patchA partial object merged by Kubernetes merge keys (containers by name)
JSON 6902 patchRFC 6902 operation list (add, replace, remove, move, copy, test) on JSON paths
images / newTagKustomize image override: newName, newTag or digest for a matched image name
configMapGenerator / secretGeneratorKustomize generators building ConfigMaps/Secrets from literals, env files or files
hash suffixContent hash appended to generated names so changes produce new names and rollouts
namePrefix / nameSuffixRename every resource (and known references)
commonLabelsDeprecated (v5.0.0) Kustomize field that adds labels including selectors; use labels
componentskind: Component kustomizations: reusable opt-in features applied by overlays
replacementsCopy a field value from one object into fields of others (successor of vars)
kubectl apply -kBuild a kustomization with kubectl's embedded Kustomize and apply it
kustomize buildStandalone Kustomize render (same as kubectl kustomize)
Helm vs KustomizeParameterised packages with releases vs patched plain YAML without release state
helm template piped to kustomizeRender a chart, then patch the output with a Kustomize overlay (loses hooks and releases)
Argo CD helm and kustomize supportArgo CD renders Helm via helm template (hooks mapped) and builds Kustomize natively
Flux HelmRelease KustomizationFlux CRDs: real Helm releases (helm.toolkit.fluxcd.io/v2) and kustomize builds (kustomize.toolkit.fluxcd.io/v1)
CRD upgrade pitfallsHelm never upgrades crds/; CRD changes need a separate step or a CRD chart
immutable fieldsFields the API server refuses to change (Deployment selector, Job template, Service clusterIP)
selector immutabilityWorkload selectors cannot change after creation; keep versions out of them
Laravel migrate hook JobA pre-install,pre-upgrade Job running php artisan migrate --force --isolated before new code starts (lock-serialised, not exactly-once)
php-fpm nginx chartChart running Nginx and php-fpm as two containers of one web pod (FastCGI on localhost)
Go service chartChart for a stateless Go HTTP service: Deployment, Service, ConfigMap, ServiceAccount, HPA, PDB
HPA in chartAn optional HorizontalPodAutoscaler template; the Deployment omits replicas when it is enabled
existingSecretChart value naming a Secret created outside the chart (External Secrets, SOPS)

References ​

Built by Morteza Negahi