Dynamically Assign Host Names to your EC2 Instances

Posted on 01/14/2016 by Brian Carey

One of the first things a new AWS user may notice when standing up a Linux instance is its less than friendly default host names.  Sure, in a dynamic cloud environment this may or may not be a concern to you.  However there's always something to be said for having meaningful server names.  While this may seem like a basic concept to some or a post that is late to the party we just wanted to show what we consider a nice simple way to handle this problem using the User Data feature of EC2 without manually setting each system's host name manually.

Setup

First, you can find a pre-built script to do this in our Github repo.  Download this script to your instance somewhere, for example:

# wget -O /usr/local/bin/ec2-init.sh https://raw.githubusercontent.com/kissit/kiss-ops/master/cloud/ec2-init.sh
# chmod 755 /usr/local/bin/ec2-init.sh

Next, you need to tell the system to run this script at boot time.  The simplest way to accomplish this is via rc.local by adding the following to the file /etc/rc.local:

## Run our custom ec2-init script
/usr/local/bin/ec2-init.sh

Now, assuming you didn't pass in the host name as User Data when the instance was built, you need to add it.  Unfortunately the instance must be stopped to do so.  So stop your instance then to add the User Data right click on it in the AWS control panel and navigate to Instance Settings > View/Change User Data.  You will then be presented with a pop up to enter your User Data.  Simply enter the host name you want to use as plain text and click Save.

Once the user data has been set, start your instance back up and login, when you do you should see the name is set to match the user data like so:

[root@example-hostname ~]#


Automation

Now, while the above is great it would be tedious to do for every system.  One way to make this process easier is to roll this into what we typically refer to as Base images.  Very rarely are we building new instances from stock images that were not created from an initial golden build.  So, setup your base system to have the script installed and run at boot.  Then, if you're building instances through the web console, provide your host name as part of the user data at creation time.  Or even better, if you're like us and doing a large number of builds through the API or a tool like Ansible, you can easily pass this information into that process.  The above is then reduced to a one time cost to get it included in your base images!