Beispiel #1
0
def deregister_image(module, ec2):
    """
    Deregisters AMI
    """

    image_id = module.params.get('image_id')
    delete_snapshot = module.params.get('delete_snapshot')
    wait = module.params.get('wait')
    wait_timeout = int(module.params.get('wait_timeout'))

    img = ec2.get_image(image_id)
    if img is None:
        module.fail_json(msg="Image %s does not exist" % image_id,
                         changed=False)

    # Get all associated snapshot ids before deregistering image otherwise this information becomes unavailable
    snapshots = []
    if hasattr(img, 'block_device_mapping'):
        for key in img.block_device_mapping:
            snapshots.append(img.block_device_mapping[key].snapshot_id)

    # When trying to re-delete already deleted image it doesn't raise an exception
    # It just returns an object without image attributes
    if hasattr(img, 'id'):
        try:
            params = {'image_id': image_id, 'delete_snapshot': delete_snapshot}
            ec2.deregister_image(**params)
        except boto.exception.BotoServerError as e:
            module.fail_json(msg="%s: %s" % (e.error_code, e.error_message))
    else:
        module.exit_json(msg="Image %s has already been deleted" % image_id,
                         changed=False)

    # wait here until the image is gone
    img = ec2.get_image(image_id)
    wait_timeout = time.time() + wait_timeout
    while wait and wait_timeout > time.time() and img is not None:
        img = ec2.get_image(image_id)
        time.sleep(3)
    if wait and wait_timeout <= time.time():
        # waiting took too long
        module.fail_json(
            msg="timed out waiting for image to be deregistered/deleted")

    # Boto library has hardcoded the deletion of the snapshot for the root volume mounted as '/dev/sda1' only
    # Make it possible to delete all snapshots which belong to image, including root block device mapped as '/dev/xvda'
    if delete_snapshot:
        try:
            for snapshot_id in snapshots:
                ec2.delete_snapshot(snapshot_id)
        except boto.exception.BotoServerError as e:
            if e.error_code == 'InvalidSnapshot.NotFound':
                # Don't error out if root volume snapshot was already deleted as part of deregister_image
                pass
        module.exit_json(msg="AMI deregister/delete operation complete",
                         changed=True,
                         snapshots_deleted=snapshots)
    else:
        module.exit_json(msg="AMI deregister/delete operation complete",
                         changed=True)
Beispiel #2
0
def ec2_deregister_ami(ec2):
	images = ec2.get_all_images(owners="self")
	for i in images:
		try:
			print "---Deregistering AMI: " + i.id
			ec2.deregister_image(i.id, delete_snapshot=True)
		except Exception, e:
			print(e)
Beispiel #3
0
def deregister_image(module, ec2):
    """
    Deregisters AMI
    """

    image_id = module.params.get('image_id')
    delete_snapshot = module.params.get('delete_snapshot')
    wait = module.params.get('wait')
    wait_timeout = int(module.params.get('wait_timeout'))

    img = ec2.get_image(image_id)
    if img is None:
        module.fail_json(msg="Image %s does not exist" % image_id, changed=False)

    # Get all associated snapshot ids before deregistering image otherwise this information becomes unavailable
    snapshots = []
    if hasattr(img, 'block_device_mapping'):
        for key in img.block_device_mapping:
            snapshots.append(img.block_device_mapping[key].snapshot_id)

    # When trying to re-delete already deleted image it doesn't raise an exception
    # It just returns an object without image attributes
    if hasattr(img, 'id'):
        try:
            params = {'image_id': image_id,
                      'delete_snapshot': delete_snapshot}
            ec2.deregister_image(**params)
        except boto.exception.BotoServerError as e:
            module.fail_json(msg="%s: %s" % (e.error_code, e.error_message))
    else:
        module.exit_json(msg="Image %s has already been deleted" % image_id, changed=False)

    # wait here until the image is gone
    img = ec2.get_image(image_id)
    wait_timeout = time.time() + wait_timeout
    while wait and wait_timeout > time.time() and img is not None:
        img = ec2.get_image(image_id)
        time.sleep(3)
    if wait and wait_timeout <= time.time():
        # waiting took too long
        module.fail_json(msg="timed out waiting for image to be deregistered/deleted")

    # Boto library has hardcoded the deletion of the snapshot for the root volume mounted as '/dev/sda1' only
    # Make it possible to delete all snapshots which belong to image, including root block device mapped as '/dev/xvda'
    if delete_snapshot:
        try:
            for snapshot_id in snapshots:
                ec2.delete_snapshot(snapshot_id)
        except boto.exception.BotoServerError as e:
            if e.error_code == 'InvalidSnapshot.NotFound':
                # Don't error out if root volume snapshot was already deleted as part of deregister_image
                pass
        module.exit_json(msg="AMI deregister/delete operation complete", changed=True, snapshots_deleted=snapshots)
    else:
        module.exit_json(msg="AMI deregister/delete operation complete", changed=True)
Beispiel #4
0
def deregister_image(module, ec2):
    """
    Deregisters AMI
    """

    image_id = module.params.get('image_id')
    delete_snapshot = module.params.get('delete_snapshot')
    wait = module.params.get('wait')
    wait_timeout = int(module.params.get('wait_timeout'))

    img = ec2.get_image(image_id)
    if img == None:
        module.fail_json(msg="Image %s does not exist" % image_id,
                         changed=False)

    # Get all associated snapshot ids before deregistering image otherwise this information becomes unavailable
    snapshots = []
    if hasattr(img, 'block_device_mapping'):
        for key in img.block_device_mapping:
            snapshots.append(img.block_device_mapping[key].snapshot_id)

    # When trying to re-delete already deleted image it doesn't raise an exception
    # It just returns an object without image attributes
    if hasattr(img, 'id'):
        try:
            params = {'image_id': image_id, 'delete_snapshot': delete_snapshot}
            res = ec2.deregister_image(**params)
        except boto.exception.BotoServerError, e:
            module.fail_json(msg="%s: %s" % (e.error_code, e.error_message))
def deregister_image(module, ec2):
    """
    Deregisters AMI
    """

    image_id = module.params.get('image_id')
    delete_snapshot = module.params.get('delete_snapshot')
    wait = module.params.get('wait')
    wait_timeout = int(module.params.get('wait_timeout'))

    img = ec2.get_image(image_id)
    if img == None:
        module.fail_json(msg = "Image %s does not exist" % image_id, changed=False)

    try:
        params = {'image_id': image_id,
                  'delete_snapshot': delete_snapshot}

        res = ec2.deregister_image(**params)
    except boto.exception.BotoServerError, e:
        module.fail_json(msg = "%s: %s" % (e.error_code, e.error_message))
Beispiel #6
0
def deregister_image(module, ec2):
    """
    Deregisters AMI
    """

    image_id = module.params.get('image_id')
    delete_snapshot = module.params.get('delete_snapshot')
    wait = module.params.get('wait')
    wait_timeout = int(module.params.get('wait_timeout'))

    img = ec2.get_image(image_id)
    if img == None:
        module.fail_json(msg = "Image %s does not exist" % image_id, changed=False)

    try:
        params = {'image_id': image_id,
                  'delete_snapshot': delete_snapshot}

        res = ec2.deregister_image(**params)
    except boto.exception.BotoServerError, e:
        module.fail_json(msg = "%s: %s" % (e.error_code, e.error_message))
Beispiel #7
0
parser = argparse.ArgumentParser(description='Deregister EC2 images in all/some available EC2 regions',
                                 parents=[bc.build_region_parser(), bc.build_filter_parser('EC2 image'), bc.build_common_parser()])
args = parser.parse_args()

# process common command line arguments
log = logging.getLogger('botocross')
bc.configure_logging(log, args.log_level)
credentials = bc.parse_credentials(args)
regions = bc.filter_regions(boto.ec2.regions(), args.region)
filter = bc.build_filter(args.filter, args.exclude)
log.info(args.resource_ids)

# execute business logic
log.info("Deregistering EC2 images")

for region in regions:
    try:
        ec2 = boto.connect_ec2(region=region, **credentials)
        images = ec2.get_all_images(image_ids=args.resource_ids, owners=['self'], filters=filter['filters'])
        if filter['excludes']:
            exclusions = ec2.get_all_images(owners=['self'], filters=filter['excludes'])
            images = bc.filter_list_by_attribute(images, exclusions, 'id')
        print region.name + ": " + str(len(images)) + " EC2 images"
        for image in images:
            if args.verbose:
                print image.id
            else:
                ec2.deregister_image(image.id, delete_snapshot=True)
    except boto.exception.BotoServerError, e:
        log.error(e.error_message)