Kubernetes: Display Pods by age in ascending order

7/31/2019

I use below command to sort the pods by age

kubectl get pods --sort-by={metadata.creationTimestamp}

It shows up pods in descending order. How can we select sorting order like ascending?

-- P Ekambaram
kubectl
kubernetes
sorting

3 Answers

8/2/2019

Sorted kubectl output and awk provide the table view with a header. Installation of extra tools is not needed.

# kubectl get pods --sort-by=.status.startTime | awk 'NR == 1; NR > 1 {print $0 | "tac"}'

An approach with JSON processor offered by paulogrell works also but could require more effort: for some Linux distributions you'll need to download and compile jq from source code. As for the jq command line I'd suggest to add the "name" to the map parameters and sort by "timestamp":

# kubectl get pods -o json | jq '.items | group_by(.metadata.creationTimestamp) | map({"name": .[0].metadata.name, "timestamp": .[0].metadata.creationTimestamp, "count": length}) | sort_by(.timestamp)'
-- mebius99
Source: StackOverflow

7/31/2019

Not supported by kubectl or the kube-apiserver as of this writing (AFAIK), but a workaround would be:

$ kubectl get pods --sort-by=.metadata.creationTimestamp | tail -n +2 | tac

or if tac is not available (MacOS X):

$ kubectl get pods --sort-by=.metadata.creationTimestamp | tail -n +2 | tail -r

If you want the header:

$ echo 'NAME                                                              READY   STATUS             RESTARTS   AGE' | \
 kubectl get pods --sort-by=.metadata.creationTimestamp | tail -n +2 | tac

You might just have to adjust the tabs on the header accordingly.

-- Rico
Source: StackOverflow

7/31/2019

I believe the Kubernetes API doesnt support this option yet, but as a workaround you can use a JSON processor (jq) to adjust its output.

Ascending

kubectl get pods -o json | jq '.items | group_by(.metadata.creationTimestamp) | map({"timestamp": .[0].metadata.creationTimestamp, "count": length}) | sort_by(.count)'

Descending

kubectl get pods -o json | jq '.items | group_by(.metadata.creationTimestamp) | map({"timestamp": .[0].metadata.creationTimestamp, "count": length}) | sort_by(.count) | reverse'

Hope this helps

-- paulogrell
Source: StackOverflow