简体   繁体   中英

Get Public DNS of Amazon EC2 Instance from JAVA API

I have managed to start, stop and check the status of a previously created EC2 instance from JAVA API. However, i'm having difficulty on getting the public dns address of this instance. Since I start the instance with StartInstancesRequest and get the response with StartInstancesResponse, i couldn't be able to retrieve the actual Instance object. My starting code is given below, it works:

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

Besides any help through connecting to this instance via JSch will be appreciated.

Thanks a lot!

Here's a method that would do the trick. It would be best to check that the instance is in the running state before calling this.

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

You can now use a filter when using describeInstances , so you don't pull info for all your instances.

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

Using aws-java-sdk-1.9.35.jar .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM