#!/usr/bin/env sh # # This injects hooks into the network management service of the # droplet with content to add routes into host for vpc peering. peering_route_script='/var/lib/cloud/scripts/peering.sh' # Detects the network service used by the system detect_network_service () { if systemctl --quiet is-active NetworkManager; then netsvc='NetworkManager' elif systemctl --quiet is-active systemd-networkd; then netsvc='networkd' elif systemctl --quiet is-active networking; then netsvc='ifupdown' else >&2 echo "Unable to detect network service to properly inject vpc peering routes" exit 1 fi } # Place the peering script in peering_route_script location place_route_injection_script() { cat > "$peering_route_script" << 'EOM' #!/bin/sh for i in $(seq 1 10); do VPC_PEERING_ENABLED=$(curl -fs --connect-timeout 5 169.254.169.254/metadata/v1/features/vpc_peering_enabled) if [ $? -ne 0 ]; then sleep 5 continue fi if [ "${VPC_PEERING_ENABLED}" != "true" ]; then exit 0 fi VPC_GATEWAY_IP=$(curl -fs --connect-timeout 5 169.254.169.254/metadata/v1/interfaces/private/0/ipv4/gateway) if [ $? -ne 0 ]; then sleep 5 continue fi ip route replace 192.168.0.0/16 via "${VPC_GATEWAY_IP}" dev eth1 mtu 1500 metric 101 && \ ip route replace 10.0.0.0/8 via "${VPC_GATEWAY_IP}" dev eth1 mtu 1500 metric 101 && \ ip route replace 172.16.0.0/12 via "${VPC_GATEWAY_IP}" dev eth1 mtu 1500 metric 101; if [ $? -eq 0 ]; then exit 0 fi sleep 5 done exit 1 EOM chmod +x "$peering_route_script" } # Inject hook into /etc/network/if-up.d/ inject_ifupdown() { cat > /etc/network/if-up.d/vpc-peering << EOM #!/bin/sh [ "\$IFACE" = "eth1" ] && ${peering_route_script} exit 0 EOM chmod +x /etc/network/if-up.d/vpc-peering "$peering_route_script" } # Inject hook into /etc/NetworkManager/dispatcher.d/ inject_network_manager() { cat > /etc/NetworkManager/dispatcher.d/vpc-peering << EOM #!/bin/sh interface=\$1 event=\$2 if [ "\$interface" != "eth1" ] || [ "\$event" != "up" ]; then exit 0 fi ${peering_route_script} EOM chmod +x /etc/NetworkManager/dispatcher.d/vpc-peering "$peering_route_script" } # systemd-networkd does not supports hooks, we inject a oneshot # systemd unit that is invoked after eth0/1 is online and if systemd-networkd restarts. inject_networkd() { cat > /etc/systemd/system/vpc-peering.service << EOM [Unit] Description=VPC Peering Route Injection Requires=systemd-networkd-wait-online.service systemd-networkd.service After=systemd-networkd-wait-online.service systemd-networkd.service PartOf=systemd-networkd.service [Service] Type=oneshot ExecStart=${peering_route_script} RemainAfterExit=yes [Install] WantedBy=multi-user.target EOM systemctl daemon-reload systemctl enable --now vpc-peering.service } detect_network_service place_route_injection_script case $netsvc in ifupdown) inject_ifupdown ;; networkd) inject_networkd ;; NetworkManager) inject_network_manager ;; esac