Filter aws cli Output with the –query Option

30 / Jun / 2014 by Nikhil Kumar Sharma 2 comments

The AWS CLI provides built-in output filtering capabilities with the –query option. To demonstrate how it works, I’ll start with JSON output of aws ec2 describe-volumes

aws ec2 describe-volumes –output json


Suppose we have to print all availability zones,

aws ec2 describe-volumes –query ‘Volumes[*].AvailabilityZone


aws ec2 describe-volumes : Shows descriptive information for one or more of your Amazon EBS volumes in a particular region
–query : to filter output
[] : array
AvailabilityZone : key whose value is ” us-east-1b us-east-1b”

Here * is used to print all values of AvailabilityZone. If we want to print first value of AvailabilityZone or second value of AvailabilityZone than we can replace * by 0 or 1 respectively.

suppose we have to print all the values of Attachments

aws ec2 describe-volumes –query ‘Volumes[*].Attachments’


But, if we only want to print InstanceId

aws ec2 describe-volumes –query ‘Volumes[*].Attachments[*].InstanceId’

Here this query will print all the value of instansce id from the json file
by volume[*] we enter into the array of volumes
and by appending .attachments[*] to volumes[*] we drill down or enter into the attachment array and by appending .instanceid to .attachments we can get the desire values for the instance id. Again we can replace * in Attachments[*] with 0 or 1 to print first instance id or second instance id respectively.
We can also get values of multiple parameters, like if we want to print InstanceId and State of the volume

aws ec2 describe-volumes –query ‘Volumes[*].[Attachments[*].[VolumeId,InstanceId,State]]’


Now if we want to know the availability zone, InstanceId and state of volume

aws ec2 describe-volumes –query ‘Volumes[*].[Attachments[0].VolumeId,AvailabilityZone,Attachments[0].InstanceId,Attachments[0].State]’



comments (2)

  1. Manu

    Help Nikhil,
    I have trying to Tag all my Network Interfaces but I need to tag them according the Tag that the Instaces or ELBs that are attached to each Network Interface.

    Is there a script or way that I tag the NI according to the Tag of the instance or ELB attached to it?
    Any help or advice on what will be the best way to do it from CLI will be appreciated due that I can’t do it manually, I’m having more than 400 NIs


Leave a Reply

Your email address will not be published. Required fields are marked *