Saturday, July 06, 2013

Fix eth0 network interface when cloning CentOS on VirtualBox

However if you clone a Oracle VirtualBox VM, you’ll notice that it kills your network interfaces throwing errors like the one listed below:

#ifup eth0
Device eth0 does not seem to be present, delaying initialisation


What’s happening here is that when you clone your VM, VirtualBox apply a new MAC Address to your network interfaces but they don’t update the linux configuration files to mirror these changes and so the kernel doesn’t firstly can’t find or start the interface that matches it’s configuration (with the old MAC Address) and it finds a new interface (the new MAC Address) that it has no configuration information for. The result is that only your networking service can only start the loopback networking interface and eth0 is dead.

  1. Remove the kernel’s networking interface rules file so that it can be regenerated.
  2. Restart udev and network services
  3. UPDATE your interface configuration file
  4. Restart the networking service.

Easy form:

#! /bin/bash
 
rm -rf /etc/udev/rules.d/70-persistent-net.rules
 
start_udev
/etc/init.d/network restart
 
DEV=/etc/udev/rules.d/70-persistent-net.rules
ETH=`cat $DEV | head -8 | tail -1 | awk '{ print $7; }' | cut -d """ -f 2`
MAC=`cat $DEV | head -8 | tail -1 | awk '{ print $4; }' | cut -d """ -f 2`
CFG="/etc/sysconfig/network-scripts/ifcfg-$ETH"
 
cat > $CFG <<EOF
DEVICE=$ETH
HWADDR=$MAC
TYPE=Ethernet
UUID=
ONBOOT=yes
NM_CONTROLLED=yes
BOOTPROTO=dhcp
EOF
 
ifdown $ETH 2> /dev/null
ifup $ETH 2> /dev/null
 
ping -c 1 www.google.com > /dev/null
if [ $? -eq 1 ]; then 
     echo "Network failed!"
     exit 1
else
     echo "Network ready!"
fi