def test_deletion(): """ Test deletion methods """ base_ami = "ami-1234abcd" parser = parse_args( [ '--keep-previous', '0', '--mapping-key', 'name', '--mapping-values', 'test-ami'] ) ec2 = boto3.client('ec2') reservation = ec2.run_instances( ImageId=base_ami, MinCount=1, MaxCount=1 ) instance = reservation["Instances"][0] # create amis images = [] for i in range(5): image = ec2.create_image( InstanceId=instance.get("InstanceId"), Name="test-ami" ) images.append(image.get("ImageId")) # delete one AMI by id app = App(parser) asg = boto3.client('autoscaling') f = Fetcher(ec2=ec2, autoscaling=asg) assert len(f.fetch_available_amis()) == 5 assert app.prepare_delete_amis( candidates=[images[4]], from_ids=True ) is None assert len(f.fetch_available_amis()) == 4 # delete with mapping strategy candidates = app.prepare_candidates() assert len(candidates) == 4 assert app.prepare_delete_amis(candidates) is None assert len(f.fetch_available_amis()) == 0
def fetch_candidates(self, available_amis=None, excluded_amis=None): """ Collects created AMIs, AMIs from ec2 instances, launch configurations, autoscaling groups and returns unused AMIs. """ f = Fetcher() available_amis = available_amis or f.fetch_available_amis() excluded_amis = excluded_amis or [] if not excluded_amis: excluded_amis += f.fetch_unattached_lc() excluded_amis += f.fetch_zeroed_asg() excluded_amis += f.fetch_instances() candidates = [v for k, v in available_amis.items() if k not in excluded_amis] return candidates