Sub topic 8
Shaping output with --output, --query, and --filters
Most AWS CLI list and describe commands return more data than you need. Three options control what you see: --output picks the format, --query trims and reshapes the result on your machine, and --filters asks the service to return fewer items in the first place. This chapter assumes you have AWS CLI v2 installed and a working profile (see the chapters on installation and profiles), and that you can read basic JSON.
Where each option acts
The three options act at different points in the request. Keeping that straight prevents most confusion.
--filtersis sent to the service. The service returns only matching items. It is not available on every command, and its syntax differs by service.--queryruns inside the CLI after the response arrives. It works on every command that returns JSON.--outputruns last and formats whatever is left.
Because --query runs after the response arrives, it does not reduce the amount of data transferred or the number of API calls. Use --filters when you want less data from the service. Use --query when you want a different shape.
Output formats
The --output option accepts these values. You can also set a default with output = json in a profile, as in the [default] profile shown earlier in this tutorial, or with the AWS_DEFAULT_OUTPUT environment variable.
| Format | Best for | Notes |
|---|---|---|
| `json` | Scripts and tools such as `jq` | The default. Preserves full structure. |
| `yaml` | Reading nested data | Same structure as JSON, easier to scan. |
| `yaml-stream` | Streaming large results | Emits items as they arrive. |
| `text` | Shell pipelines | Tab-separated values, one line per record. |
| `table` | Quick human reading | Draws a bordered table with headings. |
Run the same command with each format to see the difference:
aws s3api list-buckets --query 'Buckets[].Name' --output textWith text, the result is a single line of bucket names separated by tabs. With json the same query returns an array of strings. Choose text only when the query returns flat values, because nested structures are flattened in ways that are hard to predict.
JMESPath basics for --query
The value of --query is a JMESPath expression. JMESPath is a query language for JSON. You will use a small set of constructs most of the time.
Start with this sample response, shortened from aws ec2 describe-instances:
{
"Reservations": [
{
"Instances": [
{"InstanceId": "i-0aaa", "InstanceType": "t3.micro", "State": {"Name": "running"}},
{"InstanceId": "i-0bbb", "InstanceType": "m5.large", "State": {"Name": "stopped"}}
]
}
]
}| Goal | Expression | Result |
|---|---|---|
| Pick a key | `Reservations` | The whole array |
| Pick a nested key | `Instances[0].State.Name` | One value |
| Project over a list | `Reservations[].Instances[]` | A flat list of all instances |
| Select fields | `Reservations[].Instances[].InstanceId` | A list of IDs |
| Rename and reshape | `Reservations[].Instances[].{Id:InstanceId,Type:InstanceType}` | A list of objects with new keys |
| Filter items | `Reservations[].Instances[?InstanceType=='t3.micro']` | Only matching items |
| Count | `length(Reservations[].Instances[])` | A number |
A few details cause most mistakes:
[]flattens one level of nesting.[*]projects without flattening. If you get nested arrays when you expected a flat list, add[].- Square brackets with a number, such as
[0], pick one element.[-1]picks the last. - A multiselect list such as
[InstanceId,InstanceType]returns arrays, which suitstextandtableoutput. A multiselect hash such as{Id:InstanceId}returns objects with your own key names. - String literals in a filter expression use single quotes:
'running'. Raw literals use backticks only for numbers, booleans, or JSON, for example `true. Wrap the whole expression in single quotes in the shell so the shell does not interpret brackets, backticks, or$`.
On Windows cmd.exe, single quotes do not protect the expression. Use double quotes around the whole expression and escape inner double quotes, or switch to PowerShell or CloudShell, where the examples in this chapter work as written.
Missing values
If a key is absent, JMESPath produces null for it. In text output, null prints as None. If your script compares against an empty string, it will not match. Use the || operator to supply a default, for example Tags[?Key=='Name'].Value | [0] || 'unnamed'.
Server-side filtering with --filters
--filters is a service feature that the CLI passes through. EC2 uses it widely, along with some other services. The syntax uses Name and Values keys:
aws ec2 describe-instances \
--filters "Name=instance-state-name,Values=running" \
--query 'Reservations[].Instances[].{Id:InstanceId,Type:InstanceType}' \
--output tableHere the service returns only running instances, and the query then trims each instance to two fields. Separate multiple values for one filter with commas inside Values, for example Values=running,pending. Multiple values for the same filter match if any one matches (OR). Separate filters, passed as several space-separated arguments, must all match (AND).
aws ec2 describe-instances \
--filters "Name=instance-state-name,Values=running,pending" "Name=instance-type,Values=t3.micro"Valid filter names are defined by each API. Look them up in the command's help with aws ec2 describe-instances help, under the --filters option.
Not every service offers --filters. Some commands have their own narrowing options instead, such as --bucket, --prefix, or --instance-ids. Prefer these where they exist, since they also reduce what the service sends.
Choosing between --filters and --query
| Question | Use |
|---|---|
| Do I want fewer items from the service? | `--filters` or a command-specific option |
| Do I need a field the filters do not support? | `--query` with `[?...]` |
| Do I need to rename or reorder fields? | `--query` |
| Do I need a count or a computed value? | `--query` |
The two combine well. Filter on the server for the broad cut, then use a query for the exact fields and any condition the service cannot express.
Interaction with pagination
For list commands that paginate, the CLI applies --query to each page separately by default when it streams results. When you use --max-items or --page-size, the CLI handles the paging and the query applies to the combined result, so a command such as length(...) counts everything it fetched. If a count looks too small, check whether the command stops after a limited number of items. The chapter on pagination and waiters covers this in more detail.
Common errors
Invalid JMESPath expression: usually an unbalanced bracket, a missing quote, or a shell that stripped your quotes. Test the expression against a saved response with--queryon a simple command.- Empty output or
None: the key name is wrong or its case differs. JMESPath is case-sensitive, and AWS keys start with a capital letter in most APIs. - A column missing from a table:
tableoutput omits fields you did not select. Check the query. - Nested arrays in the result: add
[]to flatten. Unknown optionsafter--filters: the command may not support it. Read its help page.
Practice
Exercise
You want the IDs of only the stopped EC2 instances, printed one per line with no headings. Which combination of options fits, and why do you put the state check in --filters rather than --query?
Show answer
Use aws ec2 describe-instances --filters "Name=instance-state-name,Values=stopped" --query 'Reservations[].Instances[].InstanceId' --output text. To get one ID per line, add | tr '\t' '\n' or select with [] and use --output text per record. The state check goes in --filters because the service then returns only stopped instances, so less data is transferred and processed. A --query check would download every instance first and discard most of them on your machine.
Exercise
A query Reservations[].Instances[].Tags[?Key=='Name'].Value prints a list of empty lists for untagged instances and nested lists for the others. How do you get one plain name per instance, with a fallback for untagged ones?
Show answer
Use Reservations[].Instances[].{Id:InstanceId,Name:(Tags[?Key=='Name'].Value | [0]) || 'unnamed'}. The | [0] pipe takes the first match from each list, which removes the nesting, and || 'unnamed' replaces null with a default.