所以我运行这个:
aws ec2 describe-snapshots \
--region xxxxxxxxx \
--owner-ids xxxxxxxxxxxx \
| jq '.Snapshots[] | select(.VolumeId=="vol-xxxxxxxxxxxxx")'
我得到这个https://jqplay.org/s/SnT8lDwycY
如何按StartTime
排序并返回最新的"SnapshotId": "snap-xxxxxxxxxxxxxxxx"
?
当我添加| sort_by(.StartDate)'
时,出现以下错误:
jq: error (at <stdin>:22106): Cannot index string with string "StartDate"
答案 0 :(得分:1)
jqplay上显示的数据是JSON对象流。处理此类流的一种方法是使用jq的-s命令行选项。这实际上将它们组合成一个列表,然后可以对其进行排序。
因此,如果您不关心关系,那么解决此问题的简单方法是:
sort_by(.StartTime) | .[-1] | .SnapshotId
如果您的jq足够最新,则可以缩写为:
sort_by(.StartTime)[-1].SnapshotId
答案 1 :(得分:0)
想通了...
aws ec2 describe-snapshots \
--region xx-xxxx-x \
--owner-ids xxxxxxxxxx \
| jq -r '.Snapshots[] | select(.VolumeId=="vol-xxxxxxxxxxxxxxx") \
| [(.StartTime | split(", ")), (.SnapshotId | split(", "))] \
| transpose \
| { Snapshots: map({ StartTime:.[0], SnapshotId:.[1] }) } \
| .Snapshots \
| sort_by(.StartTime) \
| grep SnapshotId -m 1 \
| cut -d : -f 2 | sed 's/"//g''
答案 2 :(得分:0)
以下是一些如何使用内置--query
选项的示例。每个示例均基于前一个示例。
获取所有快照,按开始时间升序排序:
aws ec2 describe-snapshots \
--owner-ids xxxxxxxxxxxx \
--query 'sort_by(Snapshots, &StartTime)'
获取最早的快照:
aws ec2 describe-snapshots \
--owner-ids xxxxxxxxxxxx \
--query 'sort_by(Snapshots, &StartTime)[0]'
获取最新快照:
aws ec2 describe-snapshots \
--owner-ids xxxxxxxxxxxx \
--query 'sort_by(Snapshots, &StartTime)[-1]'
# Example of output:
{
"Description": "End of Q3 snapshot",
"Encrypted": false,
"OwnerId": "xxxxxxxxxxxx",
"Progress": "100%",
"SnapshotId": "snap-0f601234abcd12345",
"StartTime": "2019-09-30T23:59:59.999Z",
"State": "completed",
"VolumeId": "vol-0f123dc5b1dd911d3",
"VolumeSize": 8
}
获取最新快照的ID:
aws ec2 describe-snapshots \
--owner-ids xxxxxxxxxxxx \
--query 'sort_by(Snapshots, &StartTime)[-1].SnapshotId'
# Example of output:
"snap-0f601234abcd12345"
以纯文本格式获取最新快照的ID:
aws ec2 describe-snapshots \
--owner-ids xxxxxxxxxxxx \
--query 'sort_by(Snapshots, &StartTime)[-1].SnapshotId' \
--output text
# Example of output:
snap-0f601234abcd12345
如果您更喜欢使用jq
,则可以获得以下相同的结果(如@peak所示):
aws ec2 describe-snapshots \
--owner-ids xxxxxxxxxxxx \
| jq -r '.Snapshots | sort_by(.StartTime)[-1].SnapshotId'