How to append the content in the file for chef cookbook?

5.9k Views Asked by At

I'm new in chef and cookbook. I'm creating a cookbook, and I want to append at the end of file some contents (text). At the moment, I'm using:

file "#{node['dir']}/#{params[:name]}.txt" do
   content "my full text"
end

but I must always append in the "content" the old content because it will overwrite. Is there another way to append contents?

Thank you pasquy

3

There are 3 best solutions below

2
On

You could you use direct ruby code if you wanted like

open('myfile.out', 'a') do |f|
f << "and again ...\n"
end

That could be done in a ruby_block provider if you wanted. This link describes how to use that type of block

Another alternative is to read in your files contents and then concatenate that with the updated string in your current block?

1
On

Please don't use direct Ruby to do this. There's a built-in class in Chef called FileEdit that will handle this for you. Specifically, you probably want insert_line_if_no_match.

0
On

If you only use ruby code, then chef will write contents at load time of your recipe BEFORE checking any dependencies. And definitely not during convergence.

A combination of ruby and chef will do the trick.

file = File.open(#{node['dir']}/#{params[:name]}.txt, "rb")
existingContents = file.read
newContents = existingContents + "my full text"

file "#{node['dir']}/#{params[:name]}.txt" do
   content newContents
end

So the idea is build the string at load time, pass that string to chef and let chef change the contents at right stage during convergence.