CentOS - Hostname via DHCP
I created a CentOS Virtual Machine using static IP addressing. Afterwards, I changed the networking to use instead DHCP, so that the name would be properly obtained from the DHCP server. Eventually, I performed a set of operations, including adding a second NIC and disabling the Network Manager. And, along the way, the hostname reverted to the initial static hostname that I had initially allocated.
I looked for the usual suspects, including /etc/hosts and /etc/hostname, but nothing seemed wrong. I checked the file /etc/sysconfig/network-scripts/network-functions, that contains a function called need_hostname
need_hostname () { CHECK_HOSTNAME=$(hostname) if [ "$CHECK_HOSTNAME" = "(none)" -o "$CHECK_HOSTNAME" = "localhost" -o \ "$CHECK_HOSTNAME" = "localhost.localdomain" ]; then return 0 else return 1 fi }
And the problem was that, on the first line, CHECK_HOSTNAME was initialized with the initial static hostname (centos7).
The command hostamectl gave some additional information:
Static hostname: n/a Transient hostname: centos7 Icon name: computer Chassis: n/a Machine ID: 5c9e46abd14b479ab95c2488fc96de55 Boot ID: 297819ceb8f848ceb2379c9dc629d214 Virtualization: kvm Operating System: CentOS Linux 7 (Core) CPE OS Name: cpe:/o:centos:centos:7 Kernel: Linux 3.10.0-229.20.1.el7.x86_64 Architecture: x86_64
Now, looking to the function need_hostname above, I realized that any name except (none) or localhost ot localhost.domain would imply that no hostname was required. Ok, time to change the transient hostname:
hostnamectl set-hostname '' --transient
But this does nothing: that is the transient name, each time the machine is rebooted, is lost. What is needed is to set the static hostname, so the following line should solve this issue:
hostnamectl set-hostname localhost --static