Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter array with jq based on nested values

Tags:

json

aws-cli

jq

I am writing some bash scripts to help automate the management of AWS resources. I am using aws-cli and jq, and so far things have been great.

I am tagging my resources with custom tags. In certain circumstances I would like to filter a list of resources based on both Key and Value of the custom tag. But I am having trouble working out a succinct jq query to do it.

So, for example, if the (trimmed) JSON output for my ec2 instances is like:

[
    {
        "PublicIpAddress": "11.22.33.44",
        "PrivateIpAddress": "55.66.77.88",
        "Tags": [
            {
                "Value": "live199.blah.com",
                "Key": "Name"
            },
            {
                "Value": "live-standalone",
                "Key": "hc-class"
            }
        ]
    }
]
[
    {
        "PublicIpAddress": "111.222.333.444",
        "PrivateIpAddress": "555.666.777.888",
        "Tags": [
            {
                "Value": "staging99.blah.com",
                "Key": "Name"
            },
            {
                "Value": "staging-standalone",
                "Key": "hc-class"
            }
        ]
    }
]

...and I need find the entry where Tags.Key == "hc-class" and Tags.Value = "staging-standalone", how do I do it in a succinct way with jq?

Any help greatly appreciated.

like image 842
bhu Boue vidya Avatar asked Apr 13 '17 16:04

bhu Boue vidya


1 Answers

With the given input, the following filter produces the output as shown below:

.[] | select(any(.Tags[]; .Key == "hc-class" and .Value == "staging-standalone"))

Output:

{
  "PublicIpAddress": "111.222.333.444",
  "PrivateIpAddress": "555.666.777.888",
  "Tags": [
    {
      "Value": "staging99.blah.com",
      "Key": "Name"
    },
    {
      "Value": "staging-standalone",
      "Key": "hc-class"
    }
  ]
}
like image 158
peak Avatar answered Oct 11 '22 20:10

peak