Ubuntu set local hostname via DHCP

Sometime for automation you need to be able to set the ubuntu hostname at  boot ( or at network restart ) via DHCP / DNS .

To be able to do that you only have to add in /etc/dhcp/dhclient-exit-hooks.d a file named hostname with the following content:

 

if [ "$reason" != BOUND ] && [ "$reason" != RENEW ] \
&& [ "$reason" != REBIND ] && [ "$reason" != REBOOT ]
then
return
fi

host=$(host $new_ip_address | cut -d ' ' -f 5)
host=${hostname:0:-1}
echo $host > /etc/hostname
hostname $host

What it does ? Simple it hooks dhcpclient and after the client receives the new ip from dhcp it will make a simple reverse lookup for the ip received
and will set the hostname accordingly.