Search code examples
javaamazon-ec2sshjsch

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.


Solution

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