使用if条件在while循环时中断

时间:2016-04-22 16:55:22

标签: python boto

我正在开发一个自动创建AMI的项目。 要求:1。创建AMI              2.等到创建AMI              3.如果AMI创建失败或成功,则打破循环              4.重复所有实例的程序

我们不想在创建AMI时重启实例。

问题:当我将break语句添加到if条件时,脚本不会终止内部while循环。有人可以帮我修改代码。

#!/usr/bin/env python
import sys
import boto
import boto.ec2
import datetime
import time

list_1 = ['instance1','instance2']
conn = boto.ec2.connect_to_region('us-west-1',aws_access_key_id = '<access_key>',aws_secret_access_key = '<secret_key>')

def create_img(a, b):
    try:
        print "Starting AMI creation for : %s" % inst.tags['Name']
        img_id = conn.create_image(a, b, description='backup', no_reboot=True, dry_run=False)
    except boto.exception.BotoServerError, e:
        print e.error_message
    return(img_id)


reservations = conn.get_all_instances()
for res in reservations:
    for inst in res.instances:
        if 'Name' in inst.tags and inst.tags['Name'] in list_1:
            print "%s (%s) [%s]" % (inst.tags['Name'], inst.id, inst.state)

            name = inst.tags['Name'] + '-' + datetime.datetime.now().strftime("%Y%m%d%H%M")
            ami_id = create_img(inst.id, name)
            img = conn.get_all_images(filters={'image_id' : ami_id})[0]

            if img.state == 'failed':
                print "AMI creation failed for instance: %s" % inst.tags['Name']
            elif img.state == 'pending':
                while True:
                    if img.state == 'failed':
                        print "AMI creation failed for instance: %s" % inst.tags['Name']
                        break
                    elif img.state == 'available':
                        print "AMI creation completed for instance: %s" % inst.tags['Name']
                        break
                    else:
                        time.sleep(60)
            elif img.state == 'available':
                print "AMI creation completed for instance: %s" % inst.tags['Name']
            else:
                print "Couldn't find the AMI"

1 个答案:

答案 0 :(得分:1)

您需要通过调用img.update()来更新状态。状态信息不会自动更新。只有在响应boto API调用时才会调用AWS。

        img = conn.get_all_images(filters={'image_id' : ami_id})[0]

        if img.state == 'failed':
            print "AMI creation failed for instance: %s" % inst.tags['Name']
        elif img.state == 'pending':
            while True:
                if img.state == 'failed':
                    print "AMI creation failed for instance: %s" % inst.tags['Name']
                    break
                elif img.state == 'available':
                    print "AMI creation completed for instance: %s" % inst.tags['Name']
                    break
                else:
                    time.sleep(60)
                    img.update()