Sunday, January 30, 2022

[SOLVED] Shell script should wait until kubernetes pod is running

Issue

In a simple bash script I want to run multiple kubectl and helm commands, like:

helm install \
  cert-manager jetstack/cert-manager \
  --namespace cert-manager \
  --create-namespace \
  --version v1.5.4 \
  --set installCRDs=true
kubectl apply -f deploy/cert-manager/cluster-issuers.yaml

My problem here is, that after the helm install command I have to wait until the cert-manager pod is running, then the kubectl apply command can be used. Right now the script is calling it too early, so it will fail.


Solution

As stated in the comments kubectl wait is the way to go.
Example from the kubectl wait --help

Examples:
  # Wait for the pod "busybox1" to contain the status condition of type "Ready"
  kubectl wait --for=condition=Ready pod/busybox1

This way your script will pause until specified pod is Running, and kubectl will output

<pod-name> condition met

to STDOUT.


kubectl wait is still in experimental phase. If you want to avoid experimental features, you can achieve similar result with bash while loop. By pod name:

while [[ $(kubectl get pods <pod-name> -o 'jsonpath={..status.conditions[?(@.type=="Ready")].status}') != "True" ]]; do
   sleep 1
done

or by label:

while [[ $(kubectl get pods -l <label>=<label-value> -o 'jsonpath={..status.conditions[?(@.type=="Ready")].status}') != "True" ]]; do
   sleep 1
done


Answered By - p10l
Answer Checked By - Willingham (WPSolving Volunteer)