updating file using 'file' chef-solo resource

陌路散爱 提交于 2019-12-05 13:32:56

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

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

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.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!