jq/yq Cheat Sheet
Summary of some jq use cases and caveats daily.
Quick reference:
Need to read through some common use cases:
yq is another open source tool relies on jq to query yaml file, tt has most common operations available and syntactically like jq.
- Must quote the expression For example:
1 | # -r: raw string |
- Filter out null value
For example, I want to get the configMap name from a deployment, the volumes may have multiple subitems and one of them is config map, we need to filter out
null:
1 | kubectl get deploy nwiaas -o json | jq -r '.spec.template.spec.volumes[].configMap.name | select(. != null)' |
This is a simple case to introduce select function
- Replace field values
Using
|=operator, see here.
For example, I want to create one job from cronjob but with different args:
1 | # --dry-run=client: print without sending object |
Here I use cat at end to remove color supplement, otherwise kubectl apply will fail.
- Loop and extract specified values For example, the Elasticsearch API returns a list of map object and each map has the same number of fields, I want to extract few of the fields and output with specific format.
1 | # [.index,.shard,.prirep,.node]: generate [] array format and put items in |
It will output csv style string, for example:
1 | "xxx","yyy","zzz","qqq" |
Or format as a table:
1 | # [.index,.shard,.prirep,.node]: generate an array |
The output is like:
1 | .ds-k8s-nodes-filebeat-2022.04.28-000020 | 0 | p | 172.16.0.172 |