如何根据过滤器在kubernetes中获取前N个最新创建的pods

how to get top N latest created pods inside kubernetes based on filter

在 Kubernetes 中(使用过滤器)我们可以限制 k8s 在有趣资源上的输出,我想知道是否可以仅使用过滤器列出最近创建的前 5 个 pods。

当前示例主要列出所有 pods 并通过管道传输到另一个 unix(head 命令)

kubectl get pods --sort-by=.metadata.creationTimestamp | head -n 5

但我想首先从服务器端获取所有内容需要很长时间,然后列出前 5 个。

我可以使用特殊的过滤器来提高效率吗?

有几个方面阻止您仅使用 filter:

来解决这个问题
  1. Filter本身:

    Field selectors are essentially resource filters. By default, no selectors/filters are applied, meaning that all resources of the specified type are selected. This makes the kubectl queries kubectl get pods and kubectl get pods --field-selector "" equivalent.

    Reference - Field selectors.

    及其对supported operations的限制:

    You can use the =, ==, and != operators with field selectors (= and == mean the same thing). This kubectl command, for example, selects all Kubernetes Services that aren't in the default namespace:

    kubectl get services --all-namespaces --field-selector metadata.namespace!=default

    它无法比较 >< 之类的值,即使总计 pods 的数量是可用的。

  2. 我将请求与 --v=8 进行了比较,以查看在使用不同选项执行 kubectl get pods 时执行了哪个确切响应:

    $ kubectl get pods -A --sort-by=.metadata.creationTimestamp --v=8
    I1007 12:40:45.296727     562 round_trippers.go:432] GET https://10.186.0.2:6443/api/v1/pods?includeObject=Object
    

    $ kubectl get pods -A --field-selector=metadata.namespace=kube-system --v=8
    I1007 12:41:42.873609    1067 round_trippers.go:432] GET https://10.186.0.2:6443/api/v1/pods?fieldSelector=metadata.namespace%3Dkube-system&limit=500
    

    使用 --field-selector kubectl 时的不同之处在于它向请求添加了 &limit=500,因此如果从终端使用 kubectl 可能会出现一些数据不一致的地方.而 --sort-byapi server 获取所有数据到客户端。

  3. 使用 -o jsonpath 的工作方式与常规 kubectl get pods 请求相同,并且再次有 500 个结果的限制,这可能会导致数据不一致:

    $ kubectl get pods -A --v=7 -o jsonpath='{range.items[*]}{.metadata.creationTimestamp}{"\t"}{.metadata.name}{"\n"}{end}'
    I1007 12:52:25.505109    6943 round_trippers.go:432] GET https://10.186.0.2:6443/api/v1/pods?limit=500
    

    甚至开发人员也使用另一个 linux 命令(jqgrepsort|)来处理从中获得的初始结果库伯内特 api。参见 examples of Viewing, finding resources

因此要确认 ,您需要先将数据提供给客户端,然后再对其进行处理。