Skip to content

Instantly share code, notes, and snippets.

@srinivasmohan
Created December 17, 2012 21:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save srinivasmohan/4322269 to your computer and use it in GitHub Desktop.
Save srinivasmohan/4322269 to your computer and use it in GitHub Desktop.
Update /etc/hosts based on a template usinf Knife/Chef provided info.
#Rebuild hosts file from knife node list,
require 'erb'
require 'json'
require 'ohai' #to find my own IP
def myaddress
thissys=Ohai::System.new
thissys.all_plugins
myip=thissys['cloud']['private_ips'][0]
return myip
end
#This is called in the template file by erb
def findremoteip(name=nil)
return "#No such name" if name.nil?
svrname=name+'.somedomain.com'
nodes.search("name:#{svrname}") do |thisnode|
return "#{thisnode['cloud']['private_ips'][0]} #{name} #{svrname}" if thisnode['fqdn']==svrname
end
return "# No nodes entry for "+svrname
end
template='/etc/hosts.erb'
#These are used in the template.
scriptname="#{$0} #{$1}"
myip_ohai=myaddress
abort "Could not find my IP?" if myip_ohai.nil?
erb=ERB.new File.new(template).read,nil, '<>'
puts erb.result(binding)
@srinivasmohan
Copy link
Author

See https://gist.github.com/4322280 for hosts.erb. Assuming you have a chef/knife env fully setup, you can run "knife exec scripts/updhosts.erb > /etc/hosts" (as root) to update the /etc/hosts file on your management work station to update IP addresses of all the managed instances in hosts to be their internal (EC2, private) addresses.
If you management work station is outside EC2, then you could change findremoteip() to return node['cloud']['public_ips'][0] - This will populate your local hosts file with the public address of the instance. Of course, this wont help if your nodes are in a VPC.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment