Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 547
jatha Avatar asked Feb 11 '12 15:02

jatha


2 Answers

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;
}
like image 111
mac Avatar answered Sep 28 '22 02:09

mac


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.

like image 35
Buffalo Avatar answered Sep 28 '22 02:09

Buffalo