|
| 1 | +import boto3 |
| 2 | +import argparse |
| 3 | +import datetime |
| 4 | +import sys |
| 5 | + |
| 6 | +# Create an EC2 client |
| 7 | +ec2 = boto3.client('ec2') |
| 8 | + |
| 9 | +def delete_unused_ebs(file_name=None): |
| 10 | + # Get the list of all EBS Volumes |
| 11 | + try: |
| 12 | + response = ec2.describe_volumes() |
| 13 | + except Exception as e: |
| 14 | + print(f'Error getting the list of EBS Volumes: {e}') |
| 15 | + return |
| 16 | + |
| 17 | + # Loop through the list of volumes and check for any unused volumes |
| 18 | + for volume in response['Volumes']: |
| 19 | + if volume['State'] == 'available' and not volume['Attachments']: |
| 20 | + volume_id = volume["VolumeId"] |
| 21 | + try: |
| 22 | + snapshot = input(f'Do you want to take a snapshot of volume {volume_id} before deleting? (y/n)') |
| 23 | + if snapshot.lower() == 'y': |
| 24 | + # Take a EBS snapshot |
| 25 | + ec2.create_snapshot(VolumeId=volume_id,Description=f'Snapshot of the volume {volume_id} taken on {datetime.datetime.now()}') |
| 26 | + print(f'Creating the Snapshot of volume {volume_id}') |
| 27 | + |
| 28 | + print(f'Deleting unused EBS Volume: {volume_id}') |
| 29 | + ec2.delete_volume(VolumeId=volume_id) |
| 30 | + except Exception as e: |
| 31 | + print(f'Error deleting EBS volume {volume_id}: {e}') |
| 32 | + |
| 33 | + # Check the condition to see if the filename is provided and read the ebs volume from the file |
| 34 | + |
| 35 | + if file_name is not None: |
| 36 | + try: |
| 37 | + with open(file_name, 'r') as f: |
| 38 | + volume_ids = f.read().splitlines() |
| 39 | + for volume_id in volume_ids: |
| 40 | + snapshot = input(f'Do you want to take a snapshot of volume {volume_id} before deleting? (y/n)') |
| 41 | + if snapshot.lower() == 'y': |
| 42 | + # Take a EBS snapshot |
| 43 | + ec2.create_snapshot(VolumeId=volume_id,Description=f'Snapshot of the volume {volume_id} taken on {datetime.datetime.now()}') |
| 44 | + print(f'Creating the Snapshot of volume {volume_id}') |
| 45 | + |
| 46 | + print(f'Deleting unused EBS Volume: {volume_id}') |
| 47 | + ec2.delete_volume(VolumeId=volume_id) |
| 48 | + except Exception as e: |
| 49 | + print(f'Error deleting EBS volume {volume_id}: {e}') |
| 50 | + |
| 51 | +if __name__ == '__main__': |
| 52 | + parser = argparse.ArgumentParser() |
| 53 | + parser.add_argument('-f', '--file', help='Name of the file that contains the list of unused volumes') |
| 54 | + try: |
| 55 | + args = parser.parse_args() |
| 56 | + delete_unused_ebs() |
| 57 | + sys.exit() |
| 58 | + except Exception as e: |
| 59 | + print("An error occurred while parsing the arguments:", e) |
0 commit comments