Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EC2 Java Api Wait till Ec2 Instance gets created.

I have just started using Amazon EC2 API in Java.

I have created instances using ec2.runInstances(runInstancesRequest);

But it will take some time for the instance to get launched (typically 1-2 mins). I need to get the public DNS of the machine via Java EC2 API.

How do I know when the instances change from "pending" state to "processed" state, and How can I get the public DNS of the EC2 instance through the EC2 API.

Thanks in advance. Kanna

like image 904
kanap008 Avatar asked Oct 04 '11 18:10

kanap008


People also ask

How long does it take to create an EC2 instance?

You do not need to wait for the Instance Status Check to complete before using an Amazon EC2 instance. Linux instances are frequently ready 60-90 seconds after launch.

How long does it take for an EC2 instance to reboot?

In most cases, it takes only a few minutes to reboot your instance. When you reboot an instance, it keeps its public DNS name (IPv4), private and public IPv4 address, IPv6 address (if applicable), and any data on its instance store volumes.


1 Answers

There is no event model or other signal raised by the SDK to tell you when an EC2 object changes state - the only way to find out is to issue a DescribeXXXXXXXX call on the object on a repeated basis, say once every 30 seconds, until the state field changes.

There's a finite minimum time for the call to execute and respond, so you need to find an interval that doesn't fire requests before the prior one has completed. Or simply wait for the response, and then wait another 'n' seconds before re-issuing the call. You also don't want to spam the AWS API with rapid requests, even if they're timed between responses. In my controller application, I set the interval at 30 seconds, issue the request, wait for the response, and then subtract the elapsed time from the interval and sleep that long. In a multithreaded model, I can thereby track state changes on many objects simultaneously without swamping either my local CPU or the API.

Once the change of state has been detected (and assuming the new state is whet you expect - don't forget to handle failure modes) you can get a wide variety of descriptive information, including public DNS address (in the case of instance objects) from the structure returned in the API response object.

like image 188
Eight-Bit Guru Avatar answered Sep 20 '22 23:09

Eight-Bit Guru