cookbook : propagate list from node to fill template values

59 views Asked by At

I have a list of veriables in node file in cookbook as

"normal": {
        "Data_list": 'one, two, three, four',
    "tags": [

    ]
}

based on this list i want to add values to template , below is the source fro same , but it seems instead of running case and if statement ,it is adding all the logic as it is in template as simple text.

<%= [node['data_list']].each do |data|
     case data
     when 'one'
          "this is one and this will be added in template"
     when 'two'
          "this is two and this will be added in template"
     when 'three'
          "this is three and this will be added in template"
     when 'four'
          "this is four and this will be added in template"
     default
          "this is default and this will be added in template"
     end
end %>

any help to identify where i am doing wrong will be much helpful

2

There are 2 answers

3
Jeff On

The JSON data for data_list is set as a single string and not an array. If I understand your question correctly, I think you need to use this as your JSON data:

"normal": {
  "data_list": ["one", "two", "three", "four"],
  "tags": []
}
1
seshadri_c On

When we use a case statement, we would typically choose from 1 of the options. By iterating over an Array in node['data_list'] we will match all or more than one condition.

However, the correct way to render the template with a case statement would be:

<% node['data_list'].each do |data| %>
  <% case data %>
  <% when 'one' %>
    'this is one and this will be added in template'
  <% when 'two' %>
    'this is two and this will be added in template'
  <% when 'three' %>
    'this is three and this will be added in template'
  <% when 'four' %>
    'this is four and this will be added in template'
  <% else %>
    'this is default and this will be added in template'
  <% end %>
<% end %>

Note: Due to iteration, any non matching array items will print the else part many times.

Of course for this to work, you would have to define data_list as an Array like Jeff suggested.

Update:

In a Chef template:

  • Bare text is rendered as it is. Example: "this is one.." (quotes included)
  • String/variable interpolation. Example: <%= node['hostname'] %> will render the hostname
  • Evaluate Ruby code. Example: <% if true %> evaluate if statement