【问题标题】:How to get the pods from the namespaces with a particular label?如何从具有特定标签的命名空间中获取 pod?
【发布时间】:2020-02-27 16:02:29
【问题描述】:

可以获取集群上的所有pod:

kubectl get pod --all-namespaces -o wide

也可以通过特定标签获取集群上的所有 pod:

kubectl get pod --all-namespaces -o wide --selector some.specific.pod.label

甚至可以获取集群特定节点上的所有 pod:

kubectl get pods --all-namespaces -o wide --field-selector spec.nodeName=<node>

问题是,如何从具有特定标签的命名空间中获取所有 pod?

例如kubectl get pod --namespace-label some.specific.namespace.label -o wide(伪代码)

【问题讨论】:

    标签: kubernetes kubectl kubernetes-pod


    【解决方案1】:

    不能一次性完成该操作,因为Namespace 对象上的标签不会向下传播到其子对象。由于kubectl 只是在/api/v1/whatevers 上执行GET,因此没有明显的方法可以同时向两个端点发出 REST 请求并将它们连接在一起。

    您需要在 shell 中使用 for 循环,或者使用许多 API 客户端绑定之一来创建执行 Namespace 提取的程序,然后为匹配 Namespaces 的那些进行 Pod 提取;例如:

    for n in $(kubectl get ns --selector some.specific.namespace.label -o name); do
        # it's possible kubectl -n will accept the "namespace/foo" output of -o name
        # or one can even -o go-template='{{ range .items }}{{ .metadata.name }} {{ end }}'
        n=${n##namespace/}
        kubectl -n "$n" get pods -o wide
    done
    

    【讨论】:

    • 我编辑了您的答案,因为上面有错误。从 n=${##namespace/} 更改为 n=${n##namespace/}。我在我的集​​群上进行了测试,现在它按预期工作。很好的解决方案!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-05-16
    • 2020-12-14
    • 2018-02-13
    • 2020-01-24
    • 2017-12-11
    • 1970-01-01
    • 2014-05-10
    相关资源
    最近更新 更多