Skip to content

Instantly share code, notes, and snippets.

@ar45
Created January 7, 2020 03:43
Show Gist options
  • Save ar45/4616efa6cc4093dcdf9da1daa981b381 to your computer and use it in GitHub Desktop.
Save ar45/4616efa6cc4093dcdf9da1daa981b381 to your computer and use it in GitHub Desktop.
AWS ubuntu 18.04 setup secondary interface with routing default via interface attachment by index
#!/bin/bash
set_second_interface() # $1 = interface index (aws index) to set the default route
{
route_via="$1"
[ "$route_via" ] || {
echo "Must provide interface index number which to route via"
return 1
}
ifaces=$(ls /sys/class/net/)
for iface in $ifaces; do
[ "$(cat "/sys/class/net/$iface/type")" = 1 ] || continue
mac="$(cat "/sys/class/net/$iface/address")"
[ "$mac" ] || continue
# ensure we have a route
sudo ip route add 169.254.169.254 dev "$iface"
device_number=$(curl -fs http://169.254.169.254/latest/meta-data/network/interfaces/macs/$mac/device-number)
sudo ip route del 169.254.169.254 dev "$iface"
if [ "$route_via" = 0 ] && [ "$device_number" = 0 ]; then
# We don't have to set anything only for the secondary interfaces
sudo rm -f "/etc/netplan/51-auto-$iface.yaml"
continue
fi
cat <<EOF | sudo tee "/etc/netplan/51-auto-$iface.yaml"
network:
version: 2
ethernets:
$iface:
dhcp4: true
match:
macaddress: $mac
set-name: $iface
EOF
if [ "$route_via" != "$device_number" ]; then
cat <<EOF | sudo tee -a "/etc/netplan/51-auto-$iface.yaml"
dhcp4-overrides:
use-routes: false
EOF
fi
done
}
# If the script is sourced do nothing. If it is executed, execute the function and pass the args
(return 0 2>/dev/null) || set_second_interface "$@"
@ar45
Copy link
Author

ar45 commented Jan 7, 2020

paset the above in a shell and then run
set_second_interface 0 && sudo netplan --debug apply where 0 is the default

or download the file

ROUTE_VIA_IFACE=0
curl https://gist.githubusercontent.com/ar45/4616efa6cc4093dcdf9da1daa981b381/raw/set_second_interface.sh | bash -s $ROUTE_VIA_IFACE && sudo netplan --debug apply

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment