Get count of Kubernetes pods that aren't running

5/6/2020

I've this command to list the Kubernetes pods that are not running:

sudo kubectl get pods -n my-name-space | grep -v Running

Is there a command that will return a count of pods that are not running?

-- runnerpaul
kubernetes
kubernetes-pod

1 Answer

5/6/2020

If you add ... | wc -l to the end of that command, it will print the number of lines that the grep command outputs. This will probably include the title line, but you can suppress that.

kubectl get pods -n my-name-space --no-headers \
  | grep -v Running \
  | wc -l

If you have a JSON-processing tool like jq available, you can get more reliable output (the grep invocation will get an incorrect answer if an Evicted pod happens to have the string Running in its name). You should be able to do something like (untested)

kubectl get pods -n my-namespace -o json \
  | jq '.items | map(select(.status.phase != "Running")) | length'

If you'll be doing a lot of this, writing a non-shell program using the Kubernetes API will be more robust; you will generally be able to do an operation like "get pods" using an SDK call and get back a list of pod objects that you can filter.

-- David Maze
Source: StackOverflow