2012-02-11 199 views
6

我設法從JAVA API啓動,停止並檢查以前創建的EC2實例的狀態。但是,我很難獲取此實例的公共dns地址。由於我使用StartInstancesRequest啓動實例並使用StartInstancesResponse獲取響應,因此我無法檢索實際的Instance對象。我的起始代碼如下,它的工作原理:從JAVA API獲取Amazon EC2實例的公共DNS

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的幫助將不勝感激。

非常感謝!

回答

7

這裏有一個方法可以做到這一點。在調用它之前,最好檢查實例是否處於運行狀態。

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; 
} 
+0

完美無瑕地工作,非常感謝! – jatha 2012-02-12 14:45:03

1

您現在可以在使用describeInstances時使用過濾器,因此您不必爲所有實例提供信息。

private String GetDNS(String aInstanceId) 
{ 
    DescribeInstancesRequest request = new DescribeInstancesRequest(); 
    request.withInstanceIds(aInstanceId); 
    DescribeInstancesResult result = amazonEC2.describeInstances(request); 

    for (Reservation reservations : result.getReservations()) 
    { 
    for (Instance instance : reservations.getInstances()) 
    { 
     if (instance.getInstanceId().equals(aInstanceId)) 
     { 
     return instance.getPublicDnsName(); 
     } 
    } 
    } 

    return null; 
} 

使用aws-java-sdk-1.9.35.jar

相關問題