kubectl diff: Command Reference for CI/CD
Preview exactly what an apply would change before you run it.
kubectl diff compares your manifests against the live cluster and prints what apply would change, server-side. It is the review step before a deploy. This reference covers its flags and the exit-code semantics that matter in CI.
Common flags and usage
- diff -f <manifest|dir>: diff files against the live state
- diff -k <dir>: diff a kustomize overlay
- Exit 0: no differences; exit 1: differences found
- Exit >1: an actual error occurred
- --server-side: match the server-side apply merge you will run
Example
# Post the planned change on the PR, do not fail the job on a diff
kubectl diff -f k8s/ --server-side > plan.txt; rc=$?
[ "$rc" -le 1 ] || { echo "diff errored"; exit 1; }
cat plan.txtIn CI
diff exits 1 when differences exist, which is expected, not an error, so test for exit >1 to catch real failures. Run it in a PR check to surface the planned change for review, mirroring a Terraform plan step before the apply on merge.
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.
# 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 nodesKey takeaways
- Exit 1 means "there is a diff" and is not a failure; only >1 is an error.
- Match --server-side here to the apply you will actually run.
- A diff PR check is the Kubernetes equivalent of terraform plan.