Guidelines

This site is for tech Q&A. Please keep your posts focused on the subject at hand.

Ask one question at a time. Don't conflate multiple problems into a single question.

Make sure to include all relevant information in your posts. Try to avoid linking to external sites.

Links to documentation are fine, but in addition you should also quote the relevant parts in your posts.

0 votes
829 views
829 views

I need to check a Unix socket with crictl to see if the service that created the socket is ready. The output in that case looks as follows:

root@host:~ $ crictl -r unix:///var/run/foo/unix.sock info
{
  "status": {
    "conditions": [
      {
        "type": "RuntimeReady",
        "status": true,
        "reason": "",
        "message": ""
      },
      {
        "type": "NetworkReady",
        "status": true,
        "reason": "",
        "message": ""
      }
    ]
  }
}

Basically, I need to check if all status fields in the array conditions in the JSON output have the value true.

I can use jq to get the content of the array:

crictl -r unix:///var/run/foo/unix.sock info | jq -r '.status|.conditions[]'

but how do I check if all status values are true?

in Scripting
by (125)
3 19 33
edit history

Please log in or register to answer this question.

1 Answer

0 votes
 

You can use the map() function to create an array of boolean values indicating which of the nested objects had a property status with the value true (or any other value):

crictl ... | jq -r '.status|.conditions|map(.status==true)'

Output:

[
  true,
  true
]

Use the all function to check if all values in this result array are true (if you want to check if at least one result is true use the any function instead).

crictl ... | jq -r '.status|.conditions|map(.status==true)|all'

That will create the output true or false, depending on whether or not all of the values in the array were true. Run jq with the additional parameter -e to have the program exit with 0 or 1 for a result true or false respectively.

crictl ... | jq -re '.status|.conditions|map(.status==true)|all'

An alternative to the above would be to get the values of the status fields as an array, and then pass that array to the all function:

crictl ... | jq -re '[.status|.conditions[]|.status]|all'

However, that will only work if the values of the fields already are booleans. It will not work if the values have a different type and you need to check for a particular value (e.g. the string "foo"). The first approach is more generic.

by (125)
3 19 33
edit history
...