Wait for Kubernetes objects to become available using kubectl wait

kubernetes kubectl wait

2 min read | by Jordi Prats

Sometimes we need to wait for some condition to be met before continuing applying resources on the cluster (or accessing them in som way). We can use kubectl wait to block an script until some criteria is met.

We are going to use a Deployment as an example, but this can be used in any object that publishes conditions using the status field:

$ kubectl get deploy test-app -o yaml
apiVersion: apps/v1
kind: Deployment
(...)
status:
  availableReplicas: 1
  conditions:
  - lastTransitionTime: "2023-01-08T20:53:54Z"
    lastUpdateTime: "2023-01-08T20:53:54Z"
    message: Deployment has minimum availability.
    reason: MinimumReplicasAvailable
    status: "True"
    type: Available
  - lastTransitionTime: "2023-01-08T19:22:25Z"
    lastUpdateTime: "2023-01-08T20:53:54Z"
    message: ReplicaSet "test-app-598df49646" has successfully progressed.
    reason: NewReplicaSetAvailable
    status: "True"
    type: Progressing

We can make it go to false by triggering a redeploy using kubectl rollout restart:

$ kubectl rollout restart deploy test-app

Now we can use kubectl wait for the Available condition to get back to true using the following command:

$ kubectl wait deploy/test-app --for=condition=Available --timeout=300s 
deployment.apps/test-app condition met

We can use any condition that gets published, for example, for strimzi's Kafka, the condition is Ready:

$ kubectl get kafka demo-cluster -o yaml
apiVersion: kafka.strimzi.io/v1beta2
kind: Kafka
(...)
status:
  clusterId: Zid7QZ2VYiPSRonYgNu55Q
  conditions:
  - lastTransitionTime: "2023-01-08T19:23:45.770737Z"
    status: "True"
    type: Ready

So the command that would wait for the cluster to become available would be:

$ kubectl wait kafka/demo-cluster --for=condition=Ready --timeout=300s
kafka.kafka.strimzi.io/demo-cluster condition met

Posted on 09/01/2023

Categories