Skip to content

Change Hostname

mrp-78 edited this page Jul 21, 2019 · 3 revisions

1. Change the hostname using hostnamectl

$ sudo hostnamectl set-hostname new_hostname

The hostnamectl command does not produce output. On success, 0 is returned, a non-zero failure code otherwise.

2. Edit the /etc/hosts file

Open the /etc/hosts file and change the old hostname to the new one.

127.0.0.1   localhost
127.0.0.1   new_hostname

3. Edit the cloud.cfg file

If the cloud-init package is installed you also need to edit the cloud.cfg file.

To check if the package is installed run the following ls command:

$ ls -l /etc/cloud/cloud.cfg

If you see the following output it means that the package is not installed and no further action is required.

Output
ls: cannot access '/etc/cloud/cloud.cfg': No such file or directory

If the package is installed the output will look like the following:

Output
-rw-r--r-- 1 root root 3169 Apr 27 09:30 /etc/cloud/cloud.cfg

In this case you’ll need to open the /etc/cloud/cloud.cfg file:

$ sudo nano /etc/cloud/cloud.cfg

Search for preserve_hostname and change the value from false to true.

Verify the change

To verify that the hostname was successfully changed, once again use the hostnamectl command:

$ hostnamectl
Output
   Static hostname: new_hostname
         Icon name: computer-vm
           Chassis: vm
        Machine ID: 6f17445f53074505a008c9abd8ed64a5
           Boot ID: 1c769ab73b924a188c5caeaf8c72e0f4
    Virtualization: kvm
  Operating System: Ubuntu 18.04 LTS
            Kernel: Linux 4.15.0-22-generic
      Architecture: x86-64