Add text in an xml file


Hello guys,

As I’m pretty new with chef, I need to know what’s the best method using chef to add a line of text to an xml file if an attribute is true.
I thought of using

  ruby_block 'Edit xml file' do
    block do
      file ='/path/to/file.xml')
      file.insert_line_if_no_match("/something/", "something=#{node['recipe']['something']}")
      file.search_file_replace_line("/something/", "something=#{node['recipe']['something']}")

but what i need is to get to a certain text in that file, let’s say “some text with meaning” and replace it.
One other thing I need is to get to that “some text with meaning” line and to add a new line with some other text under it.


Thank you,


A better solution is to have chef control the xml file using a template, with appropriate if statements in the .erb file.

In config management fileedit and its like have been considered bad practice for a long time. It quickly becomes difficult to control rules in complex files, such as your xml, or to guarantee a rule is applied in an idempotent fashion.

With attributes and templates you should be able to work out what needs to be added where. If you need an example of a complex config using this method, take a look at templates/default/client.erb in the chef-client cookbook. (

–Jp Robinson


As others will tell you, it’s not the best approach; having Chef manage the entire file would be safer. But I did write a sort of XML-equivalent of the line cookbook, which you can find here. There’s a note in the README explaining why it’s not the best approach, but if you have no other choice, it’ll do in a pinch.


  • Martin


Thank you guys,

I’ll let chef control the xml file using a template.

Best regards,