How do I assign a static hostname to an Amazon EC2 instance that runs RHEL 7, 8, or 9, or CentOS 7, 8, or 9?

3 minute read
0

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 to the original hostname.

Short description

To make a hostname persist when you reboot or stop and start your EC2 instance, add the hostname to the instance's appropriate configuration files.

Note: The following steps apply to RHEL 7, 8, and 9, and CentOS 7, 8, and 9. For other distributions, see the following resources:

Resolution

To update the hostname of your RHEL or CentOS Linux instance, complete the following steps:

  1. Run the hostnamectl command from the shell. Replace persistent-hostname with the name that you want the instance to use:

    sudo hostnamectl set-hostname --static persistent-hostname

    Note: When you change the hostname with the hostnamectl command, the /etc/hosts file doesn't update. If you must update this file for your use case, then manually edit the file to add the new hostname.

  2. Use the vi text editor to update the /etc/cloud/cloud.cfg file on your Linux instance:

    Note: If your instance runs RHEL 7.4 or above, then skip this step.

    sudo vi /etc/cloud/cloud.cfg

    For more information on how to use the vi editor, run the command info vi from the command shell.

  3. Add the following string to the bottom of the /etc/cloud/cloud.cfg file. This preserves the new hostname between restarts and reboots:

    preserve_hostname: true
  4. Save and exit the vi editor.

  5. To reboot the EC2 instance and associate the new hostname with the instance, run the reboot command.

    sudo reboot
  6. To verify that the hostname change persisted, run the Linux hostname command without any parameters:

    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 run these steps again. For more information on the hostname utility, see the hostname manual on the Ubuntu website.

AWS OFFICIAL
AWS OFFICIALUpdated 10 months ago