Using jq to parse AWS CLI json output

I would like to use jq ( http://stedolan.imtqy.com/jq/ ) to parse the json output from aws elb describe-load-balancers and return the name and AZ only where AvailabilityZones contains a specific value.

Here is a partial edited json representing the original output:

{ "LoadBalancerDescriptions": [ { { "AvailabilityZones": [ "us-east-1b", "us-east-1c", "us-east-1d" ], "CanonicalHostedZoneName": "example.us-east-1.elb.amazonaws.com", 

I only managed to get this to work when a complete list of values ​​for the AvailabilityZones key is provided.

 $ aws elb describe-load-balancers --region us-east-1 |jq '.LoadBalancerDescriptions[] | select(.AvailabilityZones == ["us-east-1b", "us-east-1c", "us-east-1d"]) | .CanonicalHostedZoneName, .AvailabilityZones' 

The above works, but I just want to choose whether it will contain the value "us-east-1b", regardless of the other values.

+6
source share
1 answer

Perhaps this might work:

 aws elb describe-load-balancers --region us-east-1 | jq '.LoadBalancerDescriptions[] | select((.AvailabilityZones[] | select(. == "us-east-1b")) == "us-east-1b") | .CanonicalHostedZoneName, .AvailabilityZones' 

I really tested with input like this:

 { "LoadBalancerDescriptions": [ { "AvailabilityZones": [ "us-east-1b", "us-east-1c", "us-east-1d" ] } ] } 

And ran this command:

 jq '.LoadBalancerDescriptions[] | select((.AvailabilityZones[] | select(. == "us-east-1b")) == "us-east-1b")' input_file 

Then I got:

 { "AvailabilityZones": [ "us-east-1b", "us-east-1c", "us-east-1d" ] } 

Other for input:

 { "LoadBalancerDescriptions": [ { "AvailabilityZones": [ "us-east-1b", "us-east-1c", "us-east-1d" ] }, { "AvailabilityZones": [ "us-east-1b", "us-east-1c" ] }, { "AvailabilityZones": [ "us-east-1d" ] } ] } 

Output:

 { "AvailabilityZones": [ "us-east-1b", "us-east-1c", "us-east-1d" ] } { "AvailabilityZones": [ "us-east-1b", "us-east-1c" ] } 

You could probably use the concept to check if a key representing an array contains an element such as it.

+5
source

Source: https://habr.com/ru/post/953807/


All Articles