updating file using 'file' chef-solo resource

chef-infra, ruby

Solution

Use Chef::Util::FileEdit. Below is an example how I modify `.bashrc`. The idea here is that I just add:

# Include user specific settings
if [ -f ~/.bashrc_user ]; then . ~/.bashrc_user; fi

to the end of default `.bashrc`and all other modifications take place in `.bashrc_user` that is part of my cookbook.

cookbook_file "#{ENV['HOME']}/.bashrc_user" do
  user "user"
  group "user"
  mode 00644
end

ruby_block "include-bashrc-user" do
  block do
    file = Chef::Util::FileEdit.new("#{ENV['HOME']}/.bashrc")
    file.insert_line_if_no_match(
      "# Include user specific settings",
      "\n# Include user specific settings\nif [ -f ~/.bashrc_user ]; then . ~/.bashrc_user; fi"
    )
    file.write_file
  end
end

Problem

i am trying to install java using `chef-solo`. The problem is to set the `JAVA_HOME` and `PATH` variables in `/etc/profile` file. I tried using `'file'` resource provided by chef. here is some of my code: ``` java_home = "export JAVA_HOME=/usr/lib/java/jdk1.7.0_05" path = "export PATH=$PATH:/usr/lib/java/jdk1.7.0_05/bin" execute "make_dir" do cwd "/usr/lib/" user "root" command "mkdir java" end execute "copy" do cwd "/usr/lib/java" user "root" command "cp -r /home/user/Downloads/jdk1* /usr/lib/java" end file "/etc/profile" do owner "root" group "root" action :touch content JAVA_HOME content PATH end ``` but the problem is `content` command overrides all the content of file, is there any way to UPDATE the file while using chef-solo resources. Thanks! UPDATE: i have found some code from `chef-recipe`, but i am not sure what it does exactly, the code is.. ``` ruby_block "set-env-java-home" do block do ENV["JAVA_HOME"] = java_home end end ``` Does it set JAVA_HOME variable for only that instance or permanently? Can anybody help?

Original source