7

running aws ec2 describe-instances will return a json text similar to the following:

{
    "Reservations": [
        {
            "Instances": [
                  "PublicDnsName": "ec2..."
                    "VpcId": "vpc-...",
                        ...
            "Instances": [

I know for each "Instance" I can extract the contents of a single field, for example PublicDnsName, using jq as follows: jq '.Reservations[].Instances[].PublicDnsName' which will list the dns names for my instances But how do I extract two or more fields and separate them by a space or comma or something? I want PublicDnsName and VpcId to be listed side-by-side for each Instance.

Specifically what I'm looking for is a list of instances where VpcId is null, undefined, or non-existent. In other words I'd like a list of my Classic instances and I need this through api so I can process the results.

Michael Martinez
  • 2,543
  • 3
  • 20
  • 31

1 Answers1

9

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
jq170727
  • 226
  • 2
  • 3
  • Just FYI for folks like me who are less jq-expert than jq17027: the filter can be in the command line and does not have to be in a file. – Jeff Learman Nov 04 '21 at 13:25