Kubernetes: Display Pods by age in ascending order

夙愿已清 提交于 2021-02-18 20:58:38

问题


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?


回答1:


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)'



回答2:


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.




回答3:


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




回答4:


It Is Quite EASY: Once you have used --no-headers option, the HEADER will not be part of output (ascending ordered-listing of pods) and you can simply reverse sort the outcome of the command.

Here's the complete command to get exactly what is expected:

kubectl get po --sort-by={metadata.creationTimestamp} --no-headers | tac



来源:https://stackoverflow.com/questions/57294739/kubernetes-display-pods-by-age-in-ascending-order

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!