Get the public DNS of Amazon EC2 instance from Java API

I have managed to start, stop and check the status of EC2 instances previously created from the Java API However, it is difficult for me to obtain the public DNS address of this instance Because I started the instance with startinstancesrequest and got the response with startinstancesresponse, I couldn't retrieve the actual instance object My starting code is as follows, which is valid:

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

Any help other than connecting to this instance via jsch will be appreciated

Thank you.

Solution

This is a way to solve the problem Before calling, it is best to check whether the instance is running

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;
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>