Search code examples
amazon-ec2

EC2: Waiting until a new instance is in running state


I would like to create a new instance based on my stored AMI.

I achieve this by the following code:

RunInstancesRequest rir = new RunInstancesRequest(imageId,1, 1);
// Code for configuring the settings of the new instance
...
RunInstancesResult runResult = ec2.runInstances(rir);

However, I cannot find a wait to "block"/wait until the instance is up and running apart from Thread.currentThread().sleep(xxxx) command.

On the other hand, StartInstancesResult and TerminateInstancesResult gives you a way to have access on the state of the instances and be able to monitor any changes. But, what about the state of a completely new instance?


Solution

  • Waiting for the EC2 instance to get ready is a common pattern. In the Python library boto you also solve this with sleep calls:

       reservation = conn.run_instances([Instance configuration here])
       instance = reservation.instances[0]
    
       while instance.state != 'running':
           print '...instance is %s' % instance.state
           time.sleep(10)
           instance.update()
    

    With this mechanism you will be able to poll when your new instance will come up.