jsierles (owner)

Forks

Revisions

gist: 31100 Download_button fork
public
Public Clone URL: git://gist.github.com/31100.git
Embed All Files: show embed
Ruby #
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
#!/usr/bin/env ruby
#
# fetch hosts from amazon EC2 meta-data
#
# Based on http://dysinger.net/2008/10/13/using-amazon-ec2-metadata-as-a-simple-dns
#
 
%w(logger optparse rubygems right_aws resolv pp).each { |l| require l }
 
LOGGER = Logger.new("/var/log/fetch_hosts.log")
 
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[:aws_access_key_id] = aki
  end
  p.on("-s",
       "--secret-key PASSWORD",
       "The user's AWS secret access key.") do |sak|
    options[:aws_secret_access_key] = sak
  end
 
  p.on_tail("-h", "--help", "Show this message") {
    puts(p)
    exit
  }
  p.parse!(ARGV) rescue puts(p)
end
 
original_hosts = File.open("/etc/hosts")
File.open("/etc/hosts.bak", "w") {|f| f.write original_hosts }
 
hosts = "127.0.0.1 localhost.localdomain localhost\n"
 
if options.key?(:aws_access_key_id) and options.key?(:aws_secret_access_key)
 
  RightAws::Ec2.new(options[:aws_access_key_id], options[:aws_secret_access_key], :logger => LOGGER).describe_instances.each do |r|
    hostname = r[:aws_groups].select { |g| g =~ /^host:/ }.to_s.gsub("host:", "")
    if r[:aws_state] =~ /running/
      hosts << Resolv::DNS.new.getaddress(r[:private_dns_name]).to_s +" #{hostname}.int #{hostname}"
    end
  end
  File.open("/etc/hosts", "w") {|f| f.write hosts }
else
  puts(parser)
  exit(1)
end