I changed the hostname of my Amazon Elastic Compute Cloud (Amazon EC2) instance. However, when I reboot or stop and then start the instance, the hostname changes back.
Short description
To make a hostname persist when you reboot or stop and start your EC2 instance, add the hostname to the appropriate configuration files on the instance.
Note: The following steps apply to RHEL 7 or CentOS 7. For instructions that apply to other distributions, see one of the following:
Change the system hostname
How do I assign a static hostname to an Amazon EC2 instance running RHEL 5 or 6, CentOS 5 or 6, or Amazon Linux?
How do I assign a static hostname to an Amazon EC2 instance running SLES?
How do I assign a static hostname to an Amazon EC2 instance running Ubuntu Linux?
Resolution
1. Run the hostnamectl command from the shell to update the hostname of your RHEL 7 or CentOS 7 Linux instance. Replace persistent-hostname with the name you want the instance to use:
sudo hostnamectl set-hostname --static persistent-hostname
Note: Changing the hostname by using the hostnamectl command doesn't update the /etc/hosts file. However, if necessary, you can manually edit this file to add the new hostname.
2. Use the vi text editor to update the /etc/cloud/cloud.cfg file on your RHEL 7 or CentOS 7 Linux instance. For general information about using the vi editor, run the command info vi from the command shell:
Note: For instances running RHEL 7.4 and above, skip this step.
sudo vi /etc/cloud/cloud.cfg
3. Add the following string to the bottom of the /etc/cloud/cloud.cfg file to be sure that the new hostname is preserved between restarts and reboots:
preserve_hostname: true
Save and exit the vi editor.
4. Run the reboot command to reboot the EC2 instance and associate the new hostname with the instance:
sudo reboot
5. Run the Linux hostname command without any parameters to verify that the hostname change persisted:
hostname
The command returns the new hostname that you specified in step 1.
Note: If you install any system updates that affect the /etc/hosts file, the hostname file, or the hostname utility, then you must run these steps again.