TExcelTAD
Home › Kubernetes Packaging: Helm & Kustomize › Strategic-Merge & JSON Patches

Strategic-Merge & JSON Patches

Fields like namespace, images and replicas cover the common cases. Everything else is a patch: a description of how to change an object from the base. Kustomize's patches field accepts two formats, and choosing the right one saves a lot of frustration.

Strategic merge patch (SMP) JSON patch (RFC 6902)
Looks like a partial object: the fields you want to change a list of operations: add, replace, remove, move, copy, test
Lists merged by key where Kubernetes defines one (containers by name, env by name, ports by containerPort); otherwise replaced addressed by index (/spec/rules/0), or - to append
Good for changing fields of built-in objects, readably precise edits, list items, custom resources, many objects at once
Target by the patch's own kind + metadata.name (or an explicit target) always an explicit target

Both are written in the same patches: list, as a file (path:) or inline (patch: |-).

Strategic merge: containers merge by name

In an SMP, the containers list is merged by name, so a patch can change one container without repeating the others. Special $patch directives delete or replace instead of merging:

bash · try it yourself
mkdir -p base prod
cat > base/deployment.yaml <<'EOF'
apiVersion: apps/v1
kind: Deployment
metadata:
  name: linkly
spec:
  selector: {matchLabels: {app: linkly}}
  template:
    metadata: {labels: {app: linkly}}
    spec:
      containers:
        - name: linkly
          image: ghcr.io/acme/linkly:1.4.0
          env:
            - {name: LOG_LEVEL, value: info}
            - {name: REDIS_ADDR, value: "linkly-redis:6379"}
          resources:
            requests: {cpu: 100m, memory: 64Mi}
        - name: debug-shell
          image: busybox:1.37
          command: [sleep, infinity]
EOF
printf 'resources: [deployment.yaml]\n' > base/kustomization.yaml
cat > prod/kustomization.yaml <<'EOF'
resources: [../base]
patches:
  - patch: |-
      apiVersion: apps/v1
      kind: Deployment
      metadata:
        name: linkly
      spec:
        template:
          spec:
            containers:
              - name: linkly
                env:
                  - {name: LOG_LEVEL, value: warn}
                  - {name: GOMEMLIMIT, value: 200MiB}
                resources:
                  requests: {cpu: 250m}
                  limits: {memory: 256Mi}
              - name: debug-shell
                $patch: delete
EOF
kustomize build prod | sed -n '/containers:/,$p'
      containers:
      - env:
        - name: LOG_LEVEL
          value: warn
        - name: GOMEMLIMIT
          value: 200MiB
        - name: REDIS_ADDR
          value: linkly-redis:6379
        image: ghcr.io/acme/linkly:1.4.0
        name: linkly
        resources:
          limits:
            memory: 256Mi
          requests:
            cpu: 250m
            memory: 64Mi

Within the linkly container, env merged by name (LOG_LEVEL changed, REDIS_ADDR kept, GOMEMLIMIT added), resources.requests merged as a map (memory kept, cpu changed), and the debug-shell container was deleted. That merging comes from the Kubernetes API schema, which is why SMP only knows the merge keys of built-in kinds.

JSON patch: precise operations on many objects

A JSON patch is a list of operations against JSON Pointer paths. ~1 stands for / inside a key and ~0 for ~, so the annotation prometheus.io/port is prometheus.io~1port. With a target selector, one patch can hit many objects:

bash · try it yourself
mkdir -p base prod
cat > base/workloads.yaml <<'EOF'
apiVersion: apps/v1
kind: Deployment
metadata:
  name: linkly
  labels: {tier: web}
spec:
  selector: {matchLabels: {app: linkly}}
  template:
    metadata: {labels: {app: linkly}}
    spec:
      containers: [{name: linkly, image: ghcr.io/acme/linkly:1.4.0, args: [serve]}]
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: linkly-worker
  labels: {tier: worker}
spec:
  selector: {matchLabels: {app: linkly-worker}}
  template:
    metadata: {labels: {app: linkly-worker}}
    spec:
      containers: [{name: worker, image: ghcr.io/acme/linkly:1.4.0, args: [work]}]
EOF
printf 'resources: [workloads.yaml]\n' > base/kustomization.yaml
cat > prod/kustomization.yaml <<'EOF'
resources: [../base]
patches:
  - target: {kind: Deployment}
    patch: |-
      - op: add
        path: /spec/template/metadata/annotations
        value: {prometheus.io/scrape: "true"}
      - op: add
        path: /spec/template/metadata/annotations/prometheus.io~1port
        value: "9090"
  - target: {kind: Deployment, labelSelector: "tier=web"}
    patch: |-
      - op: add
        path: /spec/template/spec/containers/0/args/-
        value: --trusted-proxies=10.0.0.0/8
EOF
kustomize build prod | yq -o json -I0 '{"name": .metadata.name, "annotations": .spec.template.metadata.annotations, "args": .spec.template.spec.containers[0].args}'
{"name":"linkly","annotations":{"prometheus.io/port":"9090","prometheus.io/scrape":"true"},"args":["serve","--trusted-proxies=10.0.0.0/8"]}
{"name":"linkly-worker","annotations":{"prometheus.io/port":"9090","prometheus.io/scrape":"true"},"args":["work"]}

The first patch went to both Deployments; the second, selected by label, only to the web tier, and /args/- appended to the list. target can select by group, version, kind, name (a regular expression), namespace, labelSelector and annotationSelector.

Custom resources: SMP replaces lists

Kustomize has no merge keys for CRDs like HTTPRoute, so an SMP replaces their lists whole. To add one rule to an existing route, use a JSON patch:

bash · try it yourself
mkdir -p base prod
cat > base/route.yaml <<'EOF'
apiVersion: gateway.networking.k8s.io/v1
kind: HTTPRoute
metadata:
  name: linkly
spec:
  parentRefs: [{name: public, namespace: gateway-system}]
  hostnames: [lnk.example.com]
  rules:
    - backendRefs: [{name: linkly, port: 80}]
EOF
printf 'resources: [route.yaml]\n' > base/kustomization.yaml
cat > prod/kustomization.yaml <<'EOF'
resources: [../base]
patches:
  - target: {kind: HTTPRoute, name: linkly}
    patch: |-
      - op: test
        path: /spec/rules/0/backendRefs/0/name
        value: linkly
      - op: add
        path: /spec/rules/0
        value:
          matches: [{path: {type: PathPrefix, value: /admin}}]
          backendRefs: [{name: linkly-admin, port: 80}]
EOF
kustomize build prod | yq '.spec.rules'
kustomize build prod | kubeconform -strict -summary
- backendRefs:
    - name: linkly-admin
      port: 80
  matches:
    - path:
        type: PathPrefix
        value: /admin
- backendRefs:
    - name: linkly
      port: 80
Summary: 1 resource found parsing stdin - Valid: 1, Invalid: 0, Errors: 0, Skipped: 0

add at index 0 inserted the admin rule before the catch-all. The test operation is a guard: if someone changes the base so that rule 0 no longer points at linkly, the build fails instead of patching the wrong rule. Index-based JSON patches are brittle; guard them with test or prefer SMP where merge keys exist.

Choosing

  1. A field of a built-in object, or a container by name → SMP, it reads like the object.
  2. Delete a list item or a container → SMP with $patch: delete.
  3. A CRD's list, an annotation with /, append to a list, or the same change on many objects → JSON patch with a target.
  4. Replace a whole map or list in a built-in object → SMP with $patch: replace on that field.

Test yourself

An SMP sets env: [{name: LOG_LEVEL, value: warn}] on a container that has LOG_LEVEL and REDIS_ADDR. What happens to REDIS_ADDR?

  1. It is removed
  2. It is kept: env is merged by name
  3. The build fails
  4. It is duplicated

How do you write the path to annotation prometheus.io/port in a JSON patch?

  1. /metadata/annotations/prometheus.io/port
  2. /metadata/annotations/prometheus.io~1port
  3. /metadata/annotations/"prometheus.io/port"
  4. /metadata/annotations/prometheus.io%2Fport

Why does an SMP on an HTTPRoute replace its rules list instead of merging?

  1. HTTPRoute is read-only
  2. Kustomize has no merge keys for custom resources
  3. Gateway API forbids merging
  4. rules is a map