简体   繁体   中英

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?

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()

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

This work for me too. On docs we have this:

update(validate=False, dry_run=False)
- Update the instance's state information by making a call to fetch the current instance attributes from the service.

Parameters: validate (bool)
– By default, if EC2 returns no data about the instance the update method returns quietly. If the validate parameter is True , however, it will raise a ValueError exception if no data is returned from EC2.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM