Skip to content

Commit

Permalink
unused aws instace and vpcs cleanup
Browse files Browse the repository at this point in the history
Signed-off-by: shiva kumar <shivaku@nvidia.com>
  • Loading branch information
shivakunv committed Dec 17, 2024
1 parent 3d11f8c commit 6062838
Showing 1 changed file with 26 additions and 10 deletions.
36 changes: 26 additions & 10 deletions scripts/awsvpcscleanup.sh
Original file line number Diff line number Diff line change
Expand Up @@ -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 \
Expand All @@ -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"
Expand Down

0 comments on commit 6062838

Please sign in to comment.