Skip to content

Instantly share code, notes, and snippets.

@makuk66
Last active May 24, 2019 16:58
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 6 You must be signed in to fork a gist
  • Save makuk66/6379642 to your computer and use it in GitHub Desktop.
Save makuk66/6379642 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
# dhclient change hostname script for Ubuntu
# /etc/dhcp/dhclient-exit-hooks.d/sethostname
# logs in /var/log/upstart/network-interface-eth0.log
# for debugging:
echo "sethostname BEGIN"
export
set -x
if [ $reason = "BOUND" ]; then
echo new_ip_address=$new_ip_address
echo new_host_name=$new_host_name
echo new_domain_name=$new_domain_name
oldhostname=$(hostname -s)
if [ $oldhostname != $new_host_name ]; then
# Rename Host
echo $new_host_name > /etc/hostname
hostname -F /etc/hostname
# Update /etc/hosts if needed
TMPHOSTS=/etc/hosts.dhcp.new
if ! grep "$new_ip_address $new_host_name.$new_domain_name $new_host_name" /etc/hosts; then
# Remove the 127.0.1.1 put there by the debian installer
grep -v '127\.0\.1\.1 ' < /etc/hosts > $TMPHOSTS
# Add the our new ip address and name
echo "$new_ip_address $new_host_name.$new_domain_name $new_host_name" >> $TMPHOSTS
mv $TMPHOSTS /etc/hosts
fi
# Recreate SSH2 keys
export DEBIAN_FRONTEND=noninteractive
dpkg-reconfigure openssh-server
fi
fi
echo "sethostname END"
@homburg
Copy link

homburg commented Jul 9, 2014

Great job on the dhclient hook.

I'm trying to use mdns resolution for my servers, ie. $new_host_name.local. Any idea how to tweak this to enable resolution on the mdns ".local" tld?

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