Get a public DNS instance of an Amazon EC2 instance from the JAVA API

I managed to start, stop and check the status of a previously created EC2 instance from the JAVA API. However, it is difficult for me to get the public dns address of this instance. Since I am starting the instance using StartInstancesRequest and getting a response using StartInstancesResponse, I could not get the real instance of the object. My starter code is 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; } 

In addition, any help connecting to this instance through JSch would be appreciated.

Thanks a lot!

+6
source share
2 answers

Here is a method that would do the trick. It would be better to verify that the instance is in a running state before invoking 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; } 
+7
source

Now you can use the filter when using describeInstances , so you do not retrieve information for all of 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 .

+1
source

Source: https://habr.com/ru/post/908215/


All Articles