[英]Polling a stopping or starting EC2 instance with Boto
我正在使用AWS,Python和Boto庫 。
我想在Boto EC2實例上調用.stop()
.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控制台,我可以看到實例確實使它“開始”或“停止”。
解決這個問題的唯一方法是在while
循環中調用.get_all_reservations()
,如下所示:
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
報告ACTUAL狀態?
實例狀態不會自動更新。 您必須調用update
方法來告訴對象對EC2服務進行另一次往返調用並獲取對象的最新狀態。 這樣的事情應該有效:
while instance.state not in ('running', 'stopped'):
sleep(5)
instance.update()
為了在boto3中實現相同的效果,這樣的事情應該有效。
import boto3
ec2 = boto3.resource('ec2')
instance = ec2.Instance('i-1234567890123456')
while instance.state['Name'] not in ('running', 'stopped'):
sleep(5)
instance.load()
Python Boto3中的wait_until_running函數似乎就是我要使用的。
http://boto3.readthedocs.io/en/latest/reference/services/ec2.html#EC2.Instance.wait_until_running
這對我也有用。 在文檔上我們有這個:
update(validate=False, dry_run=False)
- 通過調用從服務獲取當前實例屬性來更新實例的狀態信息。
參數: validate (bool)
- 默認情況下,如果EC2沒有返回有關實例的數據,則update方法會安靜地返回。 但是,如果validate參數為True
,則如果沒有從EC2返回數據,則會引發ValueError
異常。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.