获取不是 运行 的 Kubernetes pods 的数量

Get count of Kubernetes pods that aren't running

我用这个命令列出 Kubernetes pods 不是 运行:

sudo kubectl get pods -n my-name-space | grep -v Running

是否有命令可以 return 计数 pods 而不是 运行?

如果您将 ... | wc -l 添加到该命令的末尾,它将打印 grep 命令输出的行数。这可能会包括标题行,但您可以取消它。

kubectl get pods -n my-name-space --no-headers \
  | grep -v Running \
  | wc -l

如果您有像 jq 这样的 JSON-processing 工具可用,您可以获得更可靠的输出(如果 Evicted pod,grep 调用将得到不正确的答案其名称中恰好有字符串 Running)。你应该能够做类似的事情(未经测试)

kubectl get pods -n my-namespace -o json \
  | jq '.items | map(select(.status.phase != "Running")) | length'

如果你要做很多这样的事情,使用 Kubernetes API 编写一个 non-shell 程序会更健壮;您通常可以使用 SDK 调用执行 "get pods" 之类的操作,并取回您可以过滤的 pod objects 列表。

无需任何外部工具即可完成:

kubectl get po \
  --field-selector=status.phase!=Running \
  -o go-template='{{len .items}}'
  • 过滤是通过 field-selectors
  • 完成的
  • 使用 go-template 进行计数:{{ len .items }}