I want to get the name of the oldest pod as part of a script. It seems like I should be able to run kubectl get po --no-headers=true
, sort-by AGE, and then just pipe to head -n1|awk '{print $1}'
, but I can't seem to get sort-by working. I'm running kubectl 1.7.9.
This can be accomplished with:
kubectl get pods --sort-by=.metadata.creationTimestamp -o=name | head -1
I'm not sure what version this started work in, but I'm using it in kubectl 1.12.
The AGE times are in an irregular format (23m
, 2d
) that’s hard to sort on, but you can ask kubectl
to write out the time a pod started instead. The times will come out in the very sortable ISO 8601 format. This recipe to get the single oldest pod might work for you:
kubectl get pods \
--no-headers \
--output=custom-columns=START:.status.startTime,NAME:.metadata.name \
| sort \
| head -1 \
| awk '{print $2}'
The kubectl
command asks to only print out the start time and name, in that order, for each pod.
Also consider kubectl get pods -o json
, which will give you a very large very detailed JSON record. If you have a preferred full-featured scripting language you can pick that apart there, or use a command-line tool like jq
to try digesting it further. Any field path can also be inserted into the custom-columns
output spec.