While some users may prefer to pipe AWS CLI JSON output to jq for parsing, it is possible to leverage the --query functionality that’s built-in.
Commonly, users deal with large JSON outputs when executing AWS CLI commands in their environments. To mitigate the process, JMESPath, a powerful filtering language, can specify resource properties, create lists, search output, etc.
AWS CLI Output
For reference, the AWS CLI documentation lists JSON document outputs. The commands listed below use aws ec2 describe-images, but any combination of the examples can be used for other services and properties.
{"Images":[{"VirtualizationType":"hvm","Description":"Provided by Red Hat, Inc.","PlatformDetails":"Red Hat Enterprise Linux","EnaSupport":true,"Hypervisor":"xen","State":"available","SriovNetSupport":"simple","ImageId":"ami-1234567890EXAMPLE","UsageOperation":"RunInstances:0010","BlockDeviceMappings":[{"DeviceName":"/dev/sda1","Ebs":{"SnapshotId":"snap-111222333444aaabb","DeleteOnTermination":true,"VolumeType":"gp2","VolumeSize":10,"Encrypted":false}}],"Architecture":"x86_64","ImageLocation":"123456789012/RHEL-8.0.0_HVM-20190618-x86_64-1-Hourly2-GP2","RootDeviceType":"ebs","OwnerId":"123456789012","RootDeviceName":"/dev/sda1","CreationDate":"2019-05-10T13:17:12.000Z","Public":true,"ImageType":"machine","Name":"RHEL-8.0.0_HVM-20190618-x86_64-1-Hourly2-GP2"}]}
Please note Images is a top-level list-type element in the JSON document.
Examples
Warning: The AWS describe-images commands outputs a large JSON document. The JMESPath list slicing (Images[:3]) feature is leveraged to truncate the results. If the full output is desired, use Images[] instead.
Listing Outputs
List the ImageId of the first 3 images owned by Amazon:
Note:Images[:3].ImageId outputs the property into a single list. If a list for each image is desired, use Images[:3].[ImageId]. As shown in the next example, it’s useful for listing multiple properties.
List the ImageId and OwnerId of the first 3 images owned by Amazon:
List the Id and CreationDate of the first 3 images that are owned by Amazon whose PlatformDetails contain the string ‘Linux’ in sorted order by CreationDate:
Step #1: Use the contains function and grab the first 3 results:
There is not a top-level key present. In this case, the character @ is used to represent the list that is being passed. Additionally, the key that is being sorted on must begin with an &.
After the sort_by function, the list is “retrieved” [] and the result is formatted to a customized JSON output.