|
| 1 | +#!/usr/bin/env python3 |
| 2 | + |
| 3 | +import argparse |
| 4 | +import sys |
| 5 | +from typing import Iterable, List |
| 6 | + |
| 7 | +import boto3 |
| 8 | +from botocore.exceptions import ClientError |
| 9 | + |
| 10 | +ACTIVE_STATES = [ |
| 11 | + "pending", |
| 12 | + "running", |
| 13 | + "stopping", |
| 14 | + "stopped", |
| 15 | + "shutting-down", |
| 16 | +] |
| 17 | + |
| 18 | + |
| 19 | +def _chunked(items: List[str], size: int) -> Iterable[List[str]]: |
| 20 | + for start in range(0, len(items), size): |
| 21 | + yield items[start : start + size] |
| 22 | + |
| 23 | + |
| 24 | +def _collect_instance_ids(ec2_client, name_prefix: str) -> List[str]: |
| 25 | + paginator = ec2_client.get_paginator("describe_instances") |
| 26 | + filters = [ |
| 27 | + {"Name": "tag:Name", "Values": [f"{name_prefix}*"]}, |
| 28 | + {"Name": "instance-state-name", "Values": ACTIVE_STATES}, |
| 29 | + ] |
| 30 | + |
| 31 | + instance_ids: List[str] = [] |
| 32 | + for page in paginator.paginate(Filters=filters): |
| 33 | + for reservation in page.get("Reservations", []): |
| 34 | + for instance in reservation.get("Instances", []): |
| 35 | + instance_id = instance.get("InstanceId") |
| 36 | + if instance_id: |
| 37 | + instance_ids.append(instance_id) |
| 38 | + |
| 39 | + return instance_ids |
| 40 | + |
| 41 | + |
| 42 | +def _terminate_instances(ec2_client, instance_ids: List[str], dry_run: bool) -> None: |
| 43 | + if not instance_ids: |
| 44 | + print("No instances found to terminate.") |
| 45 | + return |
| 46 | + |
| 47 | + print(f"Found {len(instance_ids)} instance(s) to terminate.") |
| 48 | + for chunk in _chunked(instance_ids, 1000): |
| 49 | + try: |
| 50 | + ec2_client.terminate_instances(InstanceIds=chunk, DryRun=dry_run) |
| 51 | + if dry_run: |
| 52 | + print(f"Dry run succeeded for {len(chunk)} instance(s): {chunk}") |
| 53 | + else: |
| 54 | + print(f"Termination started for {len(chunk)} instance(s): {chunk}") |
| 55 | + except ClientError as exc: |
| 56 | + if dry_run and exc.response.get("Error", {}).get("Code") == "DryRunOperation": |
| 57 | + print(f"Dry run succeeded for {len(chunk)} instance(s): {chunk}") |
| 58 | + continue |
| 59 | + raise |
| 60 | + |
| 61 | + |
| 62 | +def main() -> int: |
| 63 | + parser = argparse.ArgumentParser( |
| 64 | + description="Terminate EC2 instances in a region whose Name tag starts with a prefix." |
| 65 | + ) |
| 66 | + parser.add_argument("--region", default="eu-west-1", help="AWS region (default: eu-west-1)") |
| 67 | + parser.add_argument( |
| 68 | + "--prefix", |
| 69 | + default="req-", |
| 70 | + help='Name tag prefix to match (default: "req-")', |
| 71 | + ) |
| 72 | + parser.add_argument( |
| 73 | + "--dry-run", |
| 74 | + action="store_true", |
| 75 | + help="Validate permissions without terminating instances.", |
| 76 | + ) |
| 77 | + args = parser.parse_args() |
| 78 | + |
| 79 | + session = boto3.session.Session() |
| 80 | + ec2_client = session.client("ec2", region_name=args.region) |
| 81 | + |
| 82 | + try: |
| 83 | + instance_ids = _collect_instance_ids(ec2_client, args.prefix) |
| 84 | + _terminate_instances(ec2_client, instance_ids, args.dry_run) |
| 85 | + except ClientError as exc: |
| 86 | + print(f"AWS error: {exc}", file=sys.stderr) |
| 87 | + return 1 |
| 88 | + |
| 89 | + return 0 |
| 90 | + |
| 91 | + |
| 92 | +if __name__ == "__main__": |
| 93 | + raise SystemExit(main()) |
0 commit comments