9

In OpenShift, is there a more elegant way of obtaining the name of the most recently created pod in application my_app than this one?

name=$(oc get pods -l app=my_app -o=jsonpath='{range.items[*]}{.status.startTime}{"\t"}{.metadata.name}{"\n"}{end}' | sort -r | head -1 | awk '{print $2}')

The idea is to sort by .status.startTime and to output one .metadata.name. So far, I have not been successful in using oc get with both options --sort-by and -o jsonpath at the same time, so I have fallen back to Unix pipes in this version.

I am using OpenShift v3.9. I am also tagging this question for Kubernetes because it presumably applies to kubectl (instead of oc) in an analogous manner (without the -l app=my_app).

prisar
  • 3,041
  • 2
  • 26
  • 27
rookie099
  • 2,201
  • 2
  • 26
  • 52
  • 1
    FWIW, you might also want to qualify based on status. ``oc get pods -o jsonpath='{.items[?(@.status.phase=="Running")].metadata.name}'`` That way only shows when pod is actually running and not pods in other states. – Graham Dumpleton Aug 13 '18 at 23:49

2 Answers2

13

Try this:

kubectl get pods --sort-by=.metadata.creationTimestamp -o jsonpath="{.items[0].metadata.name}"
Alexey Yakunin
  • 364
  • 3
  • 3
  • 1
    Thx. Works with `oc` as well. – rookie099 Nov 26 '18 at 10:00
  • 2
    This returns the results in reverse order, how do I get the most recent pod, not the oldest pod? – wheeler Mar 12 '19 at 17:32
  • 10
    You can use jsonpath to get the last element in the result array. Instead of 0, use '-1:' `kubectl get pods --sort-by=.metadata.creationTimestamp -o jsonpath="{.items[-1:].metadata.name}"` – rashfeather Jun 13 '19 at 18:53
4

On Kubernetes front, kubectl get po --sort-by=.status.startTime is supposed to work, except in K8s 1.7: it was fixed for 1.8.

"Kubernetes sort pods by age" also mentions

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

Since Openshift 3.9 (March 2018) is fairly recent, those kubectl commands should work even if the oc one is not fully compatible.

VonC
  • 1,262,500
  • 529
  • 4,410
  • 5,250
  • Yes, but can `kubectl` return only the name of the one pod that it sorts last? For `oc get pods --sort-by=.metadata.creationTimestamp` I get a list of rows with columns `NAME`, `READY`, `STATUS`, `RESTARTS`, `AGE`, sorted by age. – rookie099 Aug 14 '18 at 04:18