From d8f9c221ede6d67a251134989a30bb850f8709e6 Mon Sep 17 00:00:00 2001 From: Michael Brown Date: Tue, 7 Nov 2023 15:54:59 +0000 Subject: [cloud] Add ability to overwrite existing AMI images AMI names must be unique within a region. Add a --overwrite option that allows an existing AMI of the same name to be deregistered (and its underlying snapshot deleted). Signed-off-by: Michael Brown --- contrib/cloud/aws-import | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-) diff --git a/contrib/cloud/aws-import b/contrib/cloud/aws-import index b9a350f..ace0058 100755 --- a/contrib/cloud/aws-import +++ b/contrib/cloud/aws-import @@ -46,11 +46,19 @@ def create_snapshot(region, description, image): return snapshot_id -def import_image(region, name, architecture, image, public): +def import_image(region, name, architecture, image, public, overwrite): """Import an AMI image""" client = boto3.client('ec2', region_name=region) resource = boto3.resource('ec2', region_name=region) description = '%s (%s)' % (name, architecture) + images = client.describe_images(Filters=[{'Name': 'name', + 'Values': [description]}]) + if overwrite and images['Images']: + images = images['Images'][0] + image_id = images['ImageId'] + snapshot_id = images['BlockDeviceMappings'][0]['Ebs']['SnapshotId'] + resource.Image(image_id).deregister() + resource.Snapshot(snapshot_id).delete() snapshot_id = create_snapshot(region=region, description=description, image=image) client.get_waiter('snapshot_completed').wait(SnapshotIds=[snapshot_id]) @@ -88,6 +96,8 @@ parser.add_argument('--name', '-n', help="Image name") parser.add_argument('--public', '-p', action='store_true', help="Make image public") +parser.add_argument('--overwrite', action='store_true', + help="Overwrite any existing image with same name") parser.add_argument('--region', '-r', action='append', help="AWS region(s)") parser.add_argument('--wiki', '-w', metavar='FILE', @@ -115,7 +125,8 @@ with ThreadPoolExecutor(max_workers=len(imports)) as executor: name=args.name, architecture=architectures[image], image=image, - public=args.public): (region, image) + public=args.public, + overwrite=args.overwrite): (region, image) for region, image in imports} results = {futures[future]: future.result() for future in as_completed(futures)} -- cgit v1.1