vCloud Director CentOS Guest OS Customization Script

I needed to customize a custom Linux VM image with a static IP address in vCloud Director. Here’s the script I came up with. It doesn’t work unless VMWare tools is installed and running in the VM (kernel upgrades tend to break it). The VM should be stopped, then paste the script into the “Guest OS Customization” script area. Boot the VM with the “Power On and Force Recustomization” option.

 

#!/bin/bash
HOSTNAME=YourHostNameHere
IPADDR=StaticIpAddressGoesHere
NETMASK=255.255.255.0
(
echo "------------------------------------------------------------------------------"
date
if [ x$1 == x"precustomization" ]; then
  set -e
  echo "Running Pre-Customization tasks..."
  if [ x$HOSTNAME != x ]; then
    echo "Configuring hostname as $HOSTNAME"
    sed -i "/HOSTNAME/d" /etc/sysconfig/network
    echo "HOSTNAME=$HOSTNAME" >> /etc/sysconfig/network 
    hostname $HOSTNAME
    hostname
  else
    # Set it so it can be used below
    HOSTNAME=`hostname`
  fi
  if [ x$IPADDR != x ]; then
    echo "Configuring network IP=$IPADDR NETMASK=$NETMASK"
    rm /etc/udev/rule.d/70-persistent-net.rules
    sed -i "/IPADDR/d" /etc/sysconfig/network-scripts/ifcfg-eth0
    sed -i "/NETMASK/d" /etc/sysconfig/network-scripts/ifcfg-eth0
    sed -i "/HWADDR/d" /etc/sysconfig/network-scripts/ifcfg-eth0
    sed -i "/BOOTPROTO/d" /etc/sysconfig/network-scripts/ifcfg-eth0
    sed -i "/DHCPHOSTNAME/d" /etc/sysconfig/network-scripts/ifcfg-eth0
    cat >> /etc/sysconfig/network-scripts/ifcfg-eth0 <<ENDCFG
BOOTPROTO=static
IPADDR=$IPADDR
NETMASK=$NETMASK
DHCPHOSTNAME=$HOSTNAME
ENDCFG
  fi
  echo "Done with Pre-Customization"
elif [ x$1 == x"postcustomization" ]; then
  echo "Running Post-Customization tasks..."
fi
) | tee -a /root/customize.log

 

Update: It turns out that having VMWare Tools functioning properly is enough for vCloud Director to configure the network settings all by itself, without the help of a script.