使用 JMESpath

问题描述

我正在尝试使用 AWS CLI 构建一个 JMESpath 查询,该查询打印一个表,其中显示了一些选定的属性作为行。我可以使用 jq 获得我想要的东西,但我只想使用 awscli 来完成它,以便它可以格式化为表格。这可能吗?下面是我想要的输出,使用 jq 对象构造语法:

% aws --output json ec2 describe-instances --instance-id $id --query 'Reservations[].Instances[0]' | jq '.[0] | {InstanceType,PrivateIpAddress,LaunchTime}'
{
  "InstanceType": "g4dn.4xlarge","PrivateIpAddress": "172.31.15.37","LaunchTime": "2021-02-17T14:49:30+00:00"
}

我最接近的是使用多选散列,但这使每个项目成为一列,因此如果项目超过几个,它看起来不太好。

% aws --output table ec2 describe-instances --instance-id $id --query 'Reservations[].Instances[0].{size: InstanceType,PrivateIP: PrivateIpAddress,LaunchTime: LaunchTime}' 
---------------------------------------------------------------
|                      DescribeInstances                      |
+---------------------------+----------------+----------------+
|        LaunchTime         |   PrivateIP    |     size       |
+---------------------------+----------------+----------------+
|  2021-02-17T14:49:30+00:00|  172.31.15.37  |  g4dn.4xlarge  |
+---------------------------+----------------+----------------+

解决方法

value 输出会将不同的 JSON 对象视为不同的行。
如果您确实打算每行有一个属性,您可以使用 JMESPath 查询为每个属性创建一个对象,如下所示:

table

在 JSON 结构上,例如:

Reservations[].Instances[0].[ { Property: `LaunchTime`,Value: LaunchTime },{ Property: `Size`,Value: InstanceType },{ Property: `PrivateIP`,Value: PrivateIpAddress } ]

这会给你这个 JSON 结果:

{
  "Reservations": [
    {
      "Instances": [
        {
          "InstanceType": "g4dn.4xlarge","PrivateIpAddress": "172.31.15.37","LaunchTime": "2021-02-17T14:49:30+00:00"
        }
      ]
    }
  ]
}

然后表格应该如下所示:

[
  [
    {
      "Property": "LaunchTime","Value": "2021-02-17T14:49:30+00:00"
    },{
      "Property": "Size","Value": "g4dn.4xlarge"
    },{
      "Property": "PrivateIP","Value": "172.31.15.37"
    }
  ]
]