由于实例对象变量未被更新,因此无法启动实例,boto3

时间:2016-07-01 05:32:31

标签: python

我正在尝试停止然后启动一个实例列表,我还需要检查实例是否已停止,以及启动部分的类似情况。

代码看起来像

$getID

继续打印:

client = boto3.client('ec2', aws_access_key_id=ACCESS_KEY, aws_secret_access_key=SECRET_KEY, region_name=region, )
response = client.stop_instances(InstanceIds=[instance_id])
print "Stopping instance Now",response['StoppingInstances']

for instance in response['StoppingInstances']:
    while instance['CurrentState']['Name'] != "stopped":
        print "Inside the STOP while LOOP"
        if instance['CurrentState']['Name'] == "stopped":
           print "Now instance is Stopped!!!"
        else :
           print "Instance is still being Stopped"

请帮助

1 个答案:

答案 0 :(得分:1)

这是一个非常繁忙的循环,您可能希望在其中添加sleep 您没有更新状态,但每次只是引用相同的状态,您需要获取最新状态。鉴于您只是停止一个instance_id,那么您可以这样做:

ec2 = boto3.resource('ec2')
response = ec2.Instance(instance_id).stop()

while ec2.Instance(instance_id).state['Name'] != "stopped":
    print "Instance is still being Stopped"
    time.sleep(5)
else:
    print "Now instance is Stopped!!!"

如果您要等待停止的实例列表,则可以使用:

ec2 = boto3.resource('ec2')
response = ec2.instances.filter(InstanceIds=instance_ids).stop()

while all(i.state['Name'] != 'stopped' for i in ec2.instances.filter(InstanceIds=instance_ids)):
    print "Instances are still being Stopped"
    time.sleep(5)
else:
    print "All instances are Stopped!!!"