diff --git a/scripts/awsvpcscleanup.sh b/scripts/awsvpcscleanup.sh index 6ab877a2..04ce69e0 100755 --- a/scripts/awsvpcscleanup.sh +++ b/scripts/awsvpcscleanup.sh @@ -40,6 +40,32 @@ for eip in $eips; do aws ec2 release-address --allocation-id "$eip" done +# Detach and Delete Security Groups +security_groups=$(aws ec2 describe-security-groups \ + --filters Name=vpc-id,Values=$vpc_id \ + --query "SecurityGroups[?GroupName!='default'].GroupId" \ + --output text | tr -d '\r' | tr '\n' ' ') + +for sg in $security_groups; do + echo "Processing security group: $sg" + # Check and detach associated ENIs (Elastic Network Interfaces) + enis=$(aws ec2 describe-network-interfaces \ + --filters Name=group-id,Values=$sg \ + --query "NetworkInterfaces[].NetworkInterfaceId" \ + --output text | tr -d '\r' | tr '\n' ' ') + for eni in $enis; do + echo "Detaching security group from network interface: $eni" + aws ec2 modify-network-interface-attribute \ + --network-interface-id "$eni" \ + --groups "$(aws ec2 describe-security-groups \ + --query 'SecurityGroups[?GroupName==`default`].GroupId' \ + --output text)" + done + # Delete the security group + echo "Deleting security group: $sg" + aws ec2 delete-security-group --group-id "$sg" +done + # Delete Route Tables route_tables=$(aws ec2 describe-route-tables \ --filters Name=vpc-id,Values=$vpc \ @@ -51,16 +77,6 @@ for rt in $route_tables; do --route-table-ids "$rt" \ --query "RouteTables[0].Associations[]" \ --output json) - - # Check if it's the main route table - is_main=$(echo "$associations" | jq -r '.[] | select(.Main==true) | .RouteTableAssociationId') - - if [ -n "$is_main" ]; then - echo "Skipping main route table: $rt (Association ID: $is_main)" - continue - fi - - # Disassociate all non-main associations for assoc in $(echo "$associations" | jq -r '.[] | select(.Main==false) | .RouteTableAssociationId'); do echo "Disassociating route table association: $assoc" aws ec2 disassociate-route-table --association-id "$assoc"