How do I assign a static hostname to an Amazon EC2 instance running RHEL 7 or CentOS 7?
Last updated: 2020-11-13
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. How do I make the hostname to persist?
To make a hostname persists when rebooting or stopping and starting 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:
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:
Save and exit the vi editor.
4. Run the reboot command to reboot the EC2 instance and associate the new hostname with the instance:
5. Run the Linux hostname command without any parameters to verify that the hostname change persisted:
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, you must run these steps again.