简体   繁体   中英

Edit file using chef

I know there are a lot of answers plus solved ones too but nothing seems to work for me, What I'm trying to do is I want to add few lines of code after tomcat is completed with it's installation in /var/lib/tomcat8/conf/catalina.properties file.

here is what i have tried so far the simple ruby way and with chef utils too.

File.open("/var/lib/tomcat8/conf/catalina.properties", "a+") do |f|
  f << "\n"
  f << "javax.xml.parsers.DocumentBuilderFactory=com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl"
end


ruby_block "insert_line" do
  block do
    file = Chef::Util::FileEdit.new("/var/lib/tomcat8/conf/catalina.properties")
    file.insert_line_if_no_match("/javax.xml.parsers.DocumentBuilderFactory=com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl/", "javax.xml.parsers.DocumentBuilderFactory=com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl")
    file.write_file
  end
end



file '/var/lib/tomcat8/conf/catalina.properties' do
   action :create
   owner 'root'
   group 'root'
   content File.open("/var/lib/tomcat8/conf/catalina.properties", "a+") do |f|
      f << "\n"
      f << "javax.xml.parsers.DocumentBuilderFactory=com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl"
    end
end



file '/var/lib/tomcat8/conf/catalina.properties' do
   action :create
   owner 'root'
   group 'root'
   content File.open("/var/lib/tomcat8/conf/catalina.properties", "a+") do |f|
      f << "\n"
      f << "javax.xml.parsers.DocumentBuilderFactory=com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl"
    end
end

I tried putting puts "testing" and it seems that chef isn't even getting into code.

Check out the poise-file and line cookbooks for examples of how to do this more safely.

We overall do not recommend this approach as it creates very brittle code that is often non-convergent (as you noticed). The better method is to use a template resource to control the entire file in a convergent manner.

There is a fundamental flaw with this logic as chef-client will append the lines regardless if they are already in the file every time it runs. I also don't think Chef really likes this approach.

If you don't want to manage the whole file as a template, then you should use the sous-chef/line-cookbook as it has conditionals / guards built into it to prevent this problem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM