Chef recipe read attributes from another node

I'm writing a very simple chef cookbook to manage the deployment of a web app, and I have a chef managed node for the database server, and would like to bring in the IP address (and a few other attributes) from that database server, into the recipe running on the app server...

For instance, in the recipe checking out the code on the app server, something like this..

hostname = node[:myapp][:dbserver_hostname]
attributes = chef_get_attributes_for_hostname(hostname)

connect_to_mysql_at_ip = attributes[:ipaddress]

I'm not sure if this is something you can do in chef easily? Struggling to find documentation on it. Thanks!


Solution 1:

I assume you've set up roles for web server, database server, etc.

Something like this in the app server recipe:

dbservers = Array.new

search(:node, "role:database_server") do |n|
  n["network"]["interfaces"]["eth0"]["addresses"].each_pair do |address,value|
    dbservers << address if value.has_key?("broadcast")
  end if n["network"]["interfaces"]["eth1"]
end

template "/path/to/app/config/appserver.conf" do
  source 'appserver.conf.erb'
  owner 'foo'
  group 'bar'
  mode 0644
  variables :dbservers => dbservers
end

Then your template will have something like:

<% @dbservers.each do |s| -%>
  connect_to_mysql_at_ip <%= s %>
<% end -%>

There might be a nicer way to get the IP address with Chef 0.10. I think the above code may have Chef 0.9 legacy in it, but it does work.