使用Boto轮询停止或启动的EC2实例 [英] Polling a stopping or starting EC2 instance with Boto

查看:143
本文介绍了使用Boto轮询停止或启动的EC2实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用AWS,Python和 Boto库

I'm using AWS, Python, and the Boto library.

我想调用 .start() .stop() 在Boto EC2实例上,然后对其进行轮询,直到完成为止。

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

但是,在最后的 while 循环中,状态似乎在待定或停止时卡住。从我的AWS控制台着重强调似乎,我可以看到实例实际上确实使其变为开始或停止。

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".

可以解决的办法是在 while 循环中调用 .get_all_reservations(),如下所示:

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

是否有一种调用方法,因此实例将报告ACTUAL状态?

Is there a method to call so the instance will report the ACTUAL state?

推荐答案

实例状态不会自动更新。您必须调用 update 方法,以告诉对象再次调用EC2服务并获取对象的最新状态。像这样的东西应该起作用:

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

要在boto3中获得相同的效果,

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

这篇关于使用Boto轮询停止或启动的EC2实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆