使用Boto轮询停止或启动EC2实例

Dan*_*n H 8 python amazon-ec2 boto amazon-web-services

我正在使用AWS,Python和Boto库.

我想调用.start().stop()在Boto EC2实例上,然后"轮询"它直到它完成.

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
Run Code Online (Sandbox Code Playgroud)

但是,在最后一个while循环中,状态似乎"停滞"在"待定"或"停止"状态.强调"似乎",从我的AWS控制台,我可以看到实例确实使它"开始"或"停止".

我能解决这个问题的唯一方法是.get_all_reservations()while循环中回忆起来,就像这样:

    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
Run Code Online (Sandbox Code Playgroud)

是否有一种方法可以调用,以便instance报告实际状态?

gar*_*aat 13

实例状态不会自动更新.您必须调用该update方法来告诉对象对EC2服务进行另一次往返调用并获取对象的最新状态.这样的事情应该有效:

while instance.state not in ('running', 'stopped'):
    sleep(5)
    instance.update()
Run Code Online (Sandbox Code Playgroud)

为了在boto3中实现相同的效果,这样的事情应该有效.

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


Ant*_*ntu 5

Python Boto3 中的 wait_until_running 函数似乎是我会使用的。

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

  • 你能写一些代码,以便像我这样来到这个链接的人可能会受益于如何在他们的代码中使用 instance.wait_until_running (2认同)