To set or change the hostname of an Amazon Linux EC2 instance, you can use the hostnamectl
command. This command is used to control the hostname and related settings of a Linux system.
To set the hostname of the EC2 instance, use the set-hostname
option and specify the new hostname:
sudo hostnamectl set-hostname new_hostname
To view the current hostname of the EC2 instance, use the status
option:
sudo hostnamectl status
Keep in mind that changing the hostname with hostnamectl
will not persist after a reboot. To make the change permanent, you will need to edit the /etc/hostname
file and set the hostname to the desired value:
sudo echo "new_hostname" > /etc/hostname
You will also need to update the /etc/hosts
file to reflect the new hostname.
sudo sed -i "s/old_hostname/new_hostname/g" /etc/hosts
After making these changes, reboot the EC2 instance to apply the new hostname.
sudo reboot
Keep in mind that changing the hostname can have unintended consequences, especially if the hostname is used in configuration files or scripts. Be sure to test any changes thoroughly before deploying them in a production environment.