1

In my namespace, I have several pods named with the same prefix, followed by the random string. There are also other pods, named differently. The result of kubectl get pods would look something like this:

service-job-12345abc
service-job-abc54321
other-job-54321cba

I need to find the nameof the most recently created pod starting with "service-job-".

I found this thread, which helps getting the name of the most recent pod in general. This one gets me the complete names of pods starting with a specific prefix.

What I struggle with is combining these two methods. With each one, I seem to lose the information I need to perform the other one.

Note: I am not an administrator of the cluster, so I cannot change anything about the naming etc. of the pods. The pods could also be in any possible state.

CloudWatcher
  • 181
  • 1
  • 11

1 Answers1

1

This works as you expect:

kubectl get pods --sort-by=.metadata.creationTimestamp --template '{{range .items}}{{.metadata.name}}{{"\n"}}{{end}}' | grep service-job- | head -1 
Amila Senadheera
  • 12,229
  • 15
  • 27
  • 43
  • For some reason templates always throw errors for me, and I failed to mention that I am forced to work with Powershell. However, the sorting and selecting does work as expected, so I am accepting this answer as correct. My tweaked version that works for me is this: `kubectl get pods --sort-by=.metadata.creationTimestamp --no-headers -o custom-columns=":metadata.name" | select-string service-job- | Select-Object -Last 1` – CloudWatcher Feb 08 '23 at 13:27