5

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.

bhu Boue vidya
  • 379
  • 6
  • 16
  • 1
    you can just do it straight from aws CLI using JMESPATH, look at the question http://stackoverflow.com/questions/43354116/using-jmespath-and-aws-ec2-describe-instances-to-output-multiple-tag-values which details some example how to work iwth that – Frederic Henri Apr 13 '17 at 16:33
  • What do you mean by "entry"? Since "Tags" is an array, the inclusion criterion is unclear. It might help if you gave the expected output. – peak Apr 13 '17 at 17:49
  • Possible duplicate of [Filtering JSON object list with jq by matching multiple objects](http://stackoverflow.com/questions/33973816/filtering-json-object-list-with-jq-by-matching-multiple-objects) – Jeff Mercado Apr 13 '17 at 23:29

2 Answers2

7

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"
    }
  ]
}
Jeff Mercado
  • 129,526
  • 32
  • 251
  • 272
peak
  • 105,803
  • 17
  • 152
  • 177
-1

I'm quite new to JQ, but I feel like I have a solution here:

https://jqplay.org/s/DljtxNX_72

select((.[0].Tags[1].Key) == "hc-class" and (.[0].Tags[1].Value) == "staging-standalone")
samjewell
  • 1,068
  • 11
  • 20