OE:
JSONPATH TIP
I don’t remember if I shared this or not (the search history only goes back a few days). So I’ll repost it
Say we want to list all OS images used by our nodes. Here are two ways we can tackle this challenge:
METHOD 1
we can use the trick mentioned here to flatten our JSON document and quickly search for paths: https://kubernetes.io/docs/reference/kubectl/cheatsheet/#viewing-finding-resources
so we would do the following:
$ sudo apt install jq
we’ll then use the trick mentioned here https://kubernetes.io/docs/reference/kubectl/cheatsheet/#viewing-finding-resources to flatten the document:
$ kubectl get nodes -o json | jq -c 'path(..)|[.[]|tostring]|join(".")' | grep -i osImage
"items.0.metadata.managedFields.4.fieldsV1.f:status.f:nodeInfo.f:osImage"
"items.0.status.nodeInfo.osImage"
"items.1.metadata.managedFields.4.fieldsV1.f:status.f:nodeInfo.f:osImage"
"items.1.status.nodeInfo.osImage"
"items.2.metadata.managedFields.4.fieldsV1.f:status.f:nodeInfo.f:osImage"
"items.2.status.nodeInfo.osImage"
"items.3.metadata.managedFields.4.fieldsV1.f:status.f:nodeInfo.f:osImage"
"items.3.status.nodeInfo.osImage"
we can further clean this up by removing the managedFields section:
$ kubectl get nodes -o json | jq -c 'path(..)|[.[]|tostring]|join(".")' | grep -i osImage | grep -v managedFields
"items.0.status.nodeInfo.osImage"
"items.1.status.nodeInfo.osImage"
"items.2.status.nodeInfo.osImage"
"items.3.status.nodeInfo.osImage"
so we can now easily write our query as follows:
$ kubectl get nodes -o jsonpath='{.items[*].status.nodeInfo.osImage}'
or if we wanted it in columnar format:
$ kubectl get nodes -o custom-columns=OS_IMAGE:.status.nodeInfo.osImage
OS_IMAGE
Ubuntu 18.04.5 LTS
Ubuntu 18.04.5 LTS
Ubuntu 18.04.5 LTS
Ubuntu 18.04.5 LTS
NOTE the above works in most cases but not all
METHOD 2 - VIM
here is a slightly longer method using Vim
$ kubectl get nodes -o json > /tmp/nodes.json
$ vim /tmp/nodes.json
we see a lot of output (over 2000 lines). Let us get to work:
:set ruler
:set foldmethod=syntax
this 2nd command folds our input into a single line
we then search for osImage. This opens only the paths that lead to osImages. Again, we ignore the managedFields section and look for the next hit. We see something like this (image1)
we split the screen and start writing the path:
status.nodeInfo.osImage
but we still need to build the rest of the path (before status). We can do this by looking at the bottom right and finding the column # (13)
:set colorcolumn=13
this adds a vertical ruler we can then use as we move up in our document to build the rest of our path (image 2). We move up and find that status is a child of items and we can now build our full query as we did in METHOD 1