Jacques Betancourt
Jacques Betancourt

Reputation: 2802

Writing file with multiple Chef cookbooks all targeting the same file

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:

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

Upvotes: 3

Views: 839

Answers (1)

Tensibai
Tensibai

Reputation: 15784

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.

Upvotes: 2

Related Questions