-
-
Save shinzui/37010 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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 | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment