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

前端之家收集整理的这篇文章主要介绍了从JAVA API获取Amazon EC2实例的公共DNS前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我已设法启动,停止并检查以前从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;
}
原文链接:https://www.f2er.com/java/239986.html

猜你在找的Java相关文章