|
| 1 | +import click |
| 2 | +import boto3 |
| 3 | +from botocore.exceptions import NoCredentialsError, PartialCredentialsError |
| 4 | +from pathlib import Path |
| 5 | +import sys |
| 6 | + |
| 7 | +# Get current script directory |
| 8 | +currentdir = Path(__file__).resolve().parent |
| 9 | +# Get parent directory |
| 10 | +parentdir = currentdir.parent |
| 11 | +# Add parent directory to sys.path |
| 12 | +sys.path.insert(0, str(parentdir)) |
| 13 | + |
| 14 | +# import logger after specifying root/parent path |
| 15 | +import logger |
| 16 | + |
| 17 | +# ========== INITIALIZE AWS EC2 CLIENT |
| 18 | + |
| 19 | +def get_ec2_client(region=None): |
| 20 | + """ |
| 21 | + Returns a Boto3 EC2 client using the default profile. |
| 22 | + """ |
| 23 | + try: |
| 24 | + return boto3.client("ec2", region_name=region) |
| 25 | + except (NoCredentialsError, PartialCredentialsError) as e: |
| 26 | + logger.error(f"Error: {str(e)}") |
| 27 | + exit(1) |
| 28 | + |
| 29 | +# ========== EC2 INSTANCE CLEANER |
| 30 | + |
| 31 | +def clean_unused_instances(ec2_client): |
| 32 | + """ |
| 33 | + Find and terminate unused EC2 instances. |
| 34 | + """ |
| 35 | + logger.info("\n==================== EC2 INSTANCE CLEANUP") |
| 36 | + instances = ec2_client.describe_instances() |
| 37 | + terminated_instances = [] |
| 38 | + |
| 39 | + total_instances = 0 |
| 40 | + for reservation in instances["Reservations"]: |
| 41 | + for instance in reservation["Instances"]: |
| 42 | + instance_id = instance["InstanceId"] |
| 43 | + state = instance["State"]["Name"] |
| 44 | + launch_time = instance["LaunchTime"] |
| 45 | + |
| 46 | + total_instances += 1 |
| 47 | + # Display instance details |
| 48 | + click.echo(f"\n===== INSTANCE: {total_instances}") |
| 49 | + click.echo(f"Instance ID: {instance_id}") |
| 50 | + click.echo(f"State : {state}") |
| 51 | + click.echo(f"Launch time: {launch_time.strftime('%Y-%m-%d %H:%M:%S')}") |
| 52 | + |
| 53 | + if state == "stopped": |
| 54 | + click.echo(f"Status: {state} - Terminating instance...") |
| 55 | + ec2_client.terminate_instances(InstanceIds=[instance_id]) |
| 56 | + terminated_instances.append(instance_id) |
| 57 | + else: |
| 58 | + click.echo(f"Status: {state} - No action needed.") |
| 59 | + |
| 60 | + if terminated_instances: |
| 61 | + logger.info(f"\nTerminated instances: {', '.join(terminated_instances)}") |
| 62 | + else: |
| 63 | + logger.info("\nNo stopped instances to terminate.") |
| 64 | + |
| 65 | +# ========== CLEAN UNUSED VOLUMES |
| 66 | + |
| 67 | +def clean_unused_volumes(ec2_client): |
| 68 | + """ |
| 69 | + Find and delete unused EC2 volumes. |
| 70 | + """ |
| 71 | + click.echo("\n==================== EC2 VOLUME CLEANUP") |
| 72 | + volumes = ec2_client.describe_volumes() |
| 73 | + deleted_volumes = [] |
| 74 | + |
| 75 | + total_volumes = 0 |
| 76 | + for volume in volumes['Volumes']: |
| 77 | + volume_id = volume['VolumeId'] |
| 78 | + state = volume['State'] |
| 79 | + attachment_state = volume.get('Attachments', []) |
| 80 | + creation_time = volume['CreateTime'] |
| 81 | + |
| 82 | + total_volumes += 1 |
| 83 | + # Display instance details |
| 84 | + click.echo(f"\n===== INSTANCE: {total_volumes}") |
| 85 | + # Display volume details |
| 86 | + click.echo(f"Volume ID : {volume_id}") |
| 87 | + click.echo(f"State : {state}") |
| 88 | + click.echo(f"Created on : {creation_time.strftime('%Y-%m-%d %H:%M:%S')}") |
| 89 | + if attachment_state: |
| 90 | + click.echo(f"Attached to : {', '.join([attachment['InstanceId'] for attachment in attachment_state])}") |
| 91 | + else: |
| 92 | + click.echo("Attached to : None (Unattached)") |
| 93 | + |
| 94 | + if state == 'available' and not attachment_state: |
| 95 | + click.echo(f"Status: Unattached — Deleting this volume...") |
| 96 | + ec2_client.delete_volume(VolumeId=volume_id) |
| 97 | + deleted_volumes.append(volume_id) |
| 98 | + else: |
| 99 | + click.echo(f"Status: In Use — No action needed.") |
| 100 | + |
| 101 | + if deleted_volumes: |
| 102 | + click.echo(f"\nDeleted volumes: {', '.join(deleted_volumes)}\n") |
| 103 | + else: |
| 104 | + click.echo("\nNo unattached volumes to delete.\n") |
| 105 | + |
| 106 | +# ========== CLICK GROUP |
| 107 | + |
| 108 | +@click.group(help="A group of commands for EC2 instance cleanup") |
| 109 | +def ec2_cleaner(): |
| 110 | + """ |
| 111 | + A group of commands for terminating EC2 instances & volumes. |
| 112 | + """ |
| 113 | + pass |
| 114 | + |
| 115 | + |
| 116 | +@ec2_cleaner.command() |
| 117 | +@click.option('--region', default=None, help='AWS region to target (default is configured region)') |
| 118 | +def clean_instances(region): |
| 119 | + """ |
| 120 | + Find and terminate unused EC2 instances. |
| 121 | + """ |
| 122 | + ec2_client = get_ec2_client(region) |
| 123 | + clean_unused_instances(ec2_client) |
| 124 | + |
| 125 | + |
| 126 | +@ec2_cleaner.command() |
| 127 | +@click.option('--region', default=None, help='AWS region to target (default is configured region)') |
| 128 | +def clean_volumes(region): |
| 129 | + """ |
| 130 | + Find and delete unused EC2 volumes. |
| 131 | + """ |
| 132 | + ec2_client = get_ec2_client(region) |
| 133 | + clean_unused_volumes(ec2_client) |
| 134 | + |
| 135 | + |
| 136 | +@ec2_cleaner.command() |
| 137 | +@click.option('--region', default=None, help='AWS region to target (default is configured region)') |
| 138 | +def clean_all(region): |
| 139 | + """ |
| 140 | + Clean both unused EC2 instances and volumes. |
| 141 | + """ |
| 142 | + ec2_client = get_ec2_client(region) |
| 143 | + clean_unused_instances(ec2_client) |
| 144 | + clean_unused_volumes(ec2_client) |
| 145 | + |
| 146 | + |
| 147 | +# if this script is run directly, invoke the 'ec2_cleaner' group |
| 148 | +if __name__ == "__main__": |
| 149 | + ec2_cleaner() |
0 commit comments