How to tell jq to print the content of two keys for each instance returned by aws ec2 cli
Solution 1:
Here is an approach using some sample code and data from my answer to a similar question on Stack Overflow.
To choose multiple fields you can use Object Construction. E.g this filter makes an object containing just PublicDnsName
and VpcId
from each instance:
.Reservations[]
| .Instances[]
| {PublicDnsName, VpcId}
If this filter is in filter.jq
and the sample data from that other answer is in data.json
then running
$ jq -M -f filter.jq data.json
produces
{
"PublicDnsName": "xxxxxxxx",
"VpcId": "vpc-eb09eb8e"
}
Once you have objects containing what you want getting the data into another format (e.g. csv) is easy. With this filter
.Reservations[]
| .Instances[]
| {PublicDnsName, VpcId}
| [.[]]
| @csv
and the -r
option
$ jq -M -r -f filter.jq data.json
jq produces
"xxxxxxxx","vpc-eb09eb8e"
To add a filtering condition, e.g. VpcId is not null, add a select.
.Reservations[]
| .Instances[]
| {PublicDnsName, VpcId}
| select(.VpcId != null)
| [.[]]
| @csv