kubernetes kubectl json path - ghdrako/doc_snipets GitHub Wiki

kubectl does not allow regular expressions using JSONPath. The simplest solution is to use jq instead to be able to parse the JSON output using regular expressions.

kubectl get pods -o json
.items[].metadata.name  
kubectl get pods -o=jsonpath='{.items[?(@.metadata.labels.name=="web")].metadata.name}'
kubectl get pods -o=jsonpath='{range .items[*]}{.metadata.name}{"\t"}{.status.startTime}{"\n"}{end}'
kubectl get pods -l name=web -o=jsonpath='{.items..metadata.name}'
kubectl get pods -o=jsonpath="{.items[*]['metadata.name', 'status.capacity']}"
kubectl get statefulset -n namespace -o=jsonpath='{$.spec.template.spec.containers[*].image}'
Function Description Example Result
text the plain text kind is {.kind} kind is List
@ the current object {@} the same as input
. or [] child operator {.kind}, {['kind']} or {['name.type']} List
.. recursive descent {..name} 127.0.0.1 127.0.0.2 myself e2e
* wildcard. Get all objects {.items[*].metadata.name} [127.0.0.1 127.0.0.2]
[start:end:step] subscript operator {.users[0].name} myself
[,] union operator {.items[*]['metadata.name', 'status.capacity']} 127.0.0.1 127.0.0.2 map[cpu:4] map[cpu:8]
?() filter {.users[?(@.name=="e2e")].user.password} secret
range, end iterate list {range .items[*]}[{.metadata.name}, {.status.capacity}] {end} [127.0.0.1, map[cpu:4]] [127.0.0.2, map[cpu:8]]
'' quote interpreted string {range .items[*]}{.metadata.name}{'\t'}{end} 127.0.0.1 127.0.0.2
\ escape termination character {.items[0].metadata.labels.kubernetes.io/hostname} 127.0.0.1

Use jq

kubectl get pods -o json | jq -r '.items[] | [filter] | [formatted result]' | jq -s '.'
kubectl get pods -o json | \ 
 jq '[.items[].spec.containers[].image | select(. | startswith("random.domain.com") | not )] | unique'



kc get pods -n acp -o=json | jq -r '.items[] | {pod: .metadata.name, containers: [.spec.containers[] | {name: .name, cpu: .resources.requests.cpu}]}'