Forked from sparkcodeuk/floating-ip-gateway.sh
Last active
February 10, 2022 09:09
-
-
Save Sugavanas/39d9c223350a637aa0c7c2c1e25bad7f 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 forked script will revert back to original settings. Pass the original IP address of the droplet as the first parameter.
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 | |
# Revert outbound traffic back to original ip. Call script with the original ip address of droplet | |
NET_INT="eth0" | |
CURL_TIMEOUT=3 | |
if [ "$1" == "" ]; then | |
echo "Original IP of droplet not given." | |
exit 1 | |
fi | |
DROPLET_IP_ADDRESS = $1 | |
echo $'Original Droplet IP: ' $DROPLET_IP_ADDRESS $'\n' | |
echo $'\nSetting original droplet IP as the default gateway: ' | |
# Check there's a floating IP attached to this droplet | |
if [ "$(curl -s --interface $DROPLET_IP_ADDRESS --connect-timeout $CURL_TIMEOUT http://169.254.169.254/metadata/v1/floating_ip/ipv4/active)" != "true" ]; then | |
echo $'\nError: this droplet doesn\'t have a floating IP assigned to it.' | |
exit 1 | |
fi | |
# Get the gateway IP for the original IP | |
GATEWAY_IP=$(curl -s --interface $DROPLET_IP_ADDRESS --connect-timeout $CURL_TIMEOUT http://169.254.169.254/metadata/v1/interfaces/public/0/ipv4/gateway) | |
if [ -z "$GATEWAY_IP" ]; then | |
echo $'\nError: failed getting gateway IP for this droplet.' | |
exit 1 | |
fi | |
# Check the original gateway isn't already the default | |
if [ ! -z $(ip route ls 0/0|awk '{print $3}'|grep "$GATEWAY_IP") ]; then | |
echo $'\nError: default gateway IP already a default route.' | |
exit 1 | |
fi | |
# Add the new route before we remove any | |
sudo route add default gw $GATEWAY_IP $NET_INT | |
# 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{} sudo route del default gw {} | |
echo "Done." |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
After running the script you can check public IP by running:
curl icanhazip.com