Question

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

Here is partial redacted json representing the source output:

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

I have only been able to get this to work when specifiying the full list of values for the AvailabilityZones key.

$ 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 want to just select if it contains a value for "us-east-1b", regardless of the other values.

Was it helpful?

Solution

Perhaps this could work:

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

I actually tested with an 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"
  ]
}

Another 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 probably could use the concept to validate if a key representing an array contains an element like it.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top