How to generate a config file from node attribute (array) with Chef

chefruby

One of chef node's attributes is an array of hashes:

"array_of_hashes": [
      {
        "hash_key_1": "value1",
        "hash_key2": "value2",
      },
      {
        "hash_key_2": "value4",
        "hash_key_1": "value3",
      }
    ]

I need to cycle through every array element and generate a configuration file with template parameters defined by values in hashes:

# cat my_config.conf
key1=value1; key2=value2
key1=value3; key2=value4

I can't achieve this result using template resource because it owerwrites the config file (doesn't append it) on every cycle iteration and I get only the last string as a result.

What's the best way to generate such a config file mentioned above?

Best Answer

Can you use a bash block?

http://wiki.opscode.com/display/chef/Resources#Resources-Script

So, something like:

bash "append_to_config" do
  user "root"
  cwd "/path/to/config/directory"
  code <<-EOH
  echo "#{node[:array_of_hashes][:hash_key]}=#{node[:array_of_hashes][:hash_value]}" > my_config.conf
  EOH
end

Plus whatever loops, conditions, etc., you would need to make that work.