0

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

roy
  • 6,344
  • 24
  • 92
  • 174
  • What does `@hadoop_data` contain? – cassianoleal Sep 05 '14 at 08:28
  • Corrected. Please check – roy Sep 05 '14 at 11:17
  • I know that doesn't answer your question, but I have to agree with @adam-jacob in that this code is probably best kept in the recipe. My usual rule for how much code to put in templates is "as little as possible to get the output I want". Code in templates is not very readable, whereas a recipe is pure code. – cassianoleal Sep 05 '14 at 14:52
  • That said, what will you do with the `.sort!`? If you keep it in the recipe, the `@hadoop_nodes` object will `.sort!` before it `.map!`. If you want to put it into the template as well, just go ahead and add each of those lines, wrapped in `<%- ... -%>`. It's not clear what you're trying to achieve. – cassianoleal Sep 05 '14 at 14:54

2 Answers2

1

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| %>
Matt
  • 68,711
  • 7
  • 155
  • 158
  • There are other tags in ERB. See [here](http://stackoverflow.com/questions/7996695/what-is-the-difference-between-and-in-erb-in-rails). – cassianoleal Sep 05 '14 at 14:58
0

Why would you want to move that in to the template file? It's probably better outside the template.

  • Hi Adam, Welcome to SO. The comment section just below the question can be used for clarifications like this. – Matt Sep 05 '14 at 10:01
  • I just want to make a list of all nodes with role mapred-datanode & mapred-namenode . then create a map for hosts file and then sort. – roy Sep 05 '14 at 11:21