jq:按另一个数组元素的值搜索

时间:2017-09-12 16:33:03

标签: jq

我有一组各种类型的对象,它们使用UUID(terraform.tfstate文件)相互引用。我想根据另一个对象中不同值的外观从一个这样的对象中选择一个值,其中两个对象通过其中一个UUID相关联。

举例来说,我可以这样做:

$ jq '.modules[].resources[]
| select(.type == "openstack_compute_instance_v2" and 
         .primary.attributes.name == "jumpbox").primary.id' terraform.tfstate
"5edfe2bf-94df-49d5-8118-3e91fb52946b"
$ jq '.modules[].resources[] 
| select(.type =="openstack_compute_floatingip_associate_v2" and 
         .primary.attributes.instance_id == "5edfe2bf-94df-49d5-8118-3e91fb52946b").primary.attributes.floating_ip' terraform.tfstate
"10.120.241.21"

给我一​​个跳跃盒的外部浮动IP' VM基于其名称。

我想把所有的jq电话都搞定。这可能吗?

1 个答案:

答案 0 :(得分:1)

如果提供更多样本数据,这将更容易回答 从你的命令向后工作(有一些重新格式化)

$ jq '
      .modules[].resources[]
    | select(.type == "openstack_compute_instance_v2" and .primary.attributes.name == "jumpbox")
    | .primary.id
' terraform.tfstate
"5edfe2bf-94df-49d5-8118-3e91fb52946b"

$ jq '
      .modules[].resources[]
    | select(.type =="openstack_compute_floatingip_associate_v2" and .primary.attributes.instance_id == "5edfe2bf-94df-49d5-8118-3e91fb52946b")
    | .primary.attributes.floating_ip
' terraform.tfstate
"10.120.241.21"

我们可以推断您有类似

的数据
{
  "modules": [
    {
      "resources": [
        {
          "type": "openstack_compute_instance_v2",
          "primary": {
            "id": "5edfe2bf-94df-49d5-8118-3e91fb52946b",
            "attributes": {
              "name": "jumpbox"
            }
          }
        },
        {
          "type": "openstack_compute_floatingip_associate_v2",
          "primary": {
            "attributes": {
              "instance_id": "5edfe2bf-94df-49d5-8118-3e91fb52946b",
              "floating_ip": "10.120.241.21"
            }
          }
        }
      ]
    }
  ]
}

以下过滤器使用functionsvariablesparenthesis ()演示了解决方案:

def get_primary_id($name):
    select(.type == "openstack_compute_instance_v2"
       and .primary.attributes.name == $name)
  | .primary.id
;
def get_floating_ip($id):
    select(.type =="openstack_compute_floatingip_associate_v2"
       and .primary.attributes.instance_id == $id)
  | .primary.attributes.floating_ip
;
  .modules[]
| ( .resources[] | get_primary_id("jumpbox") ) as $id
| ( .resources[] | get_floating_ip($id)      ) as $fip
| ($id, $fip)

如果此过滤器位于filter.jqdata.json包含上述示例数据 然后

$ jq -M -f filter.jq data.json

产生输出:

"5edfe2bf-94df-49d5-8118-3e91fb52946b"
"10.120.241.21"
相关问题