1

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.

  • I think this is a question for Stack Overflow. – Tim Oct 4 '16 at 18:55
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
|improve this answer|||||

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.