EC2: Waiting until a new instance is in running state

boto3 has:

instance.wait_until_running()

From the boto3 docs:

Waits until this Instance is running. This method calls EC2.Waiter.instance_running.wait() which polls EC2.Client.describe_instances() every 15 seconds until a successful state is reached. An error is returned after 40 failed checks.


Depending on what you are trying to do (and how many servers you plan on starting), instead of polling for the instance start events, you could install on the AMI a simple program/script that runs once when the instance starts and sends out a notification to that effect, i.e. to an AWS SNS Topic.

The process that needs to know about new servers starting could then subscribe to this SNS topic, and would receive a push notifications each time a server starts.

Solves the same problem from a different angle; your mileage may vary.


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.


From the AWS CLI changelog for v1.6.0:

Add a wait subcommand that allows for a command to block until an AWS resource reaches a given state (issue 992, issue 985)

I don't see this mentioned in the documentation, but the following worked for me:

aws ec2 start-instances --instance-ids "i-XXXXXXXX"
aws ec2 wait instance-running --instance-ids "i-XXXXXXXX"

The wait instance-running line did not finish until the EC2 instance was running.

I don't use Python/boto/botocore but assume it has something similar. Check out waiter.py on Github.

Tags:

Amazon Ec2