【问题标题】:How do I get a single pod name for kubernetes?如何获得 Kubernetes 的单个 pod 名称?
【发布时间】:2019-01-07 18:15:35
【问题描述】:

我正在寻找像“gcloud config get-value project”这样的命令来检索项目的名称,但是对于一个 pod(它可以检索任何正在运行的 pod 名称)。我知道您可以使用“kubectl get pods”获取多个 pod,但我只想要一个 pod 名称作为结果。

我不得不一直这样做:

kubectl get pods       # add one of the pod names in next line
kubectl logs -f some-pod-frontend-3931629792-g589c some-app 

我的思路是“gcloud config get-value pod”。有正确的命令吗?

【问题讨论】:

  • 你为什么不简单地 grep 输出?

标签: kubernetes google-kubernetes-engine


【解决方案1】:

方法有很多,快速搜索一下就可以找到很多解决方案:

kubectl get pods -o name --no-headers=true

kubectl get pods -o=name --all-namespaces | grep kube-proxy

kubectl get pods -o go-template --template '{{range .items}}{{.metadata.name}}{{"\n"}}{{end}}'

请查看以下链接:

kubernetes list all running pods name

Kubernetes list all container id

https://kubernetes.io/docs/tasks/access-application-cluster/list-all-running-container-images/

【讨论】:

  • 你链接到这个问题
【解决方案2】:

您可以使用 grep 命令过滤标准输出上的任何输出。因此,要获取匹配指定模式的 pod,您可以使用如下命令:

> kubectl get pods --all-namespaces|grep grafana

输出:

monitoring      kube-prometheus-grafana-57d5b4d79f-smkz6               2/2       Running   0          1h

要只输出pod名称,可以使用awk命令,参数为'{print $2}',显示上一个输出的第二列:

kubectl get pods --all-namespaces|grep grafana|awk '{print $2}'

要只显示一行,您可以像这样使用head 命令:

kubectl get pods --all-namespaces|grep grafana|awk '{print $2}'|head -n 1

【讨论】:

  • 谢谢马库斯。有没有办法只输出“kube-prometheus-grafana-57d5b4d79f-smkz6”值?
  • 好的,太好了!只是多了一个问题。我有 3 个 pod 正在运行,它列出了所有 3 个 pod。我可以只输出一个 pod 的名称吗? (对不起,我是 grep 的新手)
  • sure :) 另一个救援命令:head -n 1. 更新答案。或者您可以在 grep 中提供完整的 pod 名称。还有更多方法可以做到这一点,比如 Diegos 的回答。
  • 在 Windows 上,使用 findstr 代替 grep
【解决方案3】:
  • 这将输出最后一个 pod 名称: kubectl get pods -o go-template --template ' {{range .items}}{{.metadata.name}}{{"\n"}}{{end}}' | awk '{print $1}' | tail -n 1

  • 如果您想获取 pod 的日志: kubectl logs -fkubectl get pods -o go-template --template ' {{range .items}}{{.metadata.name}}{{"\n"}}{{end}}' | awk '{print $1}' | tail -n 1

只需用单引号运行命令即可。

链接:

  1. kubernetes list all running pods name
  2. https://kubernetes.io/docs/tasks/access-application-cluster/list-all-running-container-images/

希望这会有所帮助!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-05-24
    • 2022-08-23
    • 2021-12-09
    • 2019-02-06
    • 2017-07-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多