Chef Template : Using a nested object to generate a configuration file

165 Views Asked by At

I would like to generate a config file from a Chef template. What is the correct syntax for achieving this in Chef 13+

I have a databag with the following sub keys:

"mykey1" : {
  "param1" : "mysubvalue1",
  "param2" : "mysubvalue2"
},
"mykey2" : {
  "param1" : "mysubvalue11",
  "param2" : "mysubvalue22"
},

Then in my recipe I use the template resource:

template 'mytemplate.erb'
  ...
  variables ({
     :keys => [mykey1, mykey2]
  })
end

Then in the template:

<% @keys.each_pair do |name, _object| %>
  ["#{name}"]
  param1 = "#{_object.param1}"  # will this work??
<% end %>

What is the correct way to reference the param1 and param2

2

There are 2 best solutions below

0
On

By the time you get the data like that, it's a normal Ruby hash object. So you would use _object["param1"].

0
On

Coming here years later? Try this:

<% @keys.each_pair do |name, _object| %>
["#{name}"]
<%   _object.each do |param, sub| -%>
  <%= param %> = "<%= sub %>"
<%   end # _object.each -%>
<% end   # keys.each -%>

let me know how it goes.