Skip to content

Instantly share code, notes, and snippets.

@sckevmit
Forked from makuk66/cloudstack-sethostname.sh
Created September 22, 2017 10:49
Show Gist options
  • Save sckevmit/d644199510fccfec6a5d774887db7ce1 to your computer and use it in GitHub Desktop.
Save sckevmit/d644199510fccfec6a5d774887db7ce1 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"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment