import boto3 import json def delete_security_group(ec2_client, security_group_id): ec2_client.revoke_security_group_ingress( GroupId=security_group_id, IpPermissions=[ { 'IpProtocol': 'tcp', 'FromPort': 22, 'ToPort': 22, 'IpRanges': [{'CidrIp': '0.0.0.0/0'}] }, { 'IpProtocol': 'tcp', 'FromPort': 8080, 'ToPort': 8080, 'IpRanges': [{'CidrIp': '0.0.0.0/0'}] } ] ) ec2_client.delete_security_group(GroupId=security_group_id) print(f"Security group {security_group_id} deleted.") def delete_key_pair(ec2_client, key_name): ec2_client.delete_key_pair(KeyName=key_name) print(f"Key pair {key_name} deleted.") def delete_instances(ec2_client, instance_ids): ec2_client.terminate_instances(InstanceIds=instance_ids) print(f"EC2 instances {instance_ids} terminated.") def delete_load_balancer(elbv2_client, load_balancer_arn): elbv2_client.delete_load_balancer(LoadBalancerArn=load_balancer_arn) print(f"Load Balancer {load_balancer_arn} deleted.") def delete_target_group(elbv2_client, target_group_arn): elbv2_client.delete_target_group(TargetGroupArn=target_group_arn) print(f"Target Group {target_group_arn} deleted.") def delete_internet_gateway(ec2_client, igw_id, vpc_id): ec2_client.detach_internet_gateway(InternetGatewayId=igw_id, VpcId=vpc_id) ec2_client.delete_internet_gateway(InternetGatewayId=igw_id) print(f"Internet Gateway {igw_id} deleted.") def delete_route_table(ec2_client, route_table_id): ec2_client.delete_route_table(RouteTableId=route_table_id) print(f"Route Table {route_table_id} deleted.") def delete_vpc(ec2_client, vpc_id): ec2_client.delete_vpc(VpcId=vpc_id) print(f"VPC {vpc_id} deleted.") def delete_subnet(ec2_client, subnet_id): ec2_client.delete_subnet(SubnetId=subnet_id) print(f"Subnet {subnet_id} deleted.") def delete_resources(ec2_client, elbv2_client, resources): delete_instances(ec2_client, resources["instance_ids"]) delete_load_balancer(elbv2_client, resources["load_balancer_arn"]) delete_target_group(elbv2_client, resources["target_group_arn"]) delete_security_group(ec2_client, resources["security_group_id"]) delete_key_pair(ec2_client, resources["key_name"]) delete_internet_gateway(ec2_client, resources["igw_id"], resources["vpc_id"]) delete_route_table(ec2_client, resources["route_table_id"]) delete_subnet(ec2_client, resources["subnet_id"]) delete_vpc(ec2_client, resources["vpc_id"]) def main(): with open("resources.json", "r") as file: resources = json.load(file) ec2_client = boto3.client("ec2") elbv2_client = boto3.client("elbv2") delete_resources(ec2_client, elbv2_client, resources) if __name__ == "__main__": main()