使用’file’s chef-solo资源更新文件

我正在尝试使用chef-solo安装java。 问题是在/etc/profile文件中设置JAVA_HOMEPATH变量。 我尝试使用厨师提供的'file'资源。 这是我的一些代码:

 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 

但问题是content命令会覆盖文件的所有内容,有没有办法在使用chef-solo资源时更新文件。 谢谢!

更新:我已经找到了一些来自chef-recipe代码,但我不确定它究竟做了什么,代码是..

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

它是仅为该实例设置JAVA_HOME变量还是永久设置? 有人可以帮忙吗?

使用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 

您可以通过使用模板资源而不是文件资源来解决此问题,或者如果您只是附加这两个变量,请尝试执行以下操作:

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

正如您已经发现的那样,第二个内容行覆盖了第一个内容行。 你也不需要action :touch

作为@ user272735的建议,修改.bashrc一种简洁方法是:

  1. .bashrc_local文件中写下所有修改,
  2. 将您的特定设置包含在.bashrc

对于第1步,我们可以使用模板资源 。 对于第2步,我更喜欢使用line cookbook 。

示例代码如下,

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