【问题标题】:AWS get instance name in JavaAWS在Java中获取实例名称
【发布时间】:2017-06-06 21:39:57
【问题描述】:

我正在用 Java 开发一个应用程序,我能够列出实例:

for (Reservation reservation : result.getReservations()) {
    for (Instance instance : reservation.getInstances()) {
        System.out.println("Instance id:"
                + instance.getInstanceId());
    }
}

如何获取实例名称?

【问题讨论】:

  • 知道了。 Thanks.Instance.getTags() 给出标签列表,Tag.value 是实例名称。
  • @shmosel:您能否发帖作为 Viswanath 接受的答案,以便其他人可以找到您的解决方案?
  • @DaveMaple 我不知道足以发布实质性答案。随意张贴自己。

标签: java amazon-web-services amazon-ec2 aws-sdk


【解决方案1】:

要获取实例名称,您需要使用以下内容:

        for (Reservation reservation : response.getReservations()) {
            for (Instance instance : reservation.getInstances()) {
                Tag tagName = instance.getTags().stream()
                        .filter(o -> o.getKey().equals("Name"))
                        .findFirst()
                        .orElse(new Tag("Name", "name not found"));

                System.out.println("Found instance with ID: " + instance.getInstanceId()
                        + ", NAME: " + tagName.getValue()
                        + ", TYPE: " + instance.getInstanceType()
                );
            }
        }

通过这种方式,您可以提取具有 key:"Name" 和 value 的标签是您所需要的。

【讨论】:

    【解决方案2】:

    您可以访问与实例关联的标签:

    for (Reservation reservation : result.getReservations()) {
        for (Instance instance : reservation.getInstances()) {
            System.out.println("Instance id:" + instance.getInstanceId());
    
            if (instance.getTags() != null) {
                for (Tag tag : instance.getTags()) {
                    System.out.println(String.format(
                        "%s: %s", 
                        tag.getKey(), 
                        tag.getValue()
                    ));
                }
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2013-08-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多