简短的回答
添加
[] | sort_by(@, &[3])
在你的表达结束。方括号 ( []
) 将展平结构,sort_by(...)
将结果(这是一个四列表)按第四列排序。完整的查询将是:
--query 'Reservations[*].Instances[*].[LaunchTime,InstanceId,PrivateIpAddress,Tags[?Key==`Name`] | [0].Value][] | sort_by(@, &[3])'
长答案
检查您当前的查询结果
根据describe-instances
文档,describe-instances
输出的结构如下所示:
{
"Reservations": [
{
"Instances": [
{
"LaunchTime": "..LaunchTime..",
"InstanceId": "R1I1",
"PrivateIpAddress": "..PrivateIpAddress..",
"Tags": [{"Key": "Name", "Value": "foo"}]
},
{
"LaunchTime": "..LaunchTime..",
"InstanceId": "R1I2",
"PrivateIpAddress": "..PrivateIpAddress..",
"Tags": [{"Key": "Name", "Value": "baz"}]
}
]
},
{
"Instances": [
{
"LaunchTime": "..LaunchTime..",
"InstanceId": "R2I1",
"PrivateIpAddress": "..PrivateIpAddress..",
"Tags": [{"Key": "Name", "Value": "bar"}]
}
]
}
]
}
使用您的原始查询
--query 'Reservations[*].Instances[*].[LaunchTime,InstanceId,PrivateIpAddress,Tags[?Key==`Name`] | [0].Value]'
将输出
[
[
[
"..LaunchTime..",
"R1I1",
"..PrivateIpAddress..",
"foo"
],
[
"..LaunchTime..",
"R1I2",
"..PrivateIpAddress..",
"baz"
]
],
[
[
"..LaunchTime..",
"R2I1",
"..PrivateIpAddress..",
"bar"
]
]
]
展平查询结果
您可以在上述查询结果中看到您正在获取一个表列表 ( [[{},{}],[{}]]
)。我想您需要一个非嵌套表 ( [{},{},{}]
)。为此,只需[]
在查询末尾添加,即
--query 'Reservations[*].Instances[*].[LaunchTime,InstanceId,PrivateIpAddress,Tags[?Key==`Name`] | [0].Value][]'
这将使结构变平,导致
[
[
"..LaunchTime..",
"R1I1",
"..PrivateIpAddress..",
"foo"
],
[
"..LaunchTime..",
"R1I2",
"..PrivateIpAddress..",
"baz"
],
[
"..LaunchTime..",
"R2I1",
"..PrivateIpAddress..",
"bar"
]
]
现在是时候对表格进行排序了。
对表格进行排序
使用sort_by
时不要忘记在表达式前面加上&
(&)。这样,您可以指定对该表达式的引用sort_by
,然后将其传递给.
示例: data | sort_by(@, &@)
相当于data | sort(@)
.
TagName
您创建的表中的 ( )[LaunchTime,InstanceId,PrivateIpAddress,TagName]
是第四列。您可以通过将表传递给表达式来获取该列[3]
:
TableExpression | [3]
但是,您希望按第四列对表格进行排序。你可以这样做:
TableExpression | sort_by(@, &[3])
结果查询将是:
--query 'Reservations[*].Instances[*].[LaunchTime,InstanceId,PrivateIpAddress,Tags[?Key==`Name`][] | [0].Value] | sort_by(@, &[3])'
查询结果:
[
[
"..LaunchTime..",
"R2I1",
"..PrivateIpAddress..",
"bar"
],
[
"..LaunchTime..",
"R1I2",
"..PrivateIpAddress..",
"baz"
],
[
"..LaunchTime..",
"R1I1",
"..PrivateIpAddress..",
"foo"
]
]