基于嵌套值使用 jq 过滤数组

bhu*_*dya 5 json aws-cli jq

我正在编写一些 bash 脚本来帮助自动化 AWS 资源的管理。我正在使用aws-cliand jq,到目前为止一切都很好。

我正在使用自定义标签标记我的资源。在某些情况下,我想根据KeyValue自定义标签过滤资源列表。但是我在制定一个简洁的jq查询来做到这一点时遇到了麻烦。

因此,例如,如果我的 ec2 实例的(修剪后的)JSON 输出类似于:

[
    {
        "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"
            }
        ]
    }
]
Run Code Online (Sandbox Code Playgroud)

...我需要在 whereTags.Key == "hc-class"和 中找到条目,Tags.Value = "staging-standalone"我该如何以简洁的方式做到这一点jq

非常感谢任何帮助。

pea*_*eak 6

对于给定的输入,以下过滤器会产生如下所示的输出:

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

输出:

{
  "PublicIpAddress": "111.222.333.444",
  "PrivateIpAddress": "555.666.777.888",
  "Tags": [
    {
      "Value": "staging99.blah.com",
      "Key": "Name"
    },
    {
      "Value": "staging-standalone",
      "Key": "hc-class"
    }
  ]
}
Run Code Online (Sandbox Code Playgroud)