Python boto ec2 - How do I wait till an image is created or failed
Question: I am writing a code to iterate through all available instances and create an
AMI for them as below:

    
    
    for reservation in reservations:
        ......
        ami_id = ec2_conn.create_image(instance.id, ami_name, description=ami_desc, no_reboot=True)
    

But how do I wait till an image is created before proceeding with the creation
of next image? Because I need to track the status of each ami created.

I know that I can retrieve the state using:

    
    
    image_status = get_image(ami_id).state
    

So, do I iterate through the list of ami_ids created and then fetch the state
for each of them? If so, then what if the image is still pending when I read
the state of the image? How will I find out if the image creation has failed
eventually?

Thanks.


Answer: If I understand correctly, you want to initiate the `create_image` call and
then wait until the server-side operation completes before moving on. To do
this, you have to poll the EC2 service periodically until the state of the
image is either `available` (meaning it succeeded) or `failed` (meaning it
failed). The code would look something like this:

    
    
    import time
    ...
    image_id = ec2_conn.create_image(instance.id, ...)
    image = ec2_conn.get_all_images(image_ids=[image_id])[0]
    while image.state == 'pending':
        time.sleep(5)
        image.update()
    if image.state == 'available':
        # success, do something here
    else:
        # handle failure here
    

