I have a problem with JQ where I can’t get the correct fields. I have don’t so many tutorials but can’t seem to get this. I am trying to get only the "cpu" for the "mysql" container, but I keep getting both "sidecar, and mysql". Honestly I think it is my misunderstanding of JQ so please feel free to point out what I am misunderstanding.
I keep getting the following but should ONLY see "2100m":
null
2100m
jq -r –arg _NAME "mysql-innodb-cluster-0" #Only get the container with this specific name
‘.items[] #Work on all items
| select(.metadata.name == $_NAME ) #Work on the container that has this name
| .spec.containers #Get the specific key, which will be an object here.
select(.[].name=="sidecar" | not ) #Now that you have the Container Array only use the one that IS NOT named "sidecar"
| .[].resources.limits.cpu ‘ #you now have the MySQL container get ONLY it’s "cpu" value.
Command I use:
jq -r --arg _NAME "mysql-innodb-cluster-0" '.items[] | select(.metadata.name == $_NAME ) | .spec.containers | select(.[].name=="sidecar" | not ) | .[].resources.limits.cpu ' --raw-output /tmp/test.json
test.json
{
"apiVersion": "v1",
"items": [
{
"apiVersion": "v1",
"kind": "Pod",
"metadata": {
"name": "mysql-innodb-cluster-0"
},
"spec": {
"containers": [
{
"name": "sidecar",
"resources": {}
},
{
"name": "mysql",
"resources": {
"limits": {
"cpu": "2100m",
"memory": "5G"
}
}
}
]
}
}
],
"kind": "List"
}
>Solution :
After you selected the correct name, you’ll need to continue select‘ing on the .spec.containers to find the one with name === "mysql" and then select the .resources.limits.cpu from that object:
.items[] | select(.metadata.name == $_NAME) | (.spec.containers[] | select(.name == "mysql").resources?.limits?.cpu)
Will output:
"2100m"