Skip to content
LatchkeyLatchkey home

kubectl patch: Command Reference for CI/CD

Surgically update one field from a script: pick the right patch type.

kubectl patch applies a partial update and is the scriptable alternative to edit. Choosing the correct --type is what makes it behave as expected. This reference compares the three patch types and shows a CI example.

Common flags and usage

  • --type=strategic (default): Kubernetes list-aware merge for core types
  • --type=merge: plain RFC 7386 merge; replaces lists wholesale (use for CRDs)
  • --type=json: RFC 6902 op list (add/replace/remove) at explicit paths
  • -p '<patch>': inline patch body
  • --patch-file <file>: read the patch from a file

Example

shell
kubectl patch deploy/web --type=json \
  -p '[{"op":"replace","path":"/spec/replicas","value":4}]'

kubectl patch svc/web --type=merge \
  -p '{"spec":{"type":"LoadBalancer"}}'

In CI

Strategic-merge patches misbehave on custom resources, which lack merge metadata, so use --type=merge or --type=json for CRDs. A JSON-patch op against a path that does not exist fails server-side; add the parent first. Prefer apply for whole-object declarative changes and patch only for narrow, scripted edits.

Using this in CI

A runner has no kubeconfig, no cached context, and no interactive auth. Every kubectl invocation in CI needs the context supplied explicitly, and most confusing CI failures here are the command running against the wrong cluster or no cluster at all.

Terminal
# never rely on the ambient context on a runner
kubectl --context "$KUBE_CONTEXT" -n "$NAMESPACE" get pods

# confirm what you are actually connected to before mutating anything
kubectl config current-context
kubectl cluster-info

# fail fast instead of hanging on an unreachable API server
kubectl --request-timeout=30s get nodes

Key takeaways

  • Wrong --type is the top patch mistake; CRDs need merge or json.
  • json patches edit explicit paths; the path must already exist for replace.
  • For whole-object declarative changes, prefer apply over patch.

Frequently asked questions

kubectl patch: Command Reference for CI/CD?
kubectl patch applies a partial update and is the scriptable alternative to edit. Choosing the correct --type is what makes it behave as expected. This reference compares the three patch types and shows a CI example.
In CI?
Strategic-merge patches misbehave on custom resources, which lack merge metadata, so use --type=merge or --type=json for CRDs. A JSON-patch op against a path that does not exist fails server-side; add the parent first. Prefer apply for whole-object declarative changes and patch only for narrow, scripted edits.

Related guides

References

Latchkey auto-heals failures like this one - detected, fixed, and retried without you. Start free → 30-day trial · No credit card