Using a Chef recipe to append multiple lines to a config file

As you said yourself, the recommended Chef pattern is to manage the whole file.

If you're using Chef 11 you could probably make use of partials for what you're trying to achieve.

There's more info here and on this example cookbook.

As long as you have access to the original config template, just append <%= render "original_config.erb" %> to the top of your parms_to_append.conf template.


As said before, using templates and partials is common way of doing this, but chef allows appending files, and even changing(editing) file lines. Appendind is performed using following functions:

  • insert_line_after_match(regex, newline);
  • insert_line_if_no_match(regex, newline)

You may find and example here on stackoverflow, and the full documentation on rubydoc.info

Please use it with caution, and only when partials and templates are not appropriate.


I did something like this:

monit_overwrites/templates/default/monitrc.erb:

#---FLOWDOCK-START
set mail-format { from: [email protected] }
#---FLOWDOCK-END

In my recipe I did this:

monit_overwrites/recipes/default.rb:

execute "Clean up monitrc from earlier runs" do
  user "root"
  command "sed '/#---FLOWDOCK-START/,/#---FLOWDOCK-END/d' > /etc/monitrc"
end

template "/tmp/monitrc_append.conf" do
  source "monitrc_append.erb"
end

execute "Setup monit to push notifications into flowdock" do
  user "root"
  command "cat /tmp/monitrc_append.conf >> /etc/monitrc"
end

execute "Remove monitrc_append" do
  command "rm /tmp/monitrc_append.conf"
end