Skip to content

Instantly share code, notes, and snippets.

@cameronelliott
Forked from sparkcodeuk/floating-ip-gateway.sh
Last active October 19, 2022 02:36
Show Gist options
  • Save cameronelliott/65106bbb292626ef6f029c1db8f130b0 to your computer and use it in GitHub Desktop.
Save cameronelliott/65106bbb292626ef6f029c1db8f130b0 to your computer and use it in GitHub Desktop.
Digital Ocean show how to use two IP addresses
#!/bin/bash
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)
PUB_IP=$(curl -s --connect-timeout $CURL_TIMEOUT http://169.254.169.254/metadata/v1/interfaces/public/0/ipv4/address)
if [ -z "$GATEWAY_IP" ]; then
echo "Error: failed getting gateway IP for this droplet."
exit 1
fi
ip route replace default via $GATEWAY_IP dev $NET_INT
echo my default IP
curl -4 https://icanhazip.com/
echo my IP when done via pub IP
curl --interface $PUB_IP -4 https://icanhazip.com/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment