Table of Contents
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.
- Set hostname using cloud-init config via user data.
- 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:
#cloud-config hostname: your-hostname
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
So, in simple terms:
- Stop the instance.
- Change the user data, including the hostname under
- Restart the instance.
- 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.
/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:
#!/bin/bash echo "your-hostname" > /etc/hostname hostnamectl set-hostname "your-hostname" sed -i "s/^127.0.0.1.*/127.0.0.1 your-hostname localhost/" /etc/hosts
Replace “your-hostname” with the desired hostname for your EC2 instance.
This script does the following:
- Sets the hostname in the /
- Runs the “
hostnamectl” command to set the hostname.
- Updates the
/etc/hostsfile to include the new hostname.