plain_file.rb 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. def write_new_file(name, new_line, owner, group)
  2. file name do
  3. content "#{new_line}\n"
  4. owner owner
  5. group group
  6. action :create
  7. end
  8. end
  9. action :replace do
  10. if ::File.exists? new_resource.name
  11. current_content = Chef::Util::FileEdit.new new_resource.name
  12. current_content.search_file_replace(new_resource.current_line, new_resource.new_line)
  13. current_content.write_file
  14. new_resource.updated_by_last_action(true)
  15. else
  16. Chef::Log.debug("replace action couldn't be performed. #{new_resource.name} does not exist")
  17. end
  18. end
  19. action :append do
  20. if ::File.exists? new_resource.name
  21. open(new_resource.name, 'a') { |f| f.puts new_resource.new_line }
  22. else
  23. write_new_file(new_resource.name,
  24. new_resource.new_line,
  25. new_resource.owner,
  26. new_resource.group)
  27. end
  28. new_resource.updated_by_last_action(true)
  29. end
  30. action :insert_if_no_match do
  31. if ::File.exists? new_resource.name
  32. new_file = Chef::Util::FileEdit.new new_resource.name
  33. new_file.insert_line_if_no_match(new_resource.pattern,
  34. new_resource.new_line)
  35. new_file.write_file
  36. else
  37. write_new_file(new_resource.name,
  38. new_resource.new_line,
  39. new_resource.owner,
  40. new_resource.group)
  41. end
  42. new_resource.updated_by_last_action(true)
  43. end
  44. action :insert_after_match do
  45. if ::File.exists? new_resource.name
  46. new_file = Chef::Util::FileEdit.new new_resource.name
  47. new_file.insert_line_after_match(new_resource.pattern,
  48. new_resource.new_line)
  49. new_file.write_file
  50. else
  51. write_new_file(new_resource.name,
  52. new_resource.new_line,
  53. new_resource.owner,
  54. new_resource.group)
  55. end
  56. new_resource.updated_by_last_action(true)
  57. end
  58. action :remove do
  59. if ::File.exists? new_resource.name
  60. new_file = Chef::Util::FileEdit.new new_resource.name
  61. new_file.search_file_delete_line(new_resource.pattern)
  62. new_file.write_file
  63. new_resource.updated_by_last_action(true)
  64. end
  65. end