Unlock the power of the MAAS CLI with
The MAAS CLI emits JSON data, which while information-rich, can become cumbersome to sift through, especially when dealing with lists of machines. The
jq utility emerges as a lifeline, offering robust capabilities for filtering and formatting JSON data directly on the command line.
In this tutorial, we'll journey through essential
jq functionalities—key selection, array manipulation, and interplay with other CLI tools to transform raw MAAS JSON into neat, analysable tabular output.
To focus on the
hostname field for each machine, run the following command:
maas machines read | jq '..hostname'
jq navigates through each machine in the array (.) and picks the
To fetch multiple keys, such as
maas machines read | jq '..hostname, ..status_name'
This will produce output resembling:
[ "vm-1", "Deployed" ] [ "vm-2", "Ready" ]
@tsv filter to transform JSON arrays into tab-separated values:
maas machines read | jq -r '..hostname, ..status_name | @tsv'
-r to output raw text (devoid of quotes).
For better readability, pipe the output to
maas machines read | jq -r '..hostname, ..status_name | @tsv' | column -t
vm-1 Deployed vm-2 Ready
Prepend a literal array to
jq to introduce column headings:
maas machines read | jq -r '["HOSTNAME", "STATUS"], (. | [.hostname, .status_name]) | @tsv' | column -t
Create a separating line between headers and data:
maas machines read | jq -r '["HOSTNAME", "STATUS"] | (., map(length*"-")), (. | [.hostname, .status_name]) | @tsv' | column -t
To sort the output, append
sort -k 1 to the pipeline:
... | sort -k 1
To sieve out machines by their status, use
... | jq 'select(.status_name == "Ready")'
This opens doors for more complex text processing through chaining CLI tools.
This tutorial has armed you with practical skills to exploit
jq for extracting, shaping, and enhancing the JSON output from the MAAS CLI. By coupling
jq with other command-line utilities, you gain a potent toolkit for dissecting and analysing API outputs.