kubectl JSONPath 与自定义列速查

常用写法

kubectl get pods -n app -o jsonpath='{.items[*].metadata.name}'
kubectl get pods -n app -o jsonpath='{range .items[*]}{.metadata.name}{"\n"}{end}'
kubectl get pods -n app -o jsonpath='{range .items[*]}{.metadata.name}{"\t"}{.spec.nodeName}{"\n"}{end}'
kubectl get pod app-0 -n app -o jsonpath='{.spec.containers[*].image}'
kubectl get pods -n app -l app=web -o jsonpath='{.items[*].status.podIP}'
kubectl get pods -n app -o custom-columns='NAME:.metadata.name,NODE:.spec.nodeName,IP:.status.podIP'
kubectl get pods -n app -o custom-columns='NAME:.metadata.name,IMAGE:.spec.containers[0].image' --no-headers
kubectl get deploy app -n app -o jsonpath='{.spec.replicas}{" ready="}{.status.readyReplicas}{"\n"}'
kubectl get secret app -n app -o jsonpath='{.data.password}' | base64 --decode
kubectl get svc app -n app -o jsonpath='{.spec.clusterIP}'
kubectl get nodes -o jsonpath='{range .items[*]}{.metadata.name}{"\t"}{.status.addresses[?(@.type=="InternalIP")].address}{"\n"}{end}'
kubectl get events -n app -o jsonpath='{range .items[*]}{.lastTimestamp}{" "}{.reason}{" "}{.message}{"\n"}{end}'
kubectl get pod app-0 -n app -o jsonpath='{.status.conditions[?(@.type=="Ready")].status}'
kubectl get pod app-0 -n app -o jsonpath='{.metadata.labels.app\.kubernetes\.io/name}'
kubectl get pod app-0 -n app -o jsonpath='{.metadata.name} {.status.phase} {.status.podIP}'

场景速查

目的 写法/命令 注意
列表字段 {.items[*].metadata.name} [*] 只用于数组
逐行输出 {range .items[*]}...{"\n"}{end} range 与 end 必须成对
条件过滤 {.items[?(@.status.phase=="Running")].metadata.name} 过滤写在数组上
键名含点 {.metadata.labels.app\.kubernetes\.io/name} 键里的点要转义
多容器镜像 {.spec.containers[*].image} 下标从 0 开始
表格输出 -o custom-columns='NAME:.metadata.name,IP:.status.podIP' 列名与路径用 : 分隔
去表头 --no-headers 便于管道继续处理
复杂 JSON -o json + jq 逻辑复杂时优先用 jq
默认值 {range} 中加条件输出 JSONPath 没有默认值运算符

易错点

相关命令

读完自测

  1. 如何按行输出所有 Pod 名?
  2. 怎样取标签键 app.kubernetes.io/name 的值?
  3. custom-columns 如何去掉表头?
答案
  1. kubectl get pods -o jsonpath='{range .items[*]}{.metadata.name}{"\n"}{end}'
  2. kubectl get pod <pod> -o jsonpath='{.metadata.labels.app\.kubernetes\.io/name}'
  3. 加 --no-headers。