Skip to content

Instantly share code, notes, and snippets.

@damonsmith
Last active March 9, 2020 05:45
Show Gist options
  • Save damonsmith/cc22e0220950163dc62e161162caee54 to your computer and use it in GitHub Desktop.
Save damonsmith/cc22e0220950163dc62e161162caee54 to your computer and use it in GitHub Desktop.
#!/bin/bash
MAC_ADDRESS=`curl http://169.254.169.254/latest/meta-data/network/interfaces/macs/`
VPC_ID=`curl http://169.254.169.254/latest/meta-data/network/interfaces/macs/${MAC_ADDRESS:-1}/vpc-id`
INSTANCE_ID=`curl http://169.254.169.254/latest/meta-data/instance-id`
REGION=`curl http://169.254.169.254/latest/dynamic/instance-identity/document|grep region|awk -F\" '{print $4}'`
TAG_KEY="Reach"
TAG_VALUE="private"
ROUTE_TABLES=`aws ec2 describe-route-tables --filters "Name=tag:$TAG_KEY,Values=$TAG_VALUE" --region $REGION --output text | grep ROUTETABLES | grep $VPC_ID | awk '{print $3}'`
for ROUTE_TABLE in $ROUTE_TABLES
do
TARGET=`aws ec2 describe-route-tables --filters "Name=route-table-id,Values=$ROUTE_TABLE" --region $REGION --output text | grep "0.0.0.0/0" | awk '{print $3}'`
echo "Checking $ROUTE_TABLE"
if [ "$TARGET" = "" ]; then
echo "No default route is detected. Creating default route for $ROUTE_TABLE"
aws ec2 create-route --route-table-id $ROUTE_TABLE --destination-cidr-block 0.0.0.0/0 --instance-id $INSTANCE_ID --region $REGION
elif [ "$TARGET" != "$INSTANCE_ID" ]; then
echo "Default route is set to $TARGET. Replacing default route to $INSTANCE_ID"
aws ec2 replace-route --route-table-id $ROUTE_TABLE --destination-cidr-block 0.0.0.0/0 --instance-id $INSTANCE_ID --region $REGION
else
echo "No change is required"
fi
done
aws ec2 modify-instance-attribute --instance-id $INSTANCE_ID --no-source-dest-check --region $REGION
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment