I'm working on a project to automate AMI creation. Requirement: 1. create an AMI 2. wait until the AMI created 3. break the loop if the AMI creation failed or success 4. repeat the procedure for all instances
we don't want to reboot the instance when we create the AMI.
Problem: script is not terminating inner while loop when i add the break statement to a if condition. can someone please help me to fix the code.
#!/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"
You need to update the state by calling img.update()
. State information doesn't automatically update. A call to AWS is only made in response to an boto API call.
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()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.