-
-
Save hyukishi/111973c407c9352b23f7cad863e529bd to your computer and use it in GitHub Desktop.
Digital Ocean floating IP gateway script (force droplet to use the assigned floating IP for outbound traffic as well as inbound traffic)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
# Force outbound traffic through the attached floating IP | |
# Script must be run as root | |
NET_INT="eth0" | |
CURL_TIMEOUT=3 | |
echo -n "Setting floating IP as the default gateway: " | |
# Check there's a floating IP attached to this droplet | |
if [ "$(curl -s --connect-timeout $CURL_TIMEOUT http://169.254.169.254/metadata/v1/floating_ip/ipv4/active)" != "true" ]; then | |
echo "Error: this droplet doesn't have a floating IP assigned to it." | |
exit 1 | |
fi | |
# Get the gateway IP for the floating IP | |
GATEWAY_IP=$(curl -s --connect-timeout $CURL_TIMEOUT http://169.254.169.254/metadata/v1/interfaces/public/0/anchor_ipv4/gateway) | |
if [ -z "$GATEWAY_IP" ]; then | |
echo "Error: failed getting gateway IP for this droplet." | |
exit 1 | |
fi | |
PHYS_GATEWAY=$(curl -s --connect-timeout $CURL_TIMEOUT http://169.254.169.254/metadata/v1/interfaces/public/0/ipv4/gateway) | |
if [ -z "$PHYS_GATEWAY" ]; then | |
echo "Error: failed getting physical gateway IP for this droplet." | |
exit 1 | |
fi | |
# Check we haven't already got the floating IP as a default gateway | |
if [ ! -z $(ip route ls 0/0|awk '{print $3}'|grep "$GATEWAY_IP") ]; then | |
echo "Error: gateway IP already a default route." | |
exit 1 | |
fi | |
# Add the new route with metric 100 before we remove any | |
ip route add default via $GATEWAY_IP dev $NET_INT metric 100 | |
# Delete any other default gatways for this interface | |
ip route ls 0/0 dev $NET_INT|awk '{print $3}'|grep -v "$GATEWAY_IP"|xargs -n1 -I{} ip route del default | |
# Add the physical gateway route with metric 101 | |
ip route add default via $PHYS_GATEWAY dev $NET_INT metric 101 | |
# Add route to DO metadata server via physical interface | |
ip route add 169.254.169.0/24 via $PHYS_GATEWAY dev $NET_INT | |
echo "Done." |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment