Created
December 17, 2012 21:08
-
-
Save srinivasmohan/4322269 to your computer and use it in GitHub Desktop.
Update /etc/hosts based on a template usinf Knife/Chef provided info.
This file contains 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
#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) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.