Software Engineer's Blog

How to change Hostname on Amazon Linux Permanently

How to change Hostname on Amazon Linux Permanently

On Amazon Linux, the process to change the hostname is similar to other Linux distributions. Below are the steps to change the hostname and ensure it remains after a reboot.

1. Edit /etc/sysconfig/network file:

  • /etc/sysconfig/network file is one of the files used to configure networking settings on a Linux system.
  • The changed hostname serves as the network identifier for the system.
$ sudo vi /etc/sysconfig/network

NETWORKING=yes
HOSTNAME=your_new_hostname

2. Edit /etc/hostname file:

  • /etc/hostname file defines the system’s hostname and how the server identifies and reports itself on the network.
  • By altering this file, the changed hostname will be applied when the system reboots next.
$ echo "your_new_hostname" | sudo tee /etc/hostname

3. Edit /etc/hosts file:

  • /etc/hosts file serves the role of mapping IP addresses to hostnames and is referred to before DNS queries are made.
  • For instance, if the 127.0.0.1 address is not mapped to the system’s hostname, some systems may be unable to locate themselves, leading to various network-related issues.
$ sudo vi /etc/hosts
127.0.0.1   your_new_hostname

4. Reboot

$ sudo reboot

Completing all the above steps will change the hostname permanently on your Amazon Linux instance, and it will remain even after rebooting.

The modern way: hostnamectl

The /etc/sysconfig/network approach is the classic Amazon Linux 1 method. On Amazon Linux 2 and 2023, which are systemd-based, the direct way to set it is one command — no reboot needed:

$ sudo hostnamectl set-hostname your_new_hostname

That writes /etc/hostname for you and applies the change live. You still want the /etc/hosts entry from step 3 so the box can resolve its own name.

The gotcha that actually breaks “permanent”

Here’s the part that trips up EC2 users: cloud-init can reset your hostname on the next reboot, quietly undoing everything above. On an EC2 instance, tell cloud-init to leave it alone by editing /etc/cloud/cloud.cfg:

preserve_hostname: true

Without that line, cloud-init reapplies the instance’s default hostname at boot and your change vanishes — which is usually why a hostname that “should be permanent” keeps coming back.