Bash script to check if openshift/kubernetes pods are ready

Viewed 11132

I am trying to create a shell script that will validate that certain pods are ready by checking the READY heading showing 1/1. I have tried two ways.

1.

ready=$(oc get pods | awk '{print $2}' | tail -n +2) # prints 1/1 or 0/1 for each pod
until [[ ${ready} == "1/1" ]]
do
  echo "Waiting for pods to be ready."
  sleep 3
done

Above script just keeps saying "Waiting for pods to be ready" even when the pods are ready and displaying 1/1 in the READY column.

2.

while true ; do
  for i in 1 2 3; do
  ready=`oc get pods | awk '{print $2}' | tail -n +2 | head -n $i` 

  if [[ "${ready}" == "1/1" ]]; then
    echo "pods are up and running"
  else
    echo "waiting for pods to be ready"
  sleep 10
  break
  fi
  done
done

Above script just continually prints waiting for pods to be ready and pods are up and running.

Any help would be appreciated, I am starting with Bash and not quite sure what to do.

3 Answers

I'm surprised no one so far has mentioned the experimental, yet official kubectl wait:
$ kubectl wait ([-f FILENAME] | resource.group/resource.name | resource.group [(-l label | --all)]) [--for=delete|--for condition=available]

Following solutions works for me

while [ "$(kubectl get pods -l=app='activemq' -o jsonpath='{.items[*].status.containerStatuses[0].ready}')" != "true" ]; do
   sleep 5
   echo "Waiting for Broker to be ready."
done

For pod status, the one and only answer (a pod can be Running but not yet ready!):

kubectl get pods -l <key=val> -o 'jsonpath={..status.conditions[?(@.type=="Ready")].status}'

For individual container statuses (need to be "true"):

kubectl get pod <pod_name> --output="jsonpath={.status.containerStatuses[*].ready}" | cut -d' ' -f2

If you want to check the status of several pods, you can use -l to filter and just prefix .items[*]:

kubectl get pods -l <key=val> --output="jsonpath={.items[*].status.conditions[*].status}"
Related