Skip to content

Instantly share code, notes, and snippets.

@vadv
Last active August 29, 2015 14:19
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vadv/8281db71218af7851f1e to your computer and use it in GitHub Desktop.
Save vadv/8281db71218af7851f1e to your computer and use it in GitHub Desktop.
actions :write
attribute :magic_line, :kind_of => String, :default => "# Managed by Chef, dont write below"
attribute :host_file, :kind_of => String, :default => "/etc/hosts", :name_attribute => true
attribute :lines, :kind_of => Array
action :write do
lines = new_resource.lines
magic_line = new_resource.magic_line
host_file = new_resource.host_file
content = ''
# копируем все что находится выше магической линии плюс ее саму
::File.read(host_file).split("\n").each do |line|
content += line + "\n"
break if line == magic_line
end
# необходимо выдать предупреждение если уже есть такой
# hostname или alias есть в /etc/hosts
lines.each do |line|
line.split[1..-1].each do |element|
log("[hosts::default] - #{element} already exists in /etc/hosts") { level :warn } if
content.include?(element)
end
end
# при первом проходе никакого magic_line у нас нет
content += magic_line + "\n" unless content.include?(magic_line)
# копируем линии из провайдера
content += lines.join("\n")
# добавляем завершаюший перевод строки
content += "\n"
# создает нам бакапы
file host_file do
owner "root"
group "root"
mode "0644"
content content
action :create
end
end
log("[hosts::default] - Converge /etc/hosts") { level :warn }
hosts_lines '/etc/hosts' do
lines node['hosts']['lines'].to_a
action :write
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment