Search code examples
ruby-on-railsrubyruby-on-rails-3chef-infrachef-recipe

how to do chef map & sort in templet file


Presently I have following code in recipe

hadoop_nodes = search(:node, "(role:mapreduce-datanode OR role:mapreduce-namenode) AND chef_environment:#{node.chef_environment} AND domain:#{node['domain']}")
hadoop_nodes.map!{ |h| {:host_entry => "#{h['ipaddress']} #{h['fqdn']} #{h['hostname']}"}}
hadoop_nodes.sort!{ |x, y| x[:host_entry] <=> y[:host_entry] }

And template file which has

<%- @hadoop_nodes.each do |hadoop_node| -%>
<%= hadoop_node[:host_entry] %>
<%- end -%>

I want to move

hadoop_nodes.map!{ |h| {:host_entry => "#{h['ipaddress']} #{h['fqdn']} #{h['hostname']}"}}

to template file, but don't know how to, any help


Solution

  • Templates are really no different to normal code, except that you need to add the markers.

    • <% for code.
    • <%= for something you want output.

    As they are both loops around the object, you don't have to change much:

    <% @hadoop_nodes.each do |hadoop_node| %>
    <%=   "#{hadoop_node['ipaddress']} #{hadoop_node['fqdn']} #{hadoop_node['hostname']}" %>
    <% end %>
    

    Your request leaves out the sort though. You can do this as well:

    <% @hadoop_nodes.sort{|x, y| x['hostname'] <=> y['hostname'] }.each do |hadoop_node| %>