Say Hi

Change and Persist Hostname in Linux

March 23, 2023

Hostname is the name of your Linux system. It is used to identify your system on a network. By default, the hostname is set to localhost or the ip address when you install a Linux distribution. For example, you might have a server with the hostname ip-172-31-1-1 or localhost.

Why change Hostname?

You can change the hostname to something more meaningful and easy to remember. This is especially useful if you have multiple servers and you want to identify them easily.

For example, in my day to day work, I have to manage tens of servers. Knowing the hostname of a server is very useful when I need to connect to it using SSH or when I need to run a command on it.

Updating Hostname

You can change the hostname using the hostnamectl command or by editing the /etc/hostname file. Create a new file called change-hostname.sh and add the following code:

#!/bin/bash

set -e

HOSTNAME="my-server"

echo "$HOSTNAME" | sudo tee /etc/hostname
sudo hostname -F /etc/hostname
echo -e "127.0.0.1\t$HOSTNAME\t$HOSTNAME.local" | sudo tee -a /etc/hosts
sudo sed -i 's/preserve_hostname: false/preserve_hostname: true/g' /etc/cloud/cloud.cfg

Make the file executable:

chmod +x change-hostname.sh

Now run the script:

./change-hostname.sh

The script will change the hostname to my-server and update the /etc/hosts file. It will also update the preserve_hostname setting in the /etc/cloud/cloud.cfg file. This setting will ensure that the hostname is not reset when you reboot the server.