kubectl apply and diff
- Version
- 1.37
- Review
- Draft
Summary#
kubectl apply creates or updates objects to match manifest files. kubectl diff shows what an apply would change. With --server-side, the API server merges the manifest, tracks which manager owns each field and reports conflicts.
Syntax#
kubectl diff -f FILE_OR_DIRECTORY
kubectl apply -f FILE_OR_DIRECTORY
kubectl apply --server-side -f FILE
kubectl apply -k KUSTOMIZE_DIRECTORY
Example#
diff uses a diff program on your machine. The script ignores any custom KUBECTL_EXTERNAL_DIFF setting and keeps only the changed data line.
(
set -eu
unset KUBECTL_EXTERNAL_DIFF
work=$(mktemp -d)
trap 'rm -rf -- "$work"' EXIT
ns="ref-apply-$$"
kubectl create namespace "$ns" >/dev/null
trap 'kubectl delete namespace "$ns" >/dev/null; rm -rf -- "$work"' EXIT
manifest="$work/settings.yaml"
printf '%s\n' 'apiVersion: v1' 'kind: ConfigMap' 'metadata:' ' name: settings' \
'data:' ' color: blue' > "$manifest"
status=0
kubectl diff -n "$ns" -f "$manifest" >/dev/null || status=$?
[ "$status" -le 1 ] || exit "$status"
echo "diff before create: exit $status"
kubectl apply -n "$ns" -f "$manifest"
status=0
kubectl diff -n "$ns" -f "$manifest" >/dev/null || status=$?
[ "$status" -le 1 ] || exit "$status"
echo "diff after create: exit $status"
sed 's/color: blue/color: green/' "$manifest" > "$work/changed.yaml"
mv "$work/changed.yaml" "$manifest"
status=0
kubectl diff -n "$ns" -f "$manifest" > "$work/changes.diff" || status=$?
[ "$status" -le 1 ] || exit "$status"
echo "diff after edit: exit $status"
grep -E '^[-+] color:' "$work/changes.diff"
kubectl apply -n "$ns" -f "$manifest"
kubectl apply -n "$ns" -f "$manifest"
)
Expected output#
diff before create: exit 1
configmap/settings created
diff after create: exit 0
diff after edit: exit 1
- color: blue
+ color: green
configmap/settings configured
configmap/settings unchanged
Common mistakes#
Exit status 1 from kubectl diff means that differences exist, while a status above 1 means failure. The server-side dry run is authorized like a real write, so allow patch for existing objects and create for new ones. Avoid forcing a server-side conflict until you know who else manages the field.
Version applicability#
The example targets Kubernetes 1.37 and uses the default client-side apply. Server-side apply is stable since 1.22.
Sources#
- Attribution
- DevLookup contributors
- License
- CC-BY-4.0