The MAAS CLI outputs JSON data that can be verbose and difficult to parse, especially when listing multiple machines. The jq
utility provides powerful filtering and formatting of JSON on the command line.
In this tutorial, you’ll learn how to transform raw MAAS JSON into clean, tabular output for analysis. We’ll cover jq basics like selecting keys, manipulating arrays, and chaining with other CLI tools.
Selecting keys
-
To extract just the
hostname
field from each machine, use:maas machines read | jq '.[].hostname'
jq
iterates through the array of machines (.[]) and selects thehostname
key from each. -
You can retrieve multiple keys like this:
maas machines read | jq '.[].hostname, .[].status_name'
Which gives output like:
[ "vm-1", "Deployed" ] [ "vm-2", "Ready" ]
Tabular output with @tsv
-
The
@tsv
filter converts JSON arrays into tab-separated values:maas machines read | jq -r '.[].hostname, .[].status_name | @tsv'
The
-r
option gives raw output without quotes. -
Pipe to
column -t
for aligned columns:maas machines read | jq -r '.[].hostname, .[].status_name | @tsv' | column -t
vm-1 Deployed vm-2 Ready
Adding headings
-
Pass a literal array to
jq
for headings:maas machines read | jq -r '["HOSTNAME", "STATUS"], (.[] | [.hostname, .status_name]) | @tsv' | column -t
HOSTNAME STATUS vm-1 Deployed vm-2 Ready
-
And generate a divider row with:
maas machines read | jq -r '["HOSTNAME", "STATUS"] | (.[], map(length*"-")), (.[] | [.hostname, .status_name]) | @tsv' | column -t
HOSTNAME STATUS ------- -------- vm-1 Deployed vm-2 Ready
Sorting and piping
-
Sort by piping to
sort
:... | sort -k 1
-
Filter by status with
select()
:... | jq 'select(.status_name == "Ready")'
Chaining CLI tools enables all kinds of text processing.
Summary
In this tutorial we’ve covered using jq
to filter, format, and transform JSON output from the MAAS CLI into clean tabular data. Combining jq
with other CLI utilities provides a powerful way to slice and dice API output.