Updating a file using a file "file" for the chef

I am trying to install java using chef-solo. The problem is to set the variables JAVA_HOMEand PATHfile /etc/profile. I tried to use the resource 'file'provided by the chef. here is 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 in the command contentcancels the entire contents of the file, is there a way to UPDATE the file when using chef-solo resources. Thank!

UPDATE: I found the code from chef-recipe, but I'm not sure what it does exactly, the code ...

ruby_block  "set-env-java-home" do
  block do
    ENV["JAVA_HOME"] = java_home
  end
end

Does the JAVA_HOME variable set only for this instance or permanently? Can anyone help?

+4
source share
3 answers

Chef:: Util:: FileEdit. .bashrc. , :

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

.bashrc, .bashrc_user, .

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
+12

, , , :

content "#{java_home}\n#{path}"

, . action :touch.

0

@user272735 .bashrc:

  • .bashrc_local,
  • .bashrc.

1 . 2 line cookbook.

Sample codes as shown 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
0
source

All Articles