Wednesday, January 30, 2019

How to Use JQ to Filter Live K8S Event Output

Requirement:

    Per other node ,we can watch live K8S core API output. The output is Json format. It has lots of information.It is abit hard to find useful information from such big volume output. This note is to address that we can use jq ( an excellent Json tool) to filter the live output and get useful , meaningful information we are looking for. More jq details are on jq cookbook

Solution:

   Please refer my other node to prepare the kubectl proxy and curl. So we can use curl to get K8S Core API event output.  The default K8S output is not nicely formatted JSON. To get proper ,pretty-print output on the screen. Below are a few examples how to use JQ for that.

Example 1:
 Display all output without filtering.
(curl  -sN http://127.0.0.1:8080/api/v1/nodes?watch=true) | while read -r watchoutput;do echo "$watchoutput" | jq '.'; done

Example 2:
To get all labels of nodes via filter
(curl -sN http://127.0.0.1:8080/api/v1/nodes?watch=true) | while read -r watchoutput;do echo "$watchoutput" | jq '. | {labels: .object.metadata.labels}'; done

Example 3:
To get conditions (disk pressure, memory pressure...) of nodes via filter
(curl -sN http://127.0.0.1:8080/api/v1/nodes?watch=true) | while read -r watchoutput;do echo "$watchoutput" | jq '. | {conditions: .object.status.conditions}'; done

Example 4:
To get node name from Core API via curl
curl -sN http://127.0.0.1:8080/api/v1/nodes | jq '.items[].metadata.name'

Example 5:
Use select and contain functions of jq to find out what K8S roles of  a person named "john" has
kubectl get clusterrolebindings -o json|jq '.items[] | select(.subjects != null) | select (.subjects[].name| contains("john")).metadata.name'

No comments:

Post a Comment