As we can see, changing the Hostname of a Linux Machine is just a simple task, with the help of one single command i.e $hostname name_youwant. But in AWS if you use this command $hostname name_youwant it will change the hostname and it is not persistent. when you reboot the instance, the hostname reverts to its former name.
So to make the hostname persistent we follow some steps as below:
STEP1: RUN THE COMMAND HOSTNAMECTL IN YOUR LINUX TERMINAL (CENTOS/REHL)
sudo hostnamectl set-hostname --static persistent-hostname
Replace the “persistent-hostname” with the name you want for your instance
Note: Changing the hostname by using the hostnamectl command doesn’t update the/etc/hosts file. So you can change it manually.
STEP2: OPEN THE “CLOUD.CFG” IN “/ETC/CLOUD/CLOUD.CFG” AND UPDATE IT
sudo vi /etc/cloud/cloud.cfg
add the following line at the end of this above file
save and exit
STEP3: REBOOT THE SERVER
STEP4: CHECK THE HOSTNAME
Congratulations…. You follow all the steps and set a hostname that is persistent to your ec2-instance.