首页 > 解决方案 > Object construction with JMESpath

问题描述

I'm trying to build a JMESpath query with AWS CLI that prints a table showing a few selected properties as rows. I can get what I want using jq but I want to do it with just awscli so that it can format as a table. Is this possible? Below is the output I want, using jq object consrtuction syntax:

% 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"
}

The closest I have come is this using a multiselect hash, but this makes each item a column, so it does not look good if there are more than a few items.

% 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  |
+---------------------------+----------------+----------------+

标签: amazon-web-servicesaws-clijmespath

解决方案


The table output will consider different JSON objects as different row.
If you indeed intend to have a property per row, you can create an object per property with a JMESPath query like this:

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

On a JSON structure like:

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

This will give you the this JSON as a result:

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

And the table should then look like:

----------------------------------------------
|              DescribeInstances             |
+--------------+-----------------------------+
|   Property   |            Value            |
+--------------+-----------------------------+
|  LaunchTime  |  2021-02-17T14:49:30+00:00  |
+--------------+-----------------------------+
|     Size     |         g4dn.4xlarge        |
+--------------+-----------------------------+
|  PrivateIP   |         172.31.15.37        |
+--------------+-----------------------------+

推荐阅读