How do I get a single pod name for kuberenetes?

Multi tool use


How do I get a single pod name for kuberenetes?
I'm looking for a command like "gcloud config get-value project" that retrieves a project's name, but for a pod (it can retrieve any pod name that is running). I know you can get multiple pods with "kubectl get pods", but I would just like one pod name as the result.
I'm having to do this all the time:
kubectl get pods # add one of the pod names in next line
kubectl logs -f some-pod-frontend-3931629792-g589c some-app
I'm thinking along the lines of "gcloud config get-value pod". Is there a command to do that correctly?
2 Answers
2
You can use the grep command to filter any output on stdout. So to get pods matching a specified pattern you can use a command like this:
> kubectl get pods --all-namespaces|grep grafana
Output:
monitoring kube-prometheus-grafana-57d5b4d79f-smkz6 2/2 Running 0 1h
To only output the pod name, you can use the awk
command with a parameter of '{print $2}'
, which displays the second column of the previous output:
awk
'{print $2}'
kubectl get pods --all-namespaces|grep grafana|awk '{print $2}'
To only display one line you can use the head
command like so:
head
kubectl get pods --all-namespaces|grep grafana|awk '{print $2}'|head -n 1
Thanks Markus. Is there a way to just output the "kube-prometheus-grafana-57d5b4d79f-smkz6" value?
– sjsc
12 mins ago
sure. see updated answer.
– Markus Dresch
10 mins ago
Okay great! Just one more issue. I have 3 pods running and it's listing all 3 pods. Can I output just one of the pod's name? (Sorry, I'm a complete novice at grep)
– sjsc
7 mins ago
sure :) another command to the rescue: head -n 1. updated answer. or you could provide the full pod name in grep. and there are many more ways to do it, like Diegos answer.
– Markus Dresch
6 mins ago
You're amazing Markus!! Thank you so much!!! :) :)
– sjsc
4 mins ago
There are many ways, a quick search you can find many solutions:
kubectl get pods -o name --no-headers=true
kubectl get pods -o name --no-headers=true
kubectl get pods -o=name --all-namespaces | grep kube-proxy
kubectl get pods -o=name --all-namespaces | grep kube-proxy
kubectl get pods -o go-template --template '{{range .items}}{{.metadata.name}}{{"n"}}{{end}}'
kubectl get pods -o go-template --template '{{range .items}}{{.metadata.name}}{{"n"}}{{end}}'
please take a look to these answers:
How do I get a single pod name for kuberenetes?
Kubernetes list all container id
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
why don't you simply grep the output?
– Markus Dresch
24 mins ago