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 = Chef::Util::FileEdit.new('/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']}")
      file.write_file
   end
end

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.

Thoughts?

Thank you,
Gabriel

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. (http://github.com/chef-cookbooks/chef-client)

–Jp Robinson

1 Like

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.

Cheers!

  • Martin
1 Like

Thank you guys,

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

Best regards,
Gabriel