Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

updating file using 'file' chef-solo resource

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?

like image 750
itsme Avatar asked Dec 08 '22 21:12

itsme


2 Answers

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 .bashrcand 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
like image 176
user272735 Avatar answered Dec 30 '22 19:12

user272735


As @user272735 's suggestion, a clean way to modify .bashrc is:

  1. write all your modification in a .bashrc_local file,
  2. include your specific settings to .bashrc.

For step 1, we can use template resource. For step 2, I prefer use line cookbook.

Sample codes as below,

templates/bashrc_local.erb

export JAVA_HOME=/usr/lib/java/jdk1.7.0_05
export PATH=$PATH:/usr/lib/java/jdk1.7.0_05/bin

recipes/default.rb

# add bashrc_local
template "#{ENV['HOME']}/.bashrc_local" do
  source 'bashrc_local.erb'
  mode 00644
end

# update bashrc
append_if_no_line "add bashrc_local" do
  path "#{ENV['HOME']}/.bashrc"
  line "if [ -f ~/.bashrc_local ]; then . ~/.bashrc_local; fi"
end
like image 29
user5698801 Avatar answered Dec 30 '22 19:12

user5698801