Writing file with multiple Chef cookbooks all targeting the same file

833 views Asked by At

I have a situation where I have three cookbooks, each with a template resource that writes to an /etc/hosts file.

Rather than overwriting, I would like to append:

  • The first cookbook creates /etc/hosts file and writes lines 1,2,3.
  • The second cookbook appends lines 4,5. etc.

What's the right way to handle this in Chef land?

1

There are 1 answers

0
Tensibai On

You should better create a cookbook managing the file which generate it from attributes.

CookbookA/attributes/default.rb

default['hosts']['lines'] = []

CookbookA/recipes/genfile.rb

template "/etc/hosts" do
  source "hosts.erb"
end

CookbookA/templates/default/hosts.erb

#File Generated by Chef
<% node['hosts']['lines'].each do |l| %>
<% l -%>
<% end.unless node['hosts']['lines'].empty? %>

And then in your other cookbooks attributes files:

default['hosts']['lines'] << ["first line","second line"]

And have thoose cookbooks depends on CookbookA and in their recipe call include_recipe "CookbookA::genfile.rb"

Using << you append to the attribute instead of overwriting them.