Skip to content
Français
Account: not signed in, sync available My learning
Select theme
Français

kubectl diff and wait: check before, wait after an apply

By updated

Improve this page

Logo Kubernetes

kubectl diff shows what an apply is going to change before you run it, and kubectl wait blocks until a resource reaches the desired state. This lesson is for those who deploy with kubectl and want to automate their deployments in a script or a CI/CD pipeline. You prepare a small Deployment, you read the exit codes of diff, you see why the Available condition does not prove that the new version is running, you wait for a Job, then you assemble a script that decides, applies and waits.

What you will learn

  • Read the output of kubectl diff and tell your changes apart from the fields Kubernetes manages itself
  • Use the exit codes of diff (0, 1 and 2) in a script
  • Wait for a condition with kubectl wait, knowing its default timeout
  • Wait for a Job to finish, successfully or not, without staying blocked
  • Choose between kubectl wait and kubectl rollout status for a Deployment
  • Explain why the Available condition does not prove that the new version is running
  • Write a diff, apply, wait script that stops at the right moment

Prerequisites

You have read kubectl create and apply (the lesson that comes before this one in this module), so you know what apply reports (created, configured, unchanged). You know how to follow a rollout with kubectl rollout status, covered in Rolling updates and rollbacks, and you have the demo cluster from First cluster, with the kind-demo context active. The script at the end uses a return code, an if and set -e: if these notions are new to you, read Write your first script and Bash conditions first.

When should you use diff, and when wait?

The two commands frame an apply and do not replace each other. kubectl diff is used before, to decide whether there is anything to deploy and to review the change. kubectl wait is used after, so that the rest of the script does not start before the resource is in the desired state. A successful apply only says that the API accepted the manifest, never that the Pods are running.

MomentCommandWhat it does
Before applykubectl diff -f folder/Shows the difference between the cluster and the files
After applykubectl wait --for=condition=... --timeout=...Blocks until a condition is met, or fails at the timeout
After apply of a Deploymentkubectl rollout status deployment/... --timeout=...Blocks until the rollout of the new version is complete

Set up the working folder

The demonstration follows a passerelle Deployment (two Nginx Pods) and its Service, stored in an app/ folder. A second folder, jobs/, will hold two Jobs. Create the namespace, then the files of the Deployment and the Service.

Terminal window
kubectl create namespace verifier
mkdir -p ~/atelier-k8s/verifier/app ~/atelier-k8s/verifier/jobs
cd ~/atelier-k8s/verifier
Output
namespace/verifier created
Terminal window
cat > app/deployment.yaml <<'EOF'
apiVersion: apps/v1
kind: Deployment
metadata:
name: passerelle
labels:
app: passerelle
spec:
replicas: 2
selector:
matchLabels:
app: passerelle
template:
metadata:
labels:
app: passerelle
spec:
containers:
- name: nginx
image: nginx:1.30.5@sha256:9bf97bd7714f5e24c1ccd545ecb9eb5435cb6d109c97cebb15e7e455e0239edb
ports:
- containerPort: 80
EOF
cat > app/service.yaml <<'EOF'
apiVersion: v1
kind: Service
metadata:
name: passerelle
spec:
selector:
app: passerelle
ports:
- port: 80
targetPort: 80
EOF

These commands print nothing. The following commands are run from ~/atelier-k8s/verifier, since the app/ and jobs/ paths are relative to it.

kubectl diff: what is my apply going to change?

kubectl diff -f asks the API server what each object would become if you ran apply, through a dry run (a server-side dry-run: the computation is done, nothing is written). It then compares that result with the current object and displays it in unified diff format, where - marks what leaves and + what arrives. The verifier namespace is empty, so everything is new. The echo messages of this lesson are in French on purpose, so that the outputs stay those of the tested cluster: "code de sortie" means "exit code".

Terminal window
kubectl diff -f app/ -n verifier; echo "code de sortie : $?"
Output (the Service diff, of the same shape and 25 lines long, is cut before the last line)
diff -u -N /tmp/LIVE-551655649/apps.v1.Deployment.verifier.passerelle /tmp/MERGED-4051806654/apps.v1.Deployment.verifier.passerelle
--- /tmp/LIVE-551655649/apps.v1.Deployment.verifier.passerelle 2026-11-11 14:51:37.550155243 +0000
+++ /tmp/MERGED-4051806654/apps.v1.Deployment.verifier.passerelle 2026-11-11 14:51:37.554155555 +0000
@@ -0,0 +1,43 @@
+apiVersion: apps/v1
+kind: Deployment
+metadata:
+ creationTimestamp: "2026-11-11T14:51:37Z"
+ generation: 1
+ labels:
+ app: passerelle
+ name: passerelle
+ namespace: verifier
+ uid: 03c04894-b59c-4bde-8877-df482828c568
+spec:
+ progressDeadlineSeconds: 600
+ replicas: 2
+ revisionHistoryLimit: 10
+ selector:
+ matchLabels:
+ app: passerelle
+ strategy:
+ rollingUpdate:
+ maxSurge: 25%
+ maxUnavailable: 25%
+ type: RollingUpdate
+ template:
+ metadata:
+ labels:
+ app: passerelle
+ spec:
+ containers:
+ - image: nginx:1.30.5@sha256:9bf97bd7714f5e24c1ccd545ecb9eb5435cb6d109c97cebb15e7e455e0239edb
+ imagePullPolicy: IfNotPresent
+ name: nginx
+ ports:
+ - containerPort: 80
+ protocol: TCP
+ resources: {}
+ terminationMessagePath: /dev/termination-log
+ terminationMessagePolicy: File
+ dnsPolicy: ClusterFirst
+ restartPolicy: Always
+ schedulerName: default-scheduler
+ securityContext: {}
+ terminationGracePeriodSeconds: 30
+status: {}
code de sortie : 1

Look first at the @@ -0,0 +1,43 @@ header: zero lines on the left, forty-three on the right, so the object does not exist yet and the diff shows it in full. Then look at the fields your file does not contain: progressDeadlineSeconds, strategy, imagePullPolicy, terminationGracePeriodSeconds. These are the default values set by the server. The last line, code de sortie : 1, is explained below.

Apply the files and wait for the rollout to finish, then run the same diff again. This time, the cluster and the files are identical.

Terminal window
kubectl apply -f app/ -n verifier && kubectl rollout status deployment/passerelle -n verifier --timeout=90s
Output
deployment.apps/passerelle created
service/passerelle created
Waiting for deployment "passerelle" rollout to finish: 0 of 2 updated replicas are available...
Waiting for deployment "passerelle" rollout to finish: 1 of 2 updated replicas are available...
deployment "passerelle" successfully rolled out
Terminal window
kubectl diff -f app/ -n verifier; echo "code de sortie : $?"
Output
code de sortie : 0

The diff prints nothing and the code is 0: no difference. Now change the number of replicas in the file, from 2 to 3, and look at the diff.

Terminal window
sed -i 's/replicas: 2/replicas: 3/' app/deployment.yaml && kubectl diff -f app/ -n verifier; echo "code de sortie : $?"
Output
diff -u -N /tmp/LIVE-3041059678/apps.v1.Deployment.verifier.passerelle /tmp/MERGED-694481729/apps.v1.Deployment.verifier.passerelle
--- /tmp/LIVE-3041059678/apps.v1.Deployment.verifier.passerelle 2026-11-11 14:51:38.538232354 +0000
+++ /tmp/MERGED-694481729/apps.v1.Deployment.verifier.passerelle 2026-11-11 14:51:38.538232354 +0000
@@ -6,7 +6,7 @@
kubectl.kubernetes.io/last-applied-configuration: |
{"apiVersion":"apps/v1","kind":"Deployment","metadata":{"annotations":{},"labels":{"app":"passerelle"},"name":"passerelle","namespace":"verifier"},"spec":{"replicas":2,"selector":{"matchLabels":{"app":"passerelle"}},"template":{"metadata":{"labels":{"app":"passerelle"}},"spec":{"containers":[{"image":"nginx:1.30.5@sha256:9bf97bd7714f5e24c1ccd545ecb9eb5435cb6d109c97cebb15e7e455e0239edb","name":"nginx","ports":[{"containerPort":80}]}]}}}}
creationTimestamp: "2026-11-11T14:51:37Z"
- generation: 1
+ generation: 2
labels:
app: passerelle
name: passerelle
@@ -15,7 +15,7 @@
uid: df14b5f5-3771-4d06-8f2a-562b1e1b7c54
spec:
progressDeadlineSeconds: 600
- replicas: 2
+ replicas: 3
revisionHistoryLimit: 10
selector:
matchLabels:
code de sortie : 1

Two blocks appear, and only one comes from you: replicas: 2 becomes replicas: 3. The other, generation: 1 turning into generation: 2, is a counter that Kubernetes increases at every modification of the spec. It shows up in any diff that changes something.

Which exit codes does kubectl diff return?

kubectl diff follows the convention of the Unix diff utility, described in kubectl diff --help. It is this code, not the displayed text, that a script must read. Above all, remember that code 1 is not an error: it is the answer "there are changes", which you got twice above.

CodeMeaningCases met in the lesson
0No differenceFolder identical to the cluster
1Differences existObjects not created yet, modified replicas
2 or morekubectl or diff failedNonexistent path, see below

Here is code 2 on a path that does not exist:

Terminal window
kubectl diff -f app/inexistant.yaml -n verifier; echo "code de sortie : $?"
Output
error: the path "app/inexistant.yaml" does not exist
code de sortie : 2

Two practical consequences for a script. The chain kubectl diff -f app/ && kubectl apply -f app/ does the opposite of what you expect, since apply would only run when there is nothing to do. And under set -e, code 1 stops the script: you must capture the code explicitly, as the full script at the end of the lesson does.

Compare a folder or a Kustomize overlay

diff accepts the same sources as apply: several -f, a folder with -R to descend into subfolders, or a Kustomize overlay with -k, which the lesson Kustomize covers in detail. The exit code covers the whole set: it is 1 as soon as a single object differs.

Terminal window
kubectl diff -f app/ -R -n verifier
kubectl diff -k overlays/prod/

By default, diff compares against a simulated client-side apply. The --server-side option changes this computation: the comparison goes through a simulated server-side apply, the one the API would perform with kubectl apply --server-side.

Which permissions does a diff need?

A dry-run request is authorized like a real write. An account that can read a Deployment without being able to modify it therefore gets a Forbidden refusal on patch, with exit code 2. The account of a pipeline that runs diff needs the same RBAC verbs (Kubernetes access rights) as apply: get, patch, and create for a new object.

Now apply the three replicas, to start again from a stable state.

Terminal window
kubectl apply -f app/ -n verifier && kubectl rollout status deployment/passerelle -n verifier --timeout=90s
Output
deployment.apps/passerelle configured
service/passerelle unchanged
Waiting for deployment "passerelle" rollout to finish: 2 of 3 updated replicas are available...
deployment "passerelle" successfully rolled out

What is the default timeout of kubectl wait?

kubectl wait watches a resource and returns as soon as a condition is met (code 0), or when the timeout expires (code 1). Without --timeout, it gives up after 30 seconds. The help of the command confirms it.

Terminal window
kubectl wait --help | grep -A1 -e '--timeout'
Output (the first three blocks, examples, are cut)
--timeout=30s:
The length of time to wait before giving up. Zero means check once and don't wait, negative means wait for a week.

A timeout of 0 checks once without waiting, and a negative value waits for a week. So always set the timeout yourself: 30 seconds are rarely enough for a deployment that has to pull an image.

Which conditions can you wait for?

Each object type publishes its conditions in its status, and --for designates them by name. kubectl get <type>/<name> -o yaml shows the ones that exist and their current value. CRDs (the types that extensions add to the API) often publish their own, most often a Ready condition, and wait waits for them the same way.

--for=On whatWhat it waits for
condition=ReadyPodThe readiness probe passes (without a probe: as soon as the container starts)
condition=AvailableDeploymentThe minimum number of available replicas is reached
condition=CompleteJobThe Job succeeded
condition=FailedJobThe Job failed
deleteAny resourceThe resource is gone
createAny resourceThe resource appears in the API
jsonpath='{...}'=valueAny resourceA status field has the given value

Wait for all the Pods with a label

With -l, wait waits for all the objects selected by the label to meet the condition. If the selector finds nothing, the command fails immediately instead of waiting: a mistyped label is therefore seen right away. --for=delete is used after a kubectl delete --wait=false, or before recreating an object with the same name.

Why does Available not prove that the new version is running?

The Available condition of a Deployment only says that the minimum number of Pods is available, whatever their version. To see it, trigger a rollout that cannot succeed: set an image tag that does not exist. The API accepts the manifest, since it does not check that the image exists.

Terminal window
sed -i 's|image: .*|image: nginx:1.30.999 # ❌ nonexistent tag, on purpose|' app/deployment.yaml && kubectl apply -f app/ -n verifier
Output
deployment.apps/passerelle configured
service/passerelle unchanged

Now wait for the Available condition.

Terminal window
kubectl wait --for=condition=Available deployment/passerelle -n verifier --timeout=30s
Output
deployment.apps/passerelle condition met

The condition is met immediately, because the three old Pods are still running. If your script relied on this answer, it would conclude that the new version is deployed, when none of its Pods starts. kubectl rollout status follows the new version and gives the other answer.

Terminal window
kubectl rollout status deployment/passerelle -n verifier --timeout=30s; echo "code de sortie : $?"
Output
Waiting for deployment "passerelle" rollout to finish: 1 out of 3 new replicas have been updated...
error: timed out waiting for the condition
code de sortie : 1

After 30 seconds, rollout status fails with code 1: the new version is not complete. This is the behavior you want in a deployment script.

Can you wait for a version with kubectl wait?

Yes, with jsonpath conditions on the status fields of the Deployment. First read four numbers: the desired generation (metadata.generation), the generation already seen by the controller (status.observedGeneration), the up-to-date Pods (status.updatedReplicas) and the available Pods (status.availableReplicas).

Terminal window
kubectl get deployment passerelle -n verifier -o jsonpath='{.metadata.generation}{" "}{.status.observedGeneration}{" "}{.status.updatedReplicas}{" "}{.status.availableReplicas}{"\n"}'
Output
3 3 1 3

Read these four numbers in order: generation 3 is desired and observed, only one Pod is up to date out of the three expected, and three Pods are available (the old ones). The two missing up-to-date Pods will not arrive as long as the image is wrong: a wait that counts up-to-date Pods must therefore fail here.

kubectl wait accepts several --for=jsonpath in the same command, evaluated in the order of the line with a shared timeout. Put observedGeneration first: right after an apply, the controller has not seen the new generation yet and updatedReplicas keeps the value of the old ReplicaSet. A wait on updatedReplicas=3 alone can therefore pass wrongly. With observedGeneration equal to the desired generation as the first condition, it first waits for the controller to have seen the change.

Terminal window
GEN=$(kubectl get deployment passerelle -n verifier -o jsonpath='{.metadata.generation}')
kubectl wait deployment/passerelle -n verifier \
--for=jsonpath='{.status.observedGeneration}'="$GEN" \
--for=jsonpath='{.status.updatedReplicas}'=3 \
--for=jsonpath='{.status.availableReplicas}'=3 \
--timeout=20s; echo "code de sortie : $?"
Output
deployment.apps/passerelle condition met
error: timed out waiting for the condition on deployments/passerelle
code de sortie : 1

The first condition is met (condition met), the second never is as long as the image is wrong, and the timeout expires with code 1. Go back to the original image, then run the same wait again.

Terminal window
sed -i 's|image: .*|image: nginx:1.30.5@sha256:9bf97bd7714f5e24c1ccd545ecb9eb5435cb6d109c97cebb15e7e455e0239edb|' app/deployment.yaml && kubectl apply -f app/ -n verifier
Output
deployment.apps/passerelle configured
service/passerelle unchanged
Terminal window
GEN=$(kubectl get deployment passerelle -n verifier -o jsonpath='{.metadata.generation}')
kubectl wait deployment/passerelle -n verifier \
--for=jsonpath='{.status.observedGeneration}'="$GEN" \
--for=jsonpath='{.status.updatedReplicas}'=3 \
--for=jsonpath='{.status.availableReplicas}'=3 \
--timeout=90s
Output
deployment.apps/passerelle condition met
deployment.apps/passerelle condition met
deployment.apps/passerelle condition met

There is one condition met line per condition. The command returns in less than a second here because going back to the original image reactivates the old ReplicaSet, which was already complete.

This wait has a limit. A wait with three conditions can return before the old Pod has left: updatedReplicas and availableReplicas count the up-to-date and available Pods, not those still shutting down. It proves that the new version is being served, not that the old one is gone.

For a Deployment, use kubectl rollout status --timeout=... instead, which waits for the new version and the departure of the old one. Keep kubectl wait for Pods, Jobs, deletions and resources that have no rollout.

Terminal window
kubectl rollout status deployment/passerelle -n verifier --timeout=90s
Output
deployment "passerelle" successfully rolled out

Wait for a Job to finish, successfully or not

A Job runs a Pod until a task finishes, a database migration for example. The lesson Jobs and CronJobs covers it in detail: here, the two Jobs are provided in full and you only have to read them. The first succeeds after 5 seconds, the second fails immediately, with no retry (backoffLimit: 0).

Terminal window
cat > jobs/migration.yaml <<'EOF'
apiVersion: batch/v1
kind: Job
metadata:
name: migration-db
spec:
backoffLimit: 0
template:
spec:
restartPolicy: Never
containers:
- name: migration
image: busybox:1.38.0@sha256:a46257e06c82ad85242d0d38077d0a52d9896389ca60a1a59d3463db586e5fa4
command: ["sh", "-c", "echo migration en cours; sleep 5; echo migration terminée"]
EOF
cat > jobs/migration-echec.yaml <<'EOF'
apiVersion: batch/v1
kind: Job
metadata:
name: migration-echec
spec:
backoffLimit: 0
template:
spec:
restartPolicy: Never
containers:
- name: migration
image: busybox:1.38.0@sha256:a46257e06c82ad85242d0d38077d0a52d9896389ca60a1a59d3463db586e5fa4
command: ["sh", "-c", "echo migration en cours; exit 1"]
EOF

Apply the first one and wait for it to finish with the Complete condition.

Terminal window
kubectl apply -f jobs/migration.yaml -n verifier && kubectl wait --for=condition=Complete job/migration-db -n verifier --timeout=60s
Output
job.batch/migration-db created
job.batch/migration-db condition met

The command returned after a few seconds, when the Job finished. Do the same with the Job that fails.

Terminal window
kubectl apply -f jobs/migration-echec.yaml -n verifier && kubectl wait --for=condition=Complete job/migration-echec -n verifier --timeout=15s; echo "code de sortie : $?"
Output
job.batch/migration-echec created
error: timed out waiting for the condition on jobs/migration-echec
code de sortie : 1

The Job failed immediately, and yet wait waited the full 15 seconds of the timeout: the Complete condition is only met by a successful Job, and it never comes here. With a 300-second timeout in a pipeline, you would lose five minutes before learning that the migration failed. The Failed condition, on the other hand, answers immediately.

Terminal window
kubectl wait --for=condition=Failed job/migration-echec -n verifier --timeout=60s
Output
job.batch/migration-echec condition met

To exit as early as possible in both cases, query the two conditions in turn with --timeout=0, which checks once without waiting, in a loop bounded by an overall timeout. The following loop stops on Complete (code 0), on Failed (code 1) or after 60 seconds (code 2). Write it into a script that receives the name of the Job as an argument: SECONDS is the shell's seconds counter, and the last line, exit "$code", passes this code on to the pipeline that runs the script.

cat > attendre-job.sh <<'EOF'
#!/usr/bin/env bash
job="$1"; fin=$((SECONDS + 60)); code=2
while [ "$SECONDS" -lt "$fin" ]; do
if kubectl wait --for=condition=Complete "job/$job" -n verifier --timeout=0 >/dev/null 2>&1; then code=0; break; fi
if kubectl wait --for=condition=Failed "job/$job" -n verifier --timeout=0 >/dev/null 2>&1; then code=1; break; fi
sleep 2
done
echo "code de sortie : $code"
exit "$code"
EOF
bash attendre-job.sh migration-echec
Output
code de sortie : 1

The migration-echec Job has already failed: the loop sees it on the first pass and returns immediately. Run on migration-db, which succeeds, it prints code de sortie : 0 as soon as the Job finishes. Since each pass asks two quick questions instead of one long wait, a failing Job is detected without using up the timeout. On a Job that lasts more than 60 seconds, the loop exits with code 2, and the pipeline knows the Job did not finish.

How do you write a diff, apply, wait script?

The script ties the lesson together. It decides with the code of diff, applies, then waits for the new version with rollout status. It takes three arguments: the folder of manifests, the namespace and the name of the Deployment.

cat > deployer.sh <<'EOF'
#!/usr/bin/env bash
# Usage: ./deployer.sh <folder> <namespace> <deployment>
set -euo pipefail
dossier="$1"
namespace="$2"
deploiement="$3"
# Exit code of kubectl diff: 0 = no difference, 1 = differences, more than 1 = error.
# "|| code=$?" keeps the code without set -e stopping the script on the 1.
code=0
kubectl diff -f "$dossier" -n "$namespace" || code=$?
if [ "$code" -eq 0 ]; then
echo "Aucune différence : rien à appliquer."
exit 0
fi
if [ "$code" -gt 1 ]; then
echo "kubectl diff a échoué (code $code)." >&2
exit "$code"
fi
kubectl apply -f "$dossier" -n "$namespace"
kubectl rollout status "deployment/$deploiement" -n "$namespace" --timeout=120s
echo "Déploiement terminé."
EOF
chmod +x deployer.sh

Read it step by step. The three argument lines store the folder, the namespace and the Deployment in variables, and set -euo pipefail stops the script at the first failing command. The code=0 line, followed by kubectl diff ... || code=$?, is the key point: without the ||, set -e would stop the script on code 1, which is nevertheless a normal answer. The messages the script prints are in French on purpose, like the other outputs of the lesson: "Aucune différence : rien à appliquer." means "No difference: nothing to apply", "kubectl diff a échoué" means "kubectl diff failed" and "Déploiement terminé." means "Deployment finished."

The two if statements then filter this code. The first exits without applying anything when there is no difference. The second exits with the error code of diff when it exceeds 1. Code 1 passes between the two, so apply runs. Finally, rollout status waits for the new version and, thanks to set -e, an exceeded timeout makes the script fail.

Run it first on a folder that matches the cluster.

Terminal window
./deployer.sh app verifier passerelle; echo "code de sortie : $?"
Output
Aucune différence : rien à appliquer.
code de sortie : 0

Then change the replicas from 3 to 4 in the file and run the script again. It should display the diff, apply, wait and conclude.

Terminal window
sed -i 's/replicas: 3/replicas: 4/' app/deployment.yaml && ./deployer.sh app verifier passerelle; echo "code de sortie : $?"
Output
diff -u -N /tmp/LIVE-1901228559/apps.v1.Deployment.verifier.passerelle /tmp/MERGED-436096492/apps.v1.Deployment.verifier.passerelle
--- /tmp/LIVE-1901228559/apps.v1.Deployment.verifier.passerelle 2026-11-11 14:52:56.472393303 +0000
+++ /tmp/MERGED-436096492/apps.v1.Deployment.verifier.passerelle 2026-11-11 14:52:56.472393303 +0000
@@ -6,7 +6,7 @@
kubectl.kubernetes.io/last-applied-configuration: |
{"apiVersion":"apps/v1","kind":"Deployment","metadata":{"annotations":{},"labels":{"app":"passerelle"},"name":"passerelle","namespace":"verifier"},"spec":{"replicas":3,"selector":{"matchLabels":{"app":"passerelle"}},"template":{"metadata":{"labels":{"app":"passerelle"}},"spec":{"containers":[{"image":"nginx:1.30.5@sha256:9bf97bd7714f5e24c1ccd545ecb9eb5435cb6d109c97cebb15e7e455e0239edb","name":"nginx","ports":[{"containerPort":80}]}]}}}}
creationTimestamp: "2026-11-11T14:51:37Z"
- generation: 4
+ generation: 5
labels:
app: passerelle
name: passerelle
@@ -15,7 +15,7 @@
uid: df14b5f5-3771-4d06-8f2a-562b1e1b7c54
spec:
progressDeadlineSeconds: 600
- replicas: 3
+ replicas: 4
revisionHistoryLimit: 10
selector:
matchLabels:
deployment.apps/passerelle configured
service/passerelle unchanged
Waiting for deployment "passerelle" rollout to finish: 3 of 4 updated replicas are available...
deployment "passerelle" successfully rolled out
Déploiement terminé.
code de sortie : 0

The output follows the three steps of the script: the diff, the apply, then the wait and "Déploiement terminé.". Run the script a third time, without changing anything: it should stop right at the diff.

Terminal window
./deployer.sh app verifier passerelle; echo "code de sortie : $?"
Output
Aucune différence : rien à appliquer.
code de sortie : 0

A deployment script must also fail cleanly. Give it a folder that does not exist.

Terminal window
./deployer.sh inexistant verifier passerelle; echo "code de sortie : $?"
Output
error: the path "inexistant" does not exist
kubectl diff a échoué (code 2).
code de sortie : 2

The code 2 of kubectl diff is passed on as is by the script, which a CI pipeline reads as a failure. The same script can run in a CI job, provided the job's account has access to the cluster with the rights of apply.

Clean up the cluster

Deleting the namespace deletes the Deployment, the Service and the two Jobs with it. Then erase the working folder.

Terminal window
kubectl delete namespace verifier && rm -rf ~/atelier-k8s/verifier
Output
namespace "verifier" deleted

Troubleshooting

When a wait ends with an exceeded timeout, kubectl describe and the events of the resource almost always say why the condition does not come.

SymptomLikely causeSolution
The script stops right after kubectl diffset -e and code 1, which means "changes"Capture the code with || code=$?
error: timed out waiting for the condition after 30 sNo --timeout, default timeoutSet a suitable timeout, then read kubectl describe
wait --for=condition=Complete blocks until the timeoutThe Job failedAlso wait for condition=Failed
Available reached, but the old version is runningAvailable ignores the version of the PodsUse kubectl rollout status
Forbidden on patch during a diffThe account can read but not write, and the dry-run request is authorized like a writeGrant the get, patch and create verbs

Put it into practice

The lab replays this gesture on another Deployment: preview a change with kubectl diff by reading its exit code, apply, then wait with the right command, kubectl rollout status for the Deployment and kubectl wait for a Job that can fail. The validation covers the state of the cluster at the end and a script that stops at the right moment, not the commands typed.

Key takeaways

  • kubectl diff computes the result of an apply through a dry-run request to the server and displays it in unified diff format.
  • Its exit codes are 0 (no difference), 1 (differences, new object included) and 2 or more (error, for example a nonexistent path); under set -e, capture them with || code=$?.
  • diff requires the same permissions as apply, because a dry-run request is authorized like a write.
  • kubectl wait gives up after 30 seconds by default: always set --timeout.
  • condition=Complete is only met by a successful Job; a failed Job is detected with condition=Failed.
  • condition=Available can be met by the old Pods: for a Deployment, kubectl rollout status --timeout waits for the complete new version.
  • Several --for=jsonpath are evaluated in order: put observedGeneration first.

Test your knowledge

To check that you can read the exit codes of kubectl diff, set the timeout of kubectl wait, wait for a Job without staying blocked and choose the right wait for a Deployment.

Knowledge check

Check what you have learned with this interactive quiz

6 questions
5 min
80% to pass

How it works

  • The timer starts when you click Start
  • Multiple choice, true/false and short answer questions
  • You can move between questions
  • Detailed results are shown at the end

Starts the quiz and the timer