用B轮询停止或启动EC2实例

2024-05-15 15:30:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用AWS、Python和Boto library

我想在Boto EC2实例上调用.start().stop(),然后“轮询”它,直到它完成这两个操作。

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

然而,在最后的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

是否有方法调用以便instance将报告实际状态?


Tags: 实例instanceawsgetallconnstartrunning