Skip to content

Commit

Permalink
Merge pull request #447 from jyejare/ec2_cleanup
Browse files Browse the repository at this point in the history
EC2: Remove all unused Volumes, IPs and NICs from a region
  • Loading branch information
mshriver authored Jun 10, 2021
2 parents c8524ff + 3d932f5 commit bd5481d
Showing 1 changed file with 55 additions and 0 deletions.
55 changes: 55 additions & 0 deletions wrapanapi/systems/ec2.py
Original file line number Diff line number Diff line change
Expand Up @@ -1540,3 +1540,58 @@ def create_image_from_snapshot(self, name, snapshot_id, architecture='x86_64', e
except Exception:
self.logger.exception("Creation of image from snapshot '%s' failed.", snapshot_id)
return False

def remove_network_interface_by_id(self, nic_id):
try:
self.ec2_connection.delete_network_interface(NetworkInterfaceId=nic_id)
return True
except Exception:
self.logger.exception(f"Removal of Network interface id {nic_id} failed.")
return False

def remove_volume_by_id(self, volume_id):
try:
self.ec2_connection.delete_volume(VolumeId=volume_id)
return True
except Exception:
self.logger.exception(f"Removal of Volume by id {volume_id} failed.")
return False

def remove_all_unused_nics(self):
"""
Remove all unused Network interfaces in given region
Returns: None
"""
all_unused_nics = self.get_all_unused_network_interfaces()
for nic in all_unused_nics:
self.remove_network_interface_by_id(nic_id=nic['NetworkInterfaceId'])

def remove_all_unused_volumes(self):
"""
Remove all unused Volumes in given region
Returns: None
"""
all_unused_volumes = self.get_all_unattached_volumes()
for volume in all_unused_volumes:
self.remove_volume_by_id(volume_id=volume['VolumeId'])

def remove_all_unused_ips(self):
"""
Remove all disassociated addresses in given region
Returns: None
"""
all_unused_ips = self.get_all_disassociated_addresses()
for ip in all_unused_ips:
self.release_vpc_address(alloc_id=ip['AllocationId'])

def cleanup_resources(self):
"""
Removes all unused NICs, Volumes and IP addresses
"""
self.logger.info("cleanup: Removing all unused NICs/Volumes/IPs in resource group")
self.remove_all_unused_nics()
self.remove_all_unused_volumes()
self.remove_all_unused_ips()

0 comments on commit bd5481d

Please sign in to comment.