Array attributes and how to use them in erb files

Hello again my friends,

I have another dilemma.

I need to declare one or more attributes (based on what kind of approach I’ll learn from you guys)
This attribute (attributes) will be used on an erb file to create one or more lines with what that variable contains.

To be more explicit, I’ll explain what my (wrong) approach was:
in attributes folder/default.rb:

default['my-cookbook']['IPs'] = ['','']
default['my-cookbook']['localIP'] = node['ipaddress']

in templates/default/file.xml.erb:

     <member><%= node['my-cookbook']['localIP']%></member>
     <% node['my-cookbook']['IPs'].each do |IP| %>
           <member><%= "#{IP}"%></member>
     <% end %>

That does not work. Besides, what if I don’t have any other IP?

Any suggestion is welcomed.

Thank you.

Best regards,

The approach looked ok to me, have you tried making the IP “variable” lowercase so it isn’t treated as a constant by the ERB template engine?

Also your xml is technically invalid as you do not close the <members> element, you close the <member-list> element instead (and to be more pedantic you’re missing an xml declaration).

Try this:

  <member><%= node['my-cookbook']['localIP']%></member>
<% node['my-cookbook']['IPs'].each do |ip| %>
  <member><%= "#{ip}" %></member>
<% end %>


Recipe: my-cookbook::default
  * template[c:\temp\file.xml] action create
    - create new file c:\temp\file.xml
    - update content in file c:\temp\file.xml from none to 6a123b
    --- c:\temp\file.xml        2016-05-07 22:10:04.000000000 +0100
    +++ c:\temp/chef-file.xml20160507-3336-1e8ngj5      2016-05-07 22:10:04.000000000 +0100
    @@ -1 +1,6 @@
    +  <member></member>
    +  <member></member>
    +  <member></member>

Thank you! Your solution worked like a charm.

Best regards,