从JAVA API获取Amazon EC2实例的公共DNS - java

我设法通过JAVA API启动,停止并检查了先前创建的EC2实例的状态。但是,我很难获得此实例的公共DNS地址。由于我使用StartInstancesRequest启动实例,并使用StartInstancesResponse获取响应,因此我无法检索实际的Instance对象。我的起始代码如下,它可以正常工作:

BasicAWSCredentials oAWSCredentials = new BasicAWSCredentials(sAccessKey, sSecretKey);
AmazonEC2 ec2 = new AmazonEC2Client(oAWSCredentials);
ec2.setEndpoint("https://eu-west-1.ec2.amazonaws.com");
List<String> instanceIDs = new ArrayList<String>();
instanceIDs.add("i-XXXXXXX");

StartInstancesRequest startInstancesRequest = new StartInstancesRequest(instanceIDs);
try {
        StartInstancesResult response = ec2.startInstances(startInstancesRequest);
        System.out.println("Sent! "+response.toString());
    }catch (AmazonServiceException ex){
        System.out.println(ex.toString());
        return false;
    }catch(AmazonClientException ex){
        System.out.println(ex.toString());
        return false;
    }

除了通过JSch连接到该实例的任何帮助,我们将不胜感激。

非常感谢!

参考方案

这是可以解决问题的方法。最好在调用此实例之前检查实例是否处于运行状态。

String getInstancePublicDnsName(String instanceId) {
    DescribeInstancesResult describeInstancesRequest = ec2.describeInstances();
    List<Reservation> reservations = describeInstancesRequest.getReservations();
    Set<Instance> allInstances = new HashSet<Instance>();
    for (Reservation reservation : reservations) {
      for (Instance instance : reservation.getInstances()) {
        if (instance.getInstanceId().equals(instanceId))
          return instance.getPublicDnsName();
      }
    }
    return null;
}

45码