Created
July 13, 2012 16:06
-
-
Save shaneog/3105700 to your computer and use it in GitHub Desktop.
Change Ubuntu hostname on startup based on vCloud Director machine name
This file contains 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 | |
### BEGIN INIT INFO | |
# Provides: hostname | |
# Required-Start: | |
# Required-Stop: | |
# Should-Start: glibc | |
# X-Start-Before: networking | |
# Default-Start: S | |
# Default-Stop: | |
# Short-Description: Sets the hostname based on the vCloud Director OVF details | |
# Description: Sets the hostname based on the vCloud Director OVF details | |
# If the hostname cannot be found the current one is untouched | |
### END INIT INFO | |
# Adapted from http://www.derekabdine.com/2011/05/setting-vm-name-as-hostname-of-vmware.html | |
do_start () { | |
# First grab the old hostname | |
OLDHOSTNAME=`hostname` | |
# Now grab the new hostname via VMware RPC (OVF (vCloud Director) specific) | |
HOSTNAME=`vmtoolsd --cmd "info-get guestinfo.ovfEnv" | awk -F"\"" ' /vCloud_computerName/ {print $4}'` | |
# Sometimes in vCD the Properties section does not exist, so we can't get the machine name | |
# Check the new hostname length and bail if necessary | |
if [ -z "$HOSTNAME" ]; then | |
echo "Hostname is empty!" | |
exit 1 | |
fi | |
# Check the hostname and bail if necessary | |
if [ "$HOSTNAME" == "$OLDHOSTNAME" ]; then | |
echo "Hostname set correctly, nothing to do!" | |
exit 0 | |
fi | |
# Next, set the hostname on the system | |
echo -e "Setting hostname to $HOSTNAME...\r\n" | |
echo $HOSTNAME > /etc/hostname | |
hostname $HOSTNAME | |
# Finally, change the hostname in the hosts file | |
echo -e "Updating /etc/hosts by replacing $OLDHOSTNAME with $HOSTNAME...\r\n" | |
sed -i "s/$OLDHOSTNAME/$HOSTNAME/g" /etc/hosts | |
} | |
case "$1" in | |
start|"") | |
do_start | |
;; | |
restart|reload|force-reload) | |
echo "Error: argument '$1' not supported" >&2 | |
exit 3 | |
;; | |
stop) | |
# No-op | |
;; | |
*) | |
echo "Usage: hostname.sh [start|stop]" >&2 | |
exit 3 | |
;; | |
esac |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment