Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save doodlemania2/4fd1ac7a0d86ead54bebdbb85c66d0ea to your computer and use it in GitHub Desktop.

Select an option

Save doodlemania2/4fd1ac7a0d86ead54bebdbb85c66d0ea to your computer and use it in GitHub Desktop.
#!/bin/bash
set -euo pipefail
echo "=== Detecting current netplan interface ==="
NETPLAN_FILE=$(ls /etc/netplan/*.yaml | head -n 1)
if [[ -z "$NETPLAN_FILE" ]]; then
echo "ERROR: No netplan YAML file found in /etc/netplan"
exit 1
fi
echo "Using netplan file: $NETPLAN_FILE"
# Grab the first interface name under 'ethernets:'
IFACE=$(awk '/ethernets:/ {getline; gsub(":", "", $1); print $1; exit}' "$NETPLAN_FILE")
if [[ -z "$IFACE" ]]; then
echo "ERROR: Could not detect interface name from netplan"
exit 1
fi
if [[ "$IFACE" == "eth0" ]]; then
echo "Interface is already eth0. Nothing to do."
exit 0
fi
echo "Detected netplan interface: $IFACE"
# Get MAC address for that interface
if [[ ! -d "/sys/class/net/$IFACE" ]]; then
echo "ERROR: Interface $IFACE does not exist in /sys/class/net"
exit 1
fi
MAC=$(cat /sys/class/net/$IFACE/address)
echo "MAC address: $MAC"
echo "=== Creating udev rule to rename $IFACE → eth0 ==="
sudo tee /etc/udev/rules.d/10-rename-to-eth0.rules >/dev/null <<EOF
SUBSYSTEM=="net", ACTION=="add", ATTR{address}=="$MAC", NAME="eth0"
EOF
echo "Udev rule created."
echo "=== Updating netplan configuration to use eth0 ==="
# Replace interface name in netplan
sudo sed -i "s/$IFACE:/eth0:/g" "$NETPLAN_FILE"
sudo sed -i "s/$IFACE/eth0/g" "$NETPLAN_FILE"
# Ensure nameservers block is in correct format if present
if grep -q "nameservers:" "$NETPLAN_FILE" && ! grep -q "addresses:" "$NETPLAN_FILE"; then
echo "Fixing nameserver structure..."
# This is conservative; if your file is already correct, this won't hurt
sudo sed -i 's/nameservers:/nameservers:\n addresses:/g' "$NETPLAN_FILE"
fi
echo "=== Validating netplan ==="
sudo netplan try --timeout 5 || {
echo "Netplan validation failed. Check $NETPLAN_FILE"
exit 1
}
echo "=== Applying netplan ==="
sudo netplan apply
echo "=== Rebooting to apply interface rename to eth0 ==="
sudo reboot
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment