How To Set Permanent Hostname for AWS EC2 Linux Instances

There are two ways to set a Hostname for an AWS ec2 Linux instance permanently.

  1. Set hostname using cloud-init config via user data.
  2. Using hostnamectl command
  3. Set Hostname using shell script

Set Hostname Using Cloud-Init

To set the hostname using Cloud-Init on an EC2 instance, you can use the following Cloud Config in EC2 user data:

hostname: your-hostname

Replace your-hostname with the desired hostname for your EC2 instance.

In this example, the “hostname” key sets the hostname for the instance.

Cloud Config configuration in the user data will be used to configure the instance during the initialization process. The Cloud-Init tool on the instance will set the hostname as specified in the configuration.

For existing EC2 instances, you’ll need to stop the instance first. After you’ve made the changes to the user data, you can then restart the instance. The “Cloud-Init” system will read the new user data and set the hostname as specified under #cloud-config.

So, in simple terms:

  1. Stop the instance.
  2. Change the user data, including the hostname under #cloud-config.
  3. Restart the instance.
  4. Cloud-Init will set the new hostname.

This way, the hostname will be what you set it to be, even after the instance is restarted.


For manual hostname changes, you should make changes to the cloud.cfg file to ensure the hostname persists after the server reboots.

cloud-config setting in the ec2 user data is the simplest way to set a permanent ec2 hostname. If you try other methods, the hostname changes on every server restart. This is because EC2 uses a system called “Cloud-Init” to set up instances when they start.

The /etc/cloud/cloud.cfg file that is part of the cloud-init package has a parameter preserve_hostname set to false by default.

If you manually set the hostname, you need to set preserve_hostname to true.

Set Hostname Using Shell script

If you have a running instance and you want to set the hostname using Linux commands, use the following method.

Here is an example of a shell script to set a permanent hostname on an EC2 instance using user data:

echo "your-hostname" > /etc/hostname
hostnamectl set-hostname "your-hostname"
sed -i "s/^*/    your-hostname localhost/" /etc/hosts

Replace “your-hostname” with the desired hostname for your EC2 instance.

This script does the following:

  1. Sets the hostname in the /etc/hostname file.
  2. Runs the “hostnamectl” command to set the hostname.
  3. Updates the /etc/hosts file to include the new hostname.

Related Articles


Your email address will not be published. Required fields are marked *

  1. I’m so happy to read this. This is the kind of details that needs to be given and not the random misinformation that is at the other blogs. Appreciate your sharing this best doc.