1

On older versions of Ubuntu (using the Classical Installer), I was able to populate the hostname from my DHCP server. I then passed it by using the netcfg/get_hostname= option of the kernel parameters.

As of 20.04, the Classical Installer no longer exists. How am I able to change the hostname using my DHCP server instead of fixed hostname in the user-data file?

I have tried late-commands to use a shell script to change the hostname with sed, however it has not worked.

Christopher H
  • 368
  • 2
  • 18
gunsmoke
  • 51
  • 2
  • 5

2 Answers2

2

You can do it, using a script for a DHCP hook.

  1. Create a new file:
sudoedit /etc/dhcp/dhclient-exit-hooks.d/hostname
  1. Paste the following code into the file, save and close:
#!/bin/sh
# Filename:     /etc/dhcp/dhclient-exit-hooks.d/hostname
# Purpose:      Used by dhclient-script to set the hostname of the system
#               to match the DNS information for the host as provided by
#               DHCP.
#


# Do not update hostname for virtual machine IP assignments
if [ "$interface" != "eth0" ] && [ "$interface" != "wlan0" ]
then
    return
fi


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

echo dhclient-exit-hooks.d/hostname: Dynamic IP address = $new_ip_address
hostname=$(host $new_ip_address | cut -d ' ' -f 5 | sed -r 's/((.*)[^\.])\.?/\1/g' )
echo $hostname > /etc/hostname
hostname $hostname
echo dhclient-exit-hooks.d/hostname: Dynamic Hostname = $hostname
  1. Make the file readable...
chmod a+r /etc/dhcp/dhclient-exit-hooks.d/hostname
  1. Release the existing DHCP lease...
sudo dhclient -r
  1. And obtain a new one.
sudo dhclient
Christopher H
  • 368
  • 2
  • 18
2

Using part of the answer from here, if you set the hostname to localhost in the identity section of the autoinstall YAML, the next boot of the machine will configure to it's DHCP issued hostname.

For setting the hostname from DHCP during the installer, you'll probably need to use the Christopher H's answer within the early-commands section.