Get fancy CLI output

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

  1. To extract just the hostname field from each machine, use:

    maas machines read | jq '.[].hostname'
    

    jq iterates through the array of machines (.[]) and selects the hostname key from each.

  2. 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

  1. 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.

  2. 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

  1. 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
    
  2. 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

  1. Sort by piping to sort:

    ... | sort -k 1 
    
  2. 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.

This topic was automatically closed 365 days after the last reply. New replies are no longer allowed.