Skip to content

Lesson 22 of 24Kubernetes

Helm, Kustomize and GitOps Deploys

Package one app for dev, staging and prod with Helm or Kustomize, then let Argo CD or Flux pull every change from git and roll it out.

17 min read0/5 questions

Your API now has a Deployment, a Service, an HTTPRoute, a ConfigMap and probes. It has to run in three places: dev with one replica and debug logging, staging that mirrors prod, and prod with six replicas, bigger requests and a different hostname. Copying the YAML three times works for a week, until someone fixes a probe in prod and forgets dev. This lesson covers the two tools teams use to keep one source of truth with small per-environment differences (Helm and Kustomize), and the deploy model most Kubernetes shops now run on top of them: GitOps, where the cluster pulls its desired state from git instead of CI pushing into it.

The problem: one app, many environments

Compare the prod and dev versions of your manifests and the differences are small and predictable: replica count, image tag, resource requests, hostnames, a few env vars, maybe an extra sidecar in prod. Everything else (labels, selectors, ports, probe paths, security context) must stay identical, because drift there is exactly where "works in staging, breaks in prod" comes from.

There are two families of answer:

  • Templating. Write the manifests once with holes in them, and fill the holes from a values file per environment. This is Helm.
  • Patching. Write plain, valid manifests once (the base), and per environment apply small patches on top (the overlays). This is Kustomize.

Both end the same way: plain Kubernetes YAML that goes to the API server. Keep that in mind when something breaks. The fastest debugging step for either tool is to render the final YAML and read it.

Helm: charts, values and releases

A chart is a folder of templated manifests plus defaults. A release is one installed copy of a chart in a namespace, with a name and a revision number that goes up on every upgrade.

A chart for your own API
  • charts/api/
  • Chart.yamlname, chart version, appVersion
  • values.yamldefaults for every value
  • values-dev.yamlsmall per-environment overrides
  • values-prod.yaml
  • templates/
  • _helpers.tplnamed snippets: names, labels
  • deployment.yaml
  • service.yaml
  • httproute.yaml
  • configmap.yaml
  • NOTES.txtprinted after install
charts/api/Chart.yaml
apiVersion: v2
name: api
description: The shop API
type: application
version: 1.4.0        # the chart's own version: bump when templates change
appVersion: "2.8.1"   # the app version it ships by default (informational)

apiVersion: v2 is the chart format that both Helm 3 and Helm 4 read. Do not confuse the chart version with your image tag: the chart version describes the packaging, and the image tag usually comes from values.

Templates use Go's text/template language plus the Sprig function library. .Values is the merged values, .Release.Name and .Release.Namespace describe the release, and .Chart is Chart.yaml.

charts/api/templates/deployment.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: {{ include "api.fullname" . }}
  labels:
    {{- include "api.labels" . | nindent 4 }}
spec:
  replicas: {{ .Values.replicaCount }}
  selector:
    matchLabels:
      {{- include "api.selectorLabels" . | nindent 6 }}
  template:
    metadata:
      labels:
        {{- include "api.selectorLabels" . | nindent 8 }}
    spec:
      containers:
        - name: api
          image: "{{ .Values.image.repository }}:{{ required "image.tag is required" .Values.image.tag }}"
          ports:
            - containerPort: {{ .Values.port | default 8000 }}
          resources:
            {{- toYaml .Values.resources | nindent 12 }}
          {{- with .Values.env }}
          env:
            {{- toYaml . | nindent 12 }}
          {{- end }}
charts/api/templates/_helpers.tpl
{{- define "api.fullname" -}}
{{- printf "%s-%s" .Release.Name .Chart.Name | trunc 63 | trimSuffix "-" -}}
{{- end }}
 
{{- define "api.selectorLabels" -}}
app.kubernetes.io/name: {{ .Chart.Name }}
app.kubernetes.io/instance: {{ .Release.Name }}
{{- end }}
 
{{- define "api.labels" -}}
{{ include "api.selectorLabels" . }}
app.kubernetes.io/version: {{ .Chart.AppVersion | quote }}
helm.sh/chart: {{ printf "%s-%s" .Chart.Name .Chart.Version }}
{{- end }}

Three details trip up everyone. First, YAML is whitespace-sensitive and templates are not: nindent N adds a newline and indents by N spaces, and {{- trims whitespace before the tag. Most broken charts are indentation bugs. Second, trunc 63 exists because Kubernetes names and label values are capped at 63 characters. Third, selector labels must never change after the first install, because a Deployment's selector is immutable. Keep version labels out of selectorLabels, as above.

How values are merged

Helm builds the final values in layers, later layers winning: the chart's values.yaml, then each -f file in the order given, then --set flags. Maps merge key by key. Lists are replaced whole. Setting a key to null removes a default.

Pythonvalues_merge.py
import copy def merge(base: dict, override: dict) -> dict: out = copy.deepcopy(base) for key, value in override.items(): if value is None: out.pop(key, None) # null deletes a default elif isinstance(value, dict) and isinstance(out.get(key), dict): out[key] = merge(out[key], value) # maps merge key by key else: out[key] = copy.deepcopy(value) # scalars and LISTS replace return out chart_defaults = { "replicaCount": 1, "image": {"repository": "ghcr.io/acme/api", "tag": "sha-7f3c2a1"}, "resources": {"requests": {"cpu": "100m", "memory": "128Mi"}}, "env": [{"name": "LOG_LEVEL", "value": "info"}, {"name": "REGION", "value": "eu-west-1"}], "debugToolbar": True,}values_prod = { # -f values-prod.yaml "replicaCount": 4, "resources": {"requests": {"cpu": "500m"}}, "env": [{"name": "LOG_LEVEL", "value": "warning"}], "debugToolbar": None,}set_flags = {"image": {"tag": "sha-9b1e004"}} # --set image.tag=... final = merge(merge(chart_defaults, values_prod), set_flags)for key, value in final.items(): print(f"{key}: {value}")
Output
Press Run (⌘ Enter) to see what happens.

Look at env: prod wanted to change one variable and silently lost REGION. This is a classic production incident. If a list is meant to be extended per environment, design the values as a map (env: {LOG_LEVEL: warning}) and turn it into a list inside the template.

Predict the outputPython

What does this print?

def merge(base, override):
  out = dict(base)
  for k, v in override.items():
      if isinstance(v, dict) and isinstance(out.get(k), dict):
          out[k] = merge(out[k], v)
      else:
          out[k] = v
  return out

defaults = {"ports": [80, 443], "probe": {"path": "/health", "delay": 5}}
prod = {"ports": [8443], "probe": {"delay": 20}}
m = merge(defaults, prod)
print(m["ports"], m["probe"])
Need a nudge? Hints walk you through it.

Install, upgrade, review, roll back

helm lint charts/api -f charts/api/values-prod.yamlhelm template api charts/api -n shop -f charts/api/values-prod.yamlhelm upgrade --install api charts/api -n shop --create-namespace -f charts/api/values-prod.yaml --set image.tag=sha-9b1e004 --wait --timeout 5m --rollback-on-failurehelm history api -n shophelm rollback api 6 -n shophelm get values api -n shophelm get manifest api -n shop

helm template renders locally without touching the cluster: pipe it into a file and read it, or run it in CI to catch broken templates before merge. upgrade --install is idempotent: it installs on the first run and upgrades after that, which is what pipelines want. Helm records every revision in a Secret in the release's namespace (named like sh.helm.release.v1.api.v7), which is how history and rollback work. A rollback creates a new revision with the old content; it does not rewind the counter.

To see what an upgrade will change against what is running, the community helm-diff plugin adds helm diff upgrade, taking the same arguments as helm upgrade. Helm 4 verifies plugin provenance by default, so follow the plugin's README for the Helm 4 install steps.

Charts from registries

Charts are distributed in two ways: classic HTTP repositories (helm repo add) and OCI registries, the same registries that hold your images. Many projects now publish OCI charts first. You can push your own chart next to your images:

helm package charts/apihelm push api-1.4.0.tgz oci://ghcr.io/acme/chartshelm install api oci://ghcr.io/acme/charts/api --version 1.4.0 -n shop

Third-party software versus your own chart

Most Helm use at work is installing other people's software: cert-manager for TLS certificates, a Gateway API controller, the Prometheus stack, External Secrets. Here Helm is clearly the right tool: the vendor maintains the templates and you only own a values file.

helm install cert-manager oci://quay.io/jetstack/charts/cert-manager --version v1.21.2 -n cert-manager --create-namespace --set crds.enabled=truehelm show values oci://quay.io/jetstack/charts/cert-manager --version v1.21.2

helm show values prints every setting the chart accepts. Read it before you install anything, and pin --version: an unpinned install picks whatever is newest that day. Note how CRDs are handled: Helm installs CRDs from a chart's crds/ folder but never upgrades or deletes them, so charts like cert-manager offer a value to manage them as normal templates instead.

For your own services, a chart is worth it when you have several similar services, need to publish the app for others to install, or want release history and helm rollback. It stops being worth it when the templates become a programming language: nested if blocks for every field, values files longer than the manifests, and nobody can predict the output without rendering it. That is the moment to look at Kustomize.

Kustomize: base plus overlays

Kustomize takes plain YAML and patches it. No templating language, and every file in the base is a valid manifest you could kubectl apply on its own. It is built into kubectl.

Kustomize layout
  • deploy/
  • base/
  • kustomization.yamllists the resources
  • deployment.yamlplain, valid YAML
  • service.yaml
  • overlays/
  • dev/
  • kustomization.yamlresources: ../../base, plus changes
  • prod/
  • kustomization.yaml
  • replicas-and-resources.yamla patch
deploy/overlays/prod/kustomization.yaml
apiVersion: kustomize.config.k8s.io/v1beta1
kind: Kustomization
namespace: shop
resources:
  - ../../base
labels:
  - pairs:
      env: prod
images:
  - name: ghcr.io/acme/api
    newTag: sha-9b1e004
patches:
  - path: replicas-and-resources.yaml
  - target:
      kind: Deployment
      name: api
    patch: |-
      - op: add
        path: /spec/template/spec/containers/0/env/-
        value: { name: LOG_LEVEL, value: warning }
deploy/overlays/prod/replicas-and-resources.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: api
spec:
  replicas: 6
  template:
    spec:
      containers:
        - name: api
          resources:
            requests: { cpu: 500m, memory: 512Mi }

The first patch is a strategic merge patch: a partial object matched by kind and name, and it knows that containers is a list keyed by name, so it merges into the api container instead of replacing the list. The second is a JSON 6902 patch for precise operations. The images: field rewrites the tag of any container using that image, which is exactly the line CI changes on every release.

kubectl kustomize deploy/overlays/prodkubectl diff -k deploy/overlays/prodkubectl apply -k deploy/overlays/prod
HelmKustomize
ModelTemplates plus valuesPlain YAML plus patches
Release history and rollbackYes (helm history, helm rollback)No, git is the history
Lifecycle hooksYes (pre-install, post-upgrade, ...)No
Packaging for othersYes, versioned charts in registriesWeak
Readability at scaleFalls as conditionals growStays plain YAML
Built into kubectlNoYes (-k)

A common real setup uses both: Helm for third-party charts, Kustomize overlays for the team's own services, and a GitOps tool that understands both.

GitOps: the cluster pulls from git

In the push model, CI runs helm upgrade or kubectl apply against the cluster. That means CI holds cluster-admin credentials, nobody can tell whether the cluster still matches what was deployed, and a hand edit at 2 a.m. lives on until someone notices.

GitOps flips it. A controller running inside the cluster (Argo CD or Flux, both CNCF graduated projects) watches a git repository, renders the manifests (plain YAML, Kustomize or Helm), compares them with the live cluster, and applies the difference. It is the reconcile loop from From Containers to Kubernetes, one level up: desired state now lives in git.

The usual shape is two repositories. The app repo holds code; its CI runs tests, builds the image, pushes ghcr.io/acme/api:sha-9b1e004, then opens a commit or pull request against the config repo that changes one line: the image tag for an environment. CI never talks to the cluster.

From merge to running pods
DeveloperApp repo CIConfig repoArgo CDClustermerge PR to mainbump tag in overlays/stagingpoll or webhookdesired manifestsdiff, then applyProgressing, then Healthy

Tests pass, CI builds and pushes the image tagged with the commit SHA.

1/6

An Argo CD Application ties a git path to a destination:

argocd/api-prod.yaml
apiVersion: argoproj.io/v1alpha1
kind: Application
metadata:
  name: api-prod
  namespace: argocd
  finalizers:
    - resources-finalizer.argocd.argoproj.io
spec:
  project: default
  source:
    repoURL: https://github.com/acme/shop-config.git
    targetRevision: main
    path: apps/api/overlays/prod
  destination:
    server: https://kubernetes.default.svc
    namespace: shop
  syncPolicy:
    automated:
      prune: true
      selfHeal: true
    syncOptions:
      - CreateNamespace=true

prune deletes objects you removed from git; without it they are orphaned in the cluster. selfHeal re-applies git when someone changes the live object by hand. For a Helm source, Argo CD runs helm template and applies the output itself, so the release does not appear in helm list and helm rollback is not how you roll back. Flux expresses the same idea with a GitRepository source and a Kustomization (or HelmRelease) object that reconciles on an interval; Flux uses the Helm SDK for HelmRelease, so those do keep Helm history.

Pythongitops_loop.py
git = {"replicas": 3, "image": "api:sha-7f3c2a1"}live = dict(git)history = [dict(git)] def commit(change: dict, message: str) -> None: git.update(change) history.append(dict(git)) print(f"git commit: {message}") def sync(self_heal: bool = True) -> None: drift = {k: (live.get(k), v) for k, v in git.items() if live.get(k) != v} if not drift: print(" Synced, nothing to do") return print(f" OutOfSync: {drift}") if self_heal: live.update(git) print(f" applied -> live is now {live}") print("someone runs kubectl scale --replicas=10 by hand")live["replicas"] = 10sync() commit({"image": "api:sha-9b1e004"}, "bump api to sha-9b1e004")sync() print("v2 is broken: git revert the bump")git.clear()git.update(history[-2])history.append(dict(git))sync()print("commits in history:", len(history))
Output
Press Run (⌘ Enter) to see what happens.

Notice two things. The hand scale to 10 was undone in seconds: with self-heal on, the live cluster is not the place to make changes. If you need 10 replicas, change git (or use an autoscaler, whose replica field you tell Argo CD to ignore). And the rollback was a new commit (git revert), not a special command. History only moves forward, every change has an author and a review, and "what was running at 14:05?" is answered by git log. Argo CD's own rollback button is disabled while auto-sync is on for exactly this reason: git would put the new version straight back.

Quick check
Prod is under load. An on-call engineer runs kubectl set image deploy/api api=ghcr.io/acme/api:sha-hotfix directly. The Argo CD Application has selfHeal: true. What happens?
Need a nudge? A hint rules out a wrong answer.

Ordering, hooks and secrets

Sometimes order matters: run database migrations before the new pods start. Argo CD applies resources in sync waves, lowest first, set with the annotation argocd.argoproj.io/sync-wave: "-1" (unannotated objects are wave 0), and supports hooks such as argocd.argoproj.io/hook: PreSync for a migration Job. Helm's own pre-upgrade and post-install hooks are mapped onto these phases. The backwards-compatible migration rules from your database lessons still apply: old pods keep running during the rollout, so the schema must work for both versions.

Secrets are the awkward part, because a plain Secret must never be committed. The common answers: External Secrets Operator, which syncs from AWS Secrets Manager, Vault or similar into Kubernetes Secrets (git only holds a reference); Sealed Secrets, where git holds an encrypted blob only the cluster can decrypt; and SOPS, which Flux decrypts natively. Config, Secrets, Probes and Autoscaling covers how pods consume them.

Progressive delivery: canaries with automatic analysis

A rolling update checks only readiness: a v2 that starts fine but returns 5 percent errors still rolls out to every pod. Argo Rollouts (or Flagger, its counterpart in the Flux world) replaces the Deployment with a Rollout object whose strategy shifts traffic in steps and queries your metrics between them.

rollout.yaml
apiVersion: argoproj.io/v1alpha1
kind: Rollout
metadata:
  name: api
spec:
  strategy:
    canary:
      analysis:
        templates:
          - templateName: success-rate
        startingStep: 2
      steps:
        - setWeight: 10
        - pause: { duration: 5m }
        - setWeight: 50
        - pause: { duration: 10m }
  # selector and template as in a Deployment

The AnalysisTemplate named success-rate runs a Prometheus query on an interval with a successCondition such as result[0] >= 0.99 and a failureLimit. If the analysis fails, the rollout aborts and traffic returns to the stable version with no human involved. You do not need this on day one, but knowing that "readiness is not correctness" and that canary analysis closes the gap is a strong signal in senior interviews.

Day one on a GitOps team

Your first deploy ticket will probably look like this: "raise the API memory limit in staging". The workflow:

  1. Find the right file in the config repo: apps/api/overlays/staging/ or values-staging.yaml. Do not edit the base when you only mean one environment.
  2. Render locally (kubectl kustomize ... or helm template ...) and read the diff of the output, not just the input.
  3. Open a PR. CI in the config repo usually runs the render plus a schema check (kubeconform or similar) and a policy check.
  4. After merge, open the Application in the Argo CD UI (or argocd app get api-staging). Watch it go OutOfSync, then Synced, then Progressing, then Healthy.
  5. If it ends Degraded, click into the resource tree. A Deployment that misses its progress deadline shows as degraded; the events and pod logs underneath tell you why: an image that cannot be pulled, a crash loop, a failing readiness probe, a quota exceeded.
Put it in order6 steps

Order the steps of a GitOps release of a new API version to staging.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.
Match the pairs0/5 matched

Match each job to the tool that fits it best.

Choose an item, then its match on the other side.
Quick check
The team deploys with Argo CD and auto-sync. v2 of the API is degraded in prod. What is the standard rollback?
Need a nudge? A hint rules out a wrong answer.

With GitOps in place, the path is complete: a Dockerfile on your laptop becomes a signed image in a registry, and a merged pull request becomes a running pod. The project that follows has you build the first half of that path yourself, from a Dockerfile to a tested, scanned image pushed with a SHA tag.

Key terms
chart
A Helm package: templated Kubernetes manifests plus default values and metadata in Chart.yaml.
release
One installed instance of a chart in a namespace, with a numbered revision for every upgrade or rollback.
overlay
A Kustomize folder that pulls in a base and applies per-environment patches, image overrides and labels.
GitOps
A deploy model where an in-cluster controller continuously pulls desired state from git and reconciles the cluster to match.
drift
Any difference between the live cluster and the desired state in git, for example after a hand edit.
self-heal
An Argo CD setting that re-applies git automatically when live resources drift from it.
sync wave
An Argo CD annotation that orders how resources are applied, lowest wave first.