Polling a stopping or starting EC2 instance with B

2019-04-06 15:40发布

问题:

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?

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


回答2:

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



回答3:

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.