Delete VPC with all its resources

This commit is contained in:
JustFiesta 2024-05-22 15:54:19 +02:00
parent e9451c18ae
commit b91c2ddc9b

View file

@ -60,7 +60,38 @@ echo ""
# Deleting VPC # Deleting VPC
echo "Deleting VPCs..." echo "Deleting VPCs..."
for vpc_id in $(aws ec2 describe-vpcs --region "$REGION" --query "Vpcs[?Tags[?Key=='$TAG_KEY'&&Value=='$TAG_VALUE']].VpcId" --output text); do for vpc_id in $(aws ec2 describe-vpcs --region "$REGION" --query "Vpcs[?Tags[?Key=='$TAG_KEY'&&Value=='$TAG_VALUE']].VpcId" --output text); do
aws ec2 delete-vpc --region "$REGION" --vpc-id "$vpc_id" echo "Deleting VPC: $vpc_id..."
# Delete internet gateway
igw_id=$(aws ec2 describe-internet-gateways --region "$REGION" --filters "Name=attachment.vpc-id,Values=$vpc_id" --query "InternetGateways[].InternetGatewayId" --output text)
if [ -n "$igw_id" ]; then
aws ec2 detach-internet-gateway --internet-gateway-id "$igw_id" --vpc-id "$vpc_id" --region "$REGION"
aws ec2 delete-internet-gateway --internet-gateway-id "$igw_id" --region "$REGION"
fi
# Delete route table associations and route tables
for rtb_id in $(aws ec2 describe-route-tables --region "$REGION" --filters "Name=vpc-id,Values=$vpc_id" --query "RouteTables[].RouteTableId" --output text); do
aws ec2 disassociate-route-table --association-id "$(aws ec2 describe-route-tables --region "$REGION" --route-table-id "$rtb_id" --query "RouteTables[?VpcId=='$vpc_id'].Associations[].RouteTableAssociationId" --output text)" --region "$REGION"
aws ec2 delete-route-table --route-table-id "$rtb_id" --region "$REGION"
done
# Delete subnets
for subnet_id in $(aws ec2 describe-subnets --region "$REGION" --filters "Name=vpc-id,Values=$vpc_id" --query "Subnets[].SubnetId" --output text); do
aws ec2 delete-subnet --subnet-id "$subnet_id" --region "$REGION"
done
# Delete network ACLs
for nacl_id in $(aws ec2 describe-network-acls --region "$REGION" --filters "Name=vpc-id,Values=$vpc_id" --query "NetworkAcls[].NetworkAclId" --output text); do
aws ec2 delete-network-acl --network-acl-id "$nacl_id" --region "$REGION"
done
# Delete security groups
for sg_id in $(aws ec2 describe-security-groups --region "$REGION" --filters "Name=vpc-id,Values=$vpc_id" --query "SecurityGroups[].GroupId" --output text); do
aws ec2 delete-security-group --group-id "$sg_id" --region "$REGION"
done
# Finally, delete VPC
aws ec2 delete-vpc --vpc-id "$vpc_id" --region "$REGION"
if [ $? -eq 0 ]; then if [ $? -eq 0 ]; then
echo "VPC $vpc_id deleted successfully." echo "VPC $vpc_id deleted successfully."
else else