juanesech
7/11/2018 - 4:05 PM

Delete Default Route Table

#!/bin/bash

#Parameters
vpcName=$1
AWS_DEFAULT_REGION=$2
AWS_ACCESS_KEY_ID=$3
AWS_SECRET_ACCESS_KEY=$4

export AWS_DEFAULT_REGION AWS_ACCESS_KEY_ID AWS_SECRET_ACCESS_KEY

#Get IDs
vpcId=$(aws ec2 describe-vpcs --filters Name=tag-value,Values=$vpcName --query 'Vpcs[*].VpcId' --output text)
echo "VPC ID: "$vpcId

rtId=$(aws ec2 describe-route-tables --filters "Name=vpc-id,Values=$vpcId" --query 'RouteTables[?!not_null(Tags[?Key == `Name`].Value)].{id: RouteTableId}' --output text)
if [[ $rtId ]]; then
  echo "Default Route Table ID: "$rtId

  associationId=$(aws ec2 describe-route-tables --filters "Name=vpc-id,Values=$vpcId" --query 'RouteTables[?Associations[0].Main == `true`].{id: Associations[0].RouteTableAssociationId}' --output text)
  echo "Association ID: "$associationId

  rTables=$(aws ec2 describe-route-tables --filters "Name=vpc-id,Values=$vpcId" --query 'RouteTables[?not_null(Tags[?Key == `Name`].Value)].{id: RouteTableId}' --output text)
  rTableMain=$(echo $rTables |awk 'BEGIN { FS = " " } ; { print $1 }')
  echo "Main Route Rables ID: " $rTableMain

  #Replace Main Rute Table
  aws ec2 replace-route-table-association --association-id $associationId --route-table-id $rTableMain --output text

  #Delete Route Table
  aws ec2 delete-route-table --route-table-id $rtId
fi