当这些属性处于同一级别时,aws cli 查询多个属性

aws cli query multiple attributes when these attributes are on the same level

我正在使用 following 查找有关与特定安全组关联的实例的信息

aws ec2 describe-network-interfaces --filters Name=group-id,Values=sg-123456 --output json

这个returns(部分输出)

{
    "NetworkInterfaces": [
        {
            "Attachment": {
                "AttachTime": "2019-10-09T07:15:44+00:00",
                "AttachmentId": "eni-attach-01234567",
                "InstanceId": "i-12345678",
                "InstanceOwnerId": "123456789",
                "Status": "attached"
            },
            "AvailabilityZone": "us-east-1c",
            "Description": "Primary network interface",
            "Groups": [
                {
                    "GroupName": "sg-number1",
                    "GroupId": "sg-123456"
                },
                {
                    "GroupName": "sg-number_2",
                    "GroupId": "sg-654321"
                }
            ],

如果我只想获取实例 ID,那么我可以使用 --query 并向下搜索树

--query 'NetworkInterfaces[*].Attachment.InstanceId'

我也可以做类似的事情来获得所有 SG

--query 'NetworkInterfaces[*].Groups[*].GroupId'

我的问题是如何在一次查询中获取 InstanceID 和 Group.GroupName?

或者更好的是当这些属性处于同一级别时如何查询多个属性?

以下无效:

--query 'NetworkInterfaces[*].Attachment.InstanceId','NetworkInterfaces[*].Groups[*].GroupName'

当然可以,您将不得不使用 JMESPath 在示例中描述的内容 filters and multiselect hashes

有了这个,您可以重新创建一个对象,查询沿着树向下。

在你的例子中,查询:

NetworkInterfaces[*].{ InstanceId: Attachment.InstanceId, GroupNames: Groups[*].GroupName }

和 JSON 数据:

{
    "NetworkInterfaces": [
        {
            "Attachment": {
                "AttachTime": "2019-10-09T07:15:44+00:00",
                "AttachmentId": "eni-attach-01234567",
                "InstanceId": "i-12345678",
                "InstanceOwnerId": "123456789",
                "Status": "attached"
            },
            "AvailabilityZone": "us-east-1c",
            "Description": "Primary network interface",
            "Groups": [
                {
                    "GroupName": "sg-number1",
                    "GroupId": "sg-123456"
                },
                {
                    "GroupName": "sg-number_2",
                    "GroupId": "sg-654321"
                }
            ]
        }
    ]
}

它给出:

[
  {
    "InstanceId": "i-12345678",
    "GroupNames": [
      "sg-number1",
      "sg-number_2"
    ]
  }
]

所以你的命令最终是:

aws ec2 describe-network-interfaces --filters Name=group-id,Values=sg-123456 --output json --query 'NetworkInterfaces[*].{ InstanceId: Attachment.InstanceId, GroupNames: Groups[*].GroupName }'