Host name reverts to old name after reboot in 18.04 LTS

First edit /etc/cloud/cloud.cfg and set the parameter "preserve_hostname" from "false" to "true" and then edit /etc/hostname.


The hostname is being reset by cloud-init which can either be disabled as follows (after which you can set the hostname in the normal way e.g. using hostnamectl):

sudo touch /etc/cloud/cloud-init.disabled

Or you can use cloud-init and create/modify the user-data file (usually found at: /var/lib/cloud/seed/nocloud-net/user-data) so that the hostname: entry is set to the desired hostname (provided preserve_hostname: is not set). Firstly you'll need to clean the existing config:

sudo cloud-init clean

And then reinitialise cloud-init's config from the new/modified user-data file:

sudo cloud-init init

Then reboot. See the cloud-init docs for more details.


For the "lazy guys" like me, a copy-paste solution :)

sudo sed -i '/preserve_hostname: false/c\preserve_hostname: true' /etc/cloud/cloud.cfg && sudo hostnamectl set-hostname ReplaceThisWithTheHostnamePreferred

First command allows the new hostname to be remembered by the OS.

The second part (after the &&) will only run if the first part has finished successfully and will set the hostname to the desired value.

Regards! L


1- Edit vi /etc/cloud/cloud.cfg and change

preserve_hostname: false

To

preserve_hostname: true

Save and exit.

2- Edit vi /etc/hostname and replace your new name in this file or you can do this step with bellow command.

hostnamectl set-hostname NEWNAME

Enjoy it :)


If you're not happy with leaving an older version somewhere, then simply open the file at /var/lib/cloud/seed/nocloud-net/user-data, and change your hostname at the line:

hostname: cm-lc-nc

Then run:

cloud-init clean
cloud-init init

It will then set /etc/hostname to the new value and will remain consistent across reboots. This will remove all traces of the previous hostname and in the event that preserve_hostname is either reset or ignored for some reason, you still won't lose your new hostname.