The kubectl jsonpath has a built-in ‘range’ directive that allows you to iterate lists, and then extract elements from each list item.
For example, if you wanted a list of all the pod names and their namespace in CSV format, you could use the following:
# pods and their namespace with just kubectl kubectl get pods -A -o=jsonpath="{range .items[*]}{.metadata.namespace},{.metadata.name}{'\n'}{end}"
This output could then be used to drive a BASH script that performs an operation on each object. The example below does a ‘get’ of each pod.
pod_dump_csv=$(kubectl get pods -A -o=jsonpath="{range .items[*]}{.metadata.namespace},{.metadata.name}{'\n'}{end}") IFS=$'\n' for line in $pod_dump_csv; do ns_field=$(echo $line | awk -F, {'print $1'}) pod_field=$(echo $line | awk -F, {'print $2'}) kubectl get pod $pod_field --namespace $ns_field done
REFERENCES
kubernetes.io, jsonpath support
navicore, gist on using jsonpath range
stackexchange, jq output csv manually without @csv
NOTES
Same output as jsonpath command above, but using jq for formatting
kubectl get pods -A -o=json | jq ".items[].metadata | [.namespace,.name] | @csv" -r | tr -d '"'
jsonpath to select where specific array item
kubectl get service $service_name -n $service_ns -o=jsonpath='{.spec.ports[?(@.name=="http-web")].port}'