Last active
August 29, 2015 14:15
-
-
Save ay65535/8a81c9bea28bafa1b5a7 to your computer and use it in GitHub Desktop.
Save the following script to /etc/dhcp/dhclient-exit-hooks.d/sethostname, and adjust the permissions. cf. http://docs.cloudstack.apache.org/projects/cloudstack-administration/en/4.5/templates.html#system-preparation-for-linux
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/sh | |
# dhclient change hostname script for Ubuntu | |
# ( cf. http://docs.cloudstack.apache.org/projects/cloudstack-administration/en/4.5/templates.html#system-preparation-for-linux ) | |
oldhostname=$(hostname -s) | |
if [ $oldhostname = 'localhost' -o $oldhostname = '(none)' ]; then | |
sleep 10 # Wait for configuration to be written to disk | |
hostname=$(cat /var/lib/dhcp/dhclient.eth0.leases | awk '/host-name/ { host = $3 } END { printf host }' | sed 's/[";]//g' ) | |
fqdn="$hostname.$(cat /var/lib/dhcp/dhclient.eth0.leases | awk '/domain-name/ { domain = $3 } END { printf domain } ' | sed 's/[";]//g')" | |
ip=$(cat /var/lib/dhcp/dhclient.eth0.leases | awk '/fixed-address/ { lease = $2 } END { printf lease }' | sed 's/[";]//g') | |
echo "cloudstack-hostname: Hostname _localhost_ detected. Changing hostname and adding hosts." | |
printf " Hostname: $hostname\n FQDN: $fqdn\n IP: $ip\n" | |
# Update /etc/hosts | |
if [ ${#ip} -gt 4 ]; then | |
awk -v i="$ip" -v f="$fqdn" -v h="$hostname" '/^127/{x=1} !/^127/ && x { x=0; printf("%s\t%s\t%s\n",i,f,h); } { print $0; }' /etc/hosts > /etc/hosts.dhcp.tmp | |
#cp -p /etc/hosts /etc/hosts.dhcp.tmp | |
#echo "$ip $fqdn $hostname" >> /etc/hosts.dhcp.tmp | |
mv /etc/hosts /etc/hosts.dhcp.bak | |
mv /etc/hosts.dhcp.tmp /etc/hosts | |
# Rename Host | |
echo $hostname > /etc/hostname | |
hostname -b -F /etc/hostname | |
echo $hostname > /proc/sys/kernel/hostname | |
fi | |
# Recreate SSH2 | |
export DEBIAN_FRONTEND=noninteractive | |
dpkg-reconfigure openssh-server | |
fi |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment