Polling a stopping or starting EC2 instance with Boto

I'm using AWS, Python, and the Boto library.

I'd like to invoke .start() or .stop() on a Boto EC2 instance, then "poll" it until it has completed either.

import boto.ec2

credentials = {
  'aws_access_key_id': 'yadayada',
  'aws_secret_access_key': 'rigamarole',
  }

def toggle_instance_state():
    conn = boto.ec2.connect_to_region("us-east-1", **credentials)
    reservations = conn.get_all_reservations()
    instance = reservations[0].instances[0]
    state = instance.state
    if state == 'stopped':
        instance.start()
    elif state == 'running':
        instance.stop()
    state = instance.state
    while state not in ('running', 'stopped'):
        sleep(5)
        state = instance.state
        print " state:", state

However, in the final while loop, the state seems to get "stuck" at either "pending" or "stopping". Emphasis on "seems", as from my AWS console, I can see the instance does in fact make it to "started" or "stopped".

The only way I could fix this was to recall .get_all_reservations() in the while loop, like this:

    while state not in ('running', 'stopped'):
        sleep(5)
        # added this line:
        instance = conn.get_all_reservations()[0].instances[0]
        state = instance.state
        print " state:", state

Is there a method to call so the instance will report the ACTUAL state?

Answers 1

  • The instance state does not get updated automatically. You have to call the update method to tell the object to make another round-trip call to the EC2 service and get the latest state of the object. Something like this should work:

    while instance.state not in ('running', 'stopped'):
        sleep(5)
        instance.update()
    

    To achieve the same effect in boto3, something like this should work.

    import boto3
    ec2 = boto3.resource('ec2')
    instance = ec2.Instance('i-1234567890123456')
    while instance.state['Name'] not in ('running', 'stopped'):
        sleep(5)
        instance.load()
    

Related Articles