Automatically Configure Hostname for New EC2 Instances

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" for instance. 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.

Create a new instance from your favorite AMI. Save this script as /usr/local/ec2/ec2-hostname.sh

#!/bin/bash

# Replace this with your domain
DOMAIN=your-domain.com

USER_DATA=`/usr/bin/curl -s http://169.254.169.254/latest/user-data`
HOSTNAME=`echo $USER_DATA`
IPV4=`/usr/bin/curl -s http://169.254.169.254/latest/meta-data/public-ipv4`

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

# Add fqdn to hosts file
cat<<EOF > /etc/hosts
# This file is automatically genreated by ec2-hostname script
127.0.0.1 localhost
$IPV4 $HOSTNAME.$DOMAIN $HOSTNAME

# 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
EOF

Mark it as executable

$ chmod o+x ec2-hostanme.sh

and add the following line to /etc/rc.local so that it runs every time the instance restart

/usr/local/ec2/ec2-hostname.sh

Save this instance as a new AMI (easiest to do from the AWS console).

Next time you want to create a new instance, pass the desired hostname in the user-data option.

ec2-run-instances ami-99f510f1 --user-data "YOUR-HOSTNAME" \
  --instance-type t1.micro --group default --region us-east-1 \
  --key YOUR-KEY 

This technique was adapted from a more comprehensive example published by Marius Ducea.

Talk Back