问题
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?
回答1:
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
回答2:
As @user272735 's suggestion, a clean way to modify .bashrc
is:
- write all your modification in a
.bashrc_local
file, - 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
回答3:
You can fix this by either using a template resource instead of a file resource, or if you are just appending those two variables, try doing this:
content "#{java_home}\n#{path}"
The second content line is overriding the first, as you have already discovered. You also don't need the action :touch
.
来源:https://stackoverflow.com/questions/12090914/updating-file-using-file-chef-solo-resource