Sam Hammamy
Sam Hammamy

Reputation: 11017

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

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

Upvotes: 0

Views: 168

Answers (2)

user2066657
user2066657

Reputation: 481

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.

Upvotes: 0

coderanger
coderanger

Reputation: 54267

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

Upvotes: 1

Related Questions