Kubernetes sort pods by age

Viewed 78006

I can sort my Kubernetes pods by name using:

kubectl get pods --sort-by=.metadata.name

How can I sort them (or other resoures) by age using kubectl?

7 Answers
kubectl get pods --sort-by=.metadata.creationTimestamp

If you are trying to get the most recently created pod you can do the following

kubectl get pods --sort-by=.metadata.creationTimestamp -o jsonpath='{.items[-1:].metadata.name}'

Note the -1: gets the last item in the list, then we return the pod name

If you want to sort them in reverse order based on the age:

kubectl get po --sort-by=.metadata.creationTimestamp -n <<namespace>> | tac

If you want just the name of most-recently-created pod;

POD_NAME=$(kubectl get pod --sort-by=.metadata.creationTimestamp -o name | cut -d/ -f2 | tail -n 1)
echo "${POD_NAME}"

I wanted to see all pods that were updated in the past 24 hours. This worked perfectly well and doesn't rely on a particular version of Kubernetes or Kubernetes advanced parameters besides get pods:

kubectl get pods | awk '{print $1 " : " $5}' | grep -E ':\s([1-9]|[12][0-4])h$' | sort -k3,3

This new command (since Kubernetes 1.23) worked perfectly for me:

kubectl alpha events

In contrast, neither of these worked for me (got unsorted events):

  • kubectl get events --sort-by='.lastTimestamp'
  • kubectl get events --sort-by=.metadata.creationTimestamp

I also saw reports that the above failed due to missing event properties: https://github.com/kubernetes/kubernetes/issues/29838#issuecomment-991070746

Related