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

▼魔方 西西 提交于 2019-12-03 11:33:17

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.

Konzulic

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: monit@ourservice.com }
#---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

The easiest way to tackle this would be to create a string and pass it to content. Of course bash blocks work... but I think file resources are elegant.

lines = ""
File.open('input file') do |f|
   f.lines.each do |line|
      lines = lines  + line + "\n"
   end
end
file "file path"  do
   content line
end
Ranjith Kumar G

Here is the example ruby block for inserting 2 new lines after match:

ruby_block "insert_lines" do
  block do
    file = Chef::Util::FileEdit.new("/etc/nginx/nginx.conf")
    file.insert_line_after_match("worker_rlimit_nofile", "load_module 1")
    file.insert_line_after_match("pid", "load_module 2")
    file.write_file
  end
end

insert_line_after_match searches for the regex/string and it will insert the value in after the match.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!