Script to configure and set your Hostname and FQDN on EC2 Instances

Posted on April 15, 2013

When working with Amazon EC2 instances, you've probably experienced the need to change the default hostname to something more meaningful than “ip-10-205-14-33”. While simply issuing a hostname command will do the trick, it requires login into the machine. If you also need to properly define the fqdn (fully qualified domain name) of the machine, it requires a modification of the /etc/hosts file as well or more if you've setup a DNS server.

Setting the desired hostname and fqdn for the instance can be critical if you're automating deployment with Chef and expect to retrieve those values later on. A simple approach is to pass user data when creating the instance and use a script to read it and populate the hostname.

Thanks to Ternery labs for this awesome script. I've updated it to reflect the recent October 2012 changes to the hostname URL.

We're going to start by creating a script

nano /usr/local/ec2/

Copy and paste the information below into your script.

# Replace this with your domain

USER_DATA=`/usr/bin/curl -s`
IPV4=`/usr/bin/curl -s`

# Set the host name
hostname $HOSTNAME
echo $HOSTNAME > /etc/hostname

# Add fqdn to hosts file
cat< /etc/hosts
# This file is automatically genreated by ec2-hostname script localhost

# The following lines are desirable for IPv6 capable hosts
::1 ip6-localhost ip6-loopback
fe00::0 ip6-localnet
ff00::0 ip6-mcastprefix
ff02::1 ip6-allnodes
ff02::2 ip6-allrouters
ff02::3 ip6-allhosts

Now Save and exit your editor.

Next, we need to mark the script as executable

$ chmod o+x

Finally, add the following line to so that it runs every time the instance restarts


You can take this script one step further and save your instance as a new AMI, so that whenever you start a new image, the script will already be in place for you.


One Comment

Leave a Reply

Your email address will not be published.

Contact Us

Have a question? Send us a message. We'll get back to you soon.