Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 596
Dan H Avatar asked Oct 19 '14 02:10

Dan H


1 Answers

The wait_until_running function in Python Boto3 seem to be what I would use.

http://boto3.readthedocs.io/en/latest/reference/services/ec2.html#EC2.Instance.wait_until_running

like image 157
Antu Avatar answered Nov 03 '22 00:11

Antu