【问题标题】:How to get the most recently launched EC2 instance with AWS CLI?如何使用 AWS CLI 获取最近启动的 EC2 实例?
【发布时间】:2019-03-24 23:11:30
【问题描述】:

我目前正在使用以下 CLI 命令来获取给定实例 Name 标记“myInstanceName”的实例 PublicIPAddressLaunchTime

aws ec2 describe-instances --filters 'Name=tag:Name,Values=myInstanceName' \ 
    --region us-east-1 \
    --query 'Reservations[*].Instances[*].{PublicIpAddress: PublicIpAddress, LaunchTime: LaunchTime}'

这会导致以下结果:

[
    {
        "LaunchTime": "2019-01-25T11:49:06.000Z",
        "PublicIpAddress": "11.111.111.11"
    }
]

这很好,但是如果有两个同名的实例,我将在结果 JSON 中得到两个结果。我需要找到一种方法来获取给定名称的最新实例。

解决方案更新

这个问题是针对 EC2 实例的。该问题可以使用两种不同的方法解决,答案如下:
Parsing Result with jq
Using JMESPath

请参阅此related question,了解使用 JMESPath 按日期进行更一般的排序,以及进一步阅读。

【问题讨论】:

标签: amazon-web-services amazon-ec2 aws-cli


【解决方案1】:

尝试使用jq 实用程序。它是一个命令行 JSON 解析器。如果您不熟悉它,我建议您使用 jq playground 进行实验。

先将awcli结果展平,如下:

aws ec2 describe-instances  \
    --query 'Reservations[].Instances[].{ip: PublicIpAddress, tm: LaunchTime}' \
    --filters 'Name=tag:Name,Values= myInstanceName'

请注意,为简洁起见,我已将 LaunchTime 别名为 tm。这将导致(未排序的)输出如下:

[
  {
    "ip": "54.4.5.6",
    "tm": "2019-01-04T19:54:11.000Z"
  },
  {
    "ip": "52.1.2.3",
    "tm": "2019-03-04T20:04:00.000Z"
  }
]

接下来,将此结果通过管道传递给jq,并按tmLaunchTime 的别名)降序排序,如下所示:

jq 'sort_by(.tm) | reverse'

这将导致如下输出:

[
  {
    "ip": "52.1.2.3",
    "tm": "2019-03-04T20:04:00.000Z"
  },
  {
    "ip": "54.4.5.6",
    "tm": "2019-01-04T19:54:11.000Z"
  }
]

最后,使用jq过滤掉除第一个结果之外的所有结果,如下:

jq 'sort_by(.tm) | reverse | .[0]'

这将产生一个结果,即最近启动的实例:

{
  "ip": "52.1.2.3",
  "tm": "2019-03-04T20:04:00.000Z"
}

综合起来,最后的命令是:

aws ec2 describe-instances  \
    --query 'Reservations[].Instances[].{ip: PublicIpAddress, tm: LaunchTime}' \
    --filters 'Name=tag:Name,Values= myInstanceName' | \
    jq 'sort_by(.tm) | reverse | .[0]'

【讨论】:

  • 谢谢。这非常有用,我不知道 sort_by 函数。很好的答案,我很感激!
【解决方案2】:

这是一种查找最新启动实例并显示有关它的数据的方法:

aws ec2 describe-instances  --query 'sort_by(Reservations[].Instances[], &LaunchTime)[:-1].[InstanceId,PublicIpAddress,LaunchTime]'

sort_by(Reservations[].Instances[], &LaunchTime)[:-1] 将返回最后启动的实例。然后从这些实例中检索这些字段。

要了解这种乐趣,请参阅:

【讨论】:

    猜你喜欢
    • 2022-11-18
    • 2023-03-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多