废话少说今天偶然使用到 jsonpath 感觉还是很好玩的,所以诞生了这篇文章。主要分为两部分,1 为语法 2 为示例。
语法在这里 https://kubernetes.io/docs/reference/kubectl/jsonpath/
,我太懒了只截了图以及示例的 json 数据,不感兴趣的同学可以直接看关于 jsonpath 的使用。
{
"kind": "List",
"items":[
{
"kind":"None",
"metadata":{"name":"127.0.0.1"},
"status":{
"capacity":{"cpu":"4"},
"addresses":[{"type": "LegacyHostIP", "address":"127.0.0.1"}]
}
},
{
"kind":"None",
"metadata":{"name":"127.0.0.2"},
"status":{
"capacity":{"cpu":"8"},
"addresses":[
{"type": "LegacyHostIP", "address":"127.0.0.2"},
{"type": "another", "address":"127.0.0.3"}
]
}
}
],
"users":[
{
"name": "myself",
"user": {}
},
{
"name": "e2e",
"user": {"username": "admin", "password": "secret"}
}
]
}
先贴出来示例代码,k8s 的一个 svc
[root@node4 ~]# kubectl get svc kube-dns -n kube-system -o json
{
"apiVersion": "v1",
"kind": "Service",
"metadata": {
"annotations": {
"prometheus.io/port": "9153",
"prometheus.io/scrape": "true"
},
"creationTimestamp": "2020-02-24T07:58:00Z",
"labels": {
"k8s-app": "kube-dns",
"kubernetes.io/cluster-service": "true",
"kubernetes.io/name": "KubeDNS"
},
"name": "kube-dns",
"namespace": "kube-system",
"resourceVersion": "228",
"selfLink": "/api/v1/namespaces/kube-system/services/kube-dns",
"uid": "baf34b62-0fb7-4b91-84e8-fcc1d60d72ff"
},
"spec": {
"clusterIP": "10.96.0.10",
"ports": [
{
"name": "dns",
"port": 53,
"protocol": "UDP",
"targetPort": 53
},
{
"name": "dns-tcp",
"port": 53,
"protocol": "TCP",
"targetPort": 53
},
{
"name": "metrics",
"port": 9153,
"protocol": "TCP",
"targetPort": 9153
}
],
"selector": {
"k8s-app": "kube-dns"
},
"sessionAffinity": "None",
"type": "ClusterIP"
},
"status": {
"loadBalancer": {}
}
}
获取一些有意义的东西
1:获取所有的 ports
[root@node4 ~]# kubectl get svc kube-dns -n kube-system -o jsonpath='{$.spec.ports}'
[
map[
name:dns
port:53
protocol:UDP
targetPort:53
]
map[
name:dns-tcp
port:53
protocol:TCP
targetPort:53
]
map[
name:metrics
port:9153
protocol:TCP
targetPort:9153
]
]
2:获取 ports 中 name 是 metrics 的 port,这就类似于写正则了
[root@node4 ~]# kubectl get svc kube-dns -n kube-system -o jsonpath='{$.spec.ports[?(@.name=="metrics")].port}'
9153
或者获取 ports 中所有 protocol 是 TCP 的 name
[root@node4 ~]# kubectl get svc kube-dns -n kube-system -o jsonpath='{$.spec.ports[?(@.protocol=="TCP")].name}'
dns-tcp metrics
@ 符号代表当前对象,?() 原文是 filter 理解为过滤,() 中写条件。
3:获取 spec 中的 clusterIp
写到这里,我感觉已经没有难的地方了。
[root@node4 ~]# kubectl get svc kube-dns -n kube-system -o jsonpath='{$.spec.clusterIP}'
10.96.0.10
本来想获取一下 loadBalancer 中的数据,结果刚看到我的 loadBalancer 是空的,所以没办法获取数据了,就这样结束吧。