UPD: simplified script

This commit is contained in:
xpk 2022-08-05 15:40:04 +08:00
parent 6044f17540
commit d64630e924
Signed by: xpk
GPG Key ID: CD4FF6793F09AB86

View File

@ -1,38 +1,25 @@
#!/bin/bash #!/bin/bash
region=$1 region=$1
vpc=$(aws ec2 --region ${region} \ vpc=$(aws ec2 --region ${region} describe-vpcs --filter Name=isDefault,Values=true | jq -r .Vpcs[0].VpcId)
describe-vpcs --filter Name=isDefault,Values=true \
| jq -r .Vpcs[0].VpcId)
if [ "${vpc}" = "null" ]; then if [ "${vpc}" = "null" ]; then
echo "No default vpc found" echo "No default vpc found"
exit 0 exit 0
fi fi
igw=$(aws ec2 --region ${region} \ aws ec2 --region ${region} describe-internet-gateways --filter Name=attachment.vpc-id,Values=${vpc}
describe-internet-gateways --filter Name=attachment.vpc-id,Values=${vpc} \ | jq -r .InternetGateways[0].InternetGatewayId | while read igw; do
| jq -r .InternetGateways[0].InternetGatewayId) echo "Removing internet gateway ${igw}"
if [ "${igw}" != "null" ]; then aws ec2 --region ${region} detach-internet-gateway --internet-gateway-id ${igw} --vpc-id ${vpc}
echo "Detaching and deleting internet gateway ${igw}" aws ec2 --region ${region} delete-internet-gateway --internet-gateway-id ${igw}
aws ec2 --region ${region} \ done
detach-internet-gateway --internet-gateway-id ${igw} --vpc-id ${vpc}
aws ec2 --region ${region} \
delete-internet-gateway --internet-gateway-id ${igw}
fi
subnets=$(aws ec2 --region ${region} \ aws ec2 --region ${region} describe-subnets --filters Name=vpc-id,Values=${vpc} | jq -r .Subnets[].SubnetId) | while read subnet; do
describe-subnets --filters Name=vpc-id,Values=${vpc} \ echo "Removing subnet ${subnet}"
| jq -r .Subnets[].SubnetId) aws ec2 --region ${region} delete-subnet --subnet-id ${subnet}
if [ "${subnets}" != "null" ]; then done
for subnet in ${subnets}; do
echo "Deleting subnet ${subnet}"
aws ec2 --region ${region} \
delete-subnet --subnet-id ${subnet}
done
fi
echo "Deleting vpc ${vpc}" echo "Removing vpc ${vpc}"
aws ec2 --region ${region} \ aws ec2 --region ${region} delete-vpc --vpc-id ${vpc}
delete-vpc --vpc-id ${vpc}