Chefのexecuteを使ってsedとかgrepとかでファイルの書き換えをせこせこしてたら
code.rb
execute "add_virtual_domain" do
not_if 'grep hogehoge virtual_domain'
command "sed -i '/^hoge.com/moge.com/g' virtual_domain"
end
@sawanoboly@github さんにChef::Util::FileEdit使えYOということでコードを書き換えました。
ポイントとしては、content _file.send(:contents).joinを使うとvirtual_domainsの全ての行を評価した後に実行するので以下となります。
node['postfix']['domain_list'] = ['hoge.com', 'moge.com']の時に
+hoge.com OK
-hoge.com OK
+moge OK
となってしまうので、_fe.write_fileで毎回write_fileしてしまうところがコツです。
setup_virtual_domain.rb
node['postfix']['domain_list'].each.with_index(1) do |domain, index|
ruby_block node['postfix']['action'] + '_' + domain + "_to_virtual_domains_#{index}" do
block do
_fe = Chef::Util::FileEdit.new('/etc/postfix/virtual_domains')
case node['postfix']['action']
when 'add'
_fe.insert_line_if_no_match('^' + domain + ' OK$', domain + " OK")
when 'delete'
_fe.search_file_delete_line('^' + domain + ' OK$')
end
_fe.write_file
end
notifies :run, 'execute[make_virtual_domains.db]'
end
end
end
end
# make virtual_domains.db
execute 'make_virtual_domains.db' do
action :nothing
user 'root'
cwd node['postfix']['etc']
command '/usr/bin/postmap /etc/postfix/virtual_domains'
notifies :reload, 'service[postfix]'
end
@sawanoboly@github さんありがとう!!
追記
ruby_block名が毎回同じ名前で実行されるので.each.with_indexで名前を変えてみました。