Created
          January 7, 2020 03:43 
        
      - 
      
- 
        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
  
        
  
    
      This file contains hidden or 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 | |
| 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 "$@" | |
  
    Sign up for free
    to join this conversation on GitHub.
    Already have an account?
    Sign in to comment
  
            
paset the above in a shell and then run
set_second_interface 0 && sudo netplan --debug applywhere 0 is the defaultor download the file