How to filter AWS CLI output?

You can use AWS CLI global option –filter and –query to filter AWS CLI outputs. AWS CLI supports both server-side and client-side filtering of the data.

Server-side filtering: If you want to restrict the actual data sent by AWS, you can filter the data on server-side using –filter option. For example, suppose you have two VPCs and you only want to get data from a particular VPC, you need to use server-side filtering.

Client-side filtering: If you want to filter and get a subset of data sent by AWS, you can use client-side filter using –query option. For example, suppose you only want to get the VPC ID and nothing else, you can use –query option to retrieve only VPC id.

Note: You can also combine both server-side (–filter) and client-side (–query) filtering to get the desired data you want.

Note: It’s not mandatory to use –query for client-side filtration, you can use your own custom solution or a third-party tool like jq.

Let us understand how to filter AWS CLI output with some examples.

Get details on all your VPC in a specific AWS region without any filters:

Now, what if you only want details on one particular VPC, say the VPC having CIDR block 172.31.0.0/16. Using –filter you can filter and get the details for a particular resource. AWS will send data for that particular resource that is present in your –filter.

On the other end, if you want to get a subset of data, you can use –query option. For example, say you only want to retrieve the vpc id, then using –query you can fetch only the vpc id.

If you are querying a list of data, you need to put a square bracket [] and the end of the list elements and each child element of a parent element can be accessed using a dot (.). For example, suppose you want to get a leaf level element say “State” from the VPC description, you need to traverse from the top-level parent and down to each child level parent using a dot.

You can also filter or query AWS CLI based on some conditions. For example, say you want to list the vpc id of the default vpc in your AWS region. You can put a condition in your query parameter that checks if the vpc is the default vpc.

AWS CLI also supports sorting of the output using sort_by() function.

You can also customize the output of AWS CLI and add a new element.

Leave a Reply