Get name of most recently created pod
Asked Answered
C

2

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

Cuddy answered 13/8, 2018 at 19:38 Comment(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.Rooted
L
15

Try this:

kubectl get pods --sort-by=.metadata.creationTimestamp -o jsonpath="{.items[0].metadata.name}"
Liv answered 13/11, 2018 at 11:56 Comment(3)
Thx. Works with oc as well.Cuddy
This returns the results in reverse order, how do I get the most recent pod, not the oldest pod?Puduns
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}"Highpowered
B
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.

Bodoni answered 13/8, 2018 at 21:13 Comment(1)
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.Cuddy

© 2022 - 2024 — McMap. All rights reserved.