Notes on Life, ‘Puters and Hawaii

Using Amazon EC2 Metadata as a Simple DNS

I use the amazon metadata for creating /etc/hosts and do this on a cron schedule. This does everything I need. Instead of fancy DynDNS tricks or having to run and manage an internal DNS server I just have a ruby script that looks at the metadata ec2 to build /etc/hosts. It’s easy. To set it up yourself and try it all you need are 3 easy steps.

Step 1- Start each of your instances with unique named key that matches what you want their internal hostname to be. Such as “onion” or “potato” or whatever you want to call them.

Step 2- Make sure you have ruby, rubygems and amazon-ec2 (rubygem) installed. Then create a ruby script in /usr/local/sbin/hosts that has the following:

#!/usr/bin/env ruby
%w(optparse rubygems EC2 resolv pp).each { |l| require l }
options = {}
parser = OptionParser.new do |p|
  p.banner = "Usage: hosts [options]"
  p.on("-a", "--access-key USER", "The user's AWS access key ID.") do |aki|
    options[:access_key_id] = aki
  end
  p.on("-s",
       "--secret-key PASSWORD",
       "The user's AWS secret access key.") do |sak|
    options[:secret_access_key] = sak
  end
  p.on_tail("-h", "--help", "Show this message") {
    puts(p)
    exit
  }
  p.parse!(ARGV) rescue puts(p)
end
if options.key?(:access_key_id) and options.key?(:secret_access_key)
  puts "127.0.0.1 localhost"
  EC2::Base.new(options).describe_instances.reservationSet.item.each do |r|
    r.instancesSet.item.each do |i|
      if i.instanceState.name =~ /running/
        puts(Resolv::DNS.new.getaddress(i.privateDnsName).to_s +
             " #{i.keyName}.ec2 #{i.keyName}")
      end
    end
  end
else
  puts(parser)
  exit(1)
end

Step 3- Setup a cron job to update /etc/hosts as often as you like. I do it once per hour on all my machines

0 * * * * /usr/local/sbin/hosts -a myaccess -s mysecret >/etc/hosts

All my machines have this ec2 security key + script + cron approach. I do not have to run dyndns or any private dns servers to keep track of all my internal server ip addresses. My /etc/hosts looks like the following on the three machines in the test cluster:

127.0.0.1 localhost
10.252.202.221 oahu.ec2 oahu
10.253.115.175 maui.ec2 maui
10.253.114.190 hawaii.ec2 hawaii

Leave a Reply