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 没有默认值运算符 |
易错点
- 错误:表达式不加引号,
* 被 shell 当成通配符;正确:整个表达式用单引号包住。
- 错误:用
{.items[*].metadata.name} 直接拼多行;正确:用 {range} 加 {"\n"} 控制分隔。
- 错误:对 map 使用
[*];正确:[*] 只遍历数组,map 直接写键名。
- 错误:写
{.metadata.labels.app.kubernetes.io/name};正确:键中的点要转义为 app\.kubernetes\.io/name。
- 错误:取不到字段就怀疑语法;正确:先
-o yaml 确认字段路径、大小写和层级。
- 错误:数组越界写
{.spec.containers[1].image};正确:先确认容器数量,或用 [*]。
- 错误:把 jsonpath 输出当 JSON 再解析;正确:需要 JSON 时用
-o json。
- 错误:自定义列表达式里混入空格;正确:列定义不要留空格,整段加引号。
相关命令
读完自测
- 如何按行输出所有 Pod 名?
- 怎样取标签键
app.kubernetes.io/name 的值?
custom-columns 如何去掉表头?
答案
kubectl get pods -o jsonpath='{range .items[*]}{.metadata.name}{"\n"}{end}'
kubectl get pod <pod> -o jsonpath='{.metadata.labels.app\.kubernetes\.io/name}'
- 加
--no-headers。