Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save johnmccabe/7fad47536ee4e4686dbb99faf070f6a7 to your computer and use it in GitHub Desktop.
Save johnmccabe/7fad47536ee4e4686dbb99faf070f6a7 to your computer and use it in GitHub Desktop.
dhclient hook for setting the hostname, updating /etc/hosts, and re-generating ssh keys on Ubuntu.Useful for creating CloudStack templates.See https://issues.apache.org/jira/browse/CLOUDSTACK-4556
#!/bin/sh
echo "Running dhclient change hostname script for Ubuntu. reason=${reason}"
timestamp=$(date +%s)
if grep localhost /etc/hostname; then
echo "Current hostname:"
cat /etc/hostname
echo "Attempting to configure hostname"
if [ "x$reason" = "xBOUND" ]; then
hostname=$new_host_name
fqdn="${hostname}.${new_domain_name}"
ip=$new_ip_address
echo "cloudstack-hostname: Hostname localhost detected. Changing hostname and adding hosts."
printf " Hostname: $hostname\n FQDN: $fqdn\n IP: $ip\n\n"
echo "Wait for filesystem to become writable"
TESTFILE=/etc/.is_fs_writable_$timestamp
until touch $TESTFILE; do
echo "sleeping 1 second"
sleep 1
done
rm $TESTFILE
# Set Hosts and Hostname
TMPHOSTS=/etc/hosts.dhcp.new
if ! grep "$ip $fqdn $hostname" /etc/hosts; then
# Backup hosts file
cp /etc/hosts /etc/hosts.dhcp.bak
# Copy everything except 127.0.1.1 from initial hosts file
grep -v '127\.0\.1\.1 ' < /etc/hosts > $TMPHOSTS
# Add the new ip address and name
echo "$ip $fqdn $hostname" >> $TMPHOSTS
mv $TMPHOSTS /etc/hosts
fi
# Rename Host
echo $hostname > /etc/hostname
hostname -b -F /etc/hostname
echo $hostname > /proc/sys/kernel/hostname
# Create fresh SSH keys
export DEBIAN_FRONTEND=noninteractive
dpkg-reconfigure openssh-server
fi
fi
@johnmccabe
Copy link
Author

johnmccabe commented Apr 25, 2016

Working on Ubuntu 14.04 and survives reboots

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment