我是大厨和红宝石的新手,我正在尝试实施一个厨师食谱,从我的食谱中不存在这些文件的目录中删除文件:
ruby_block 'cleandir' do
block do
Dir.foreach('/tmp/conf.d') do |item|
next if item.include?("#{node['logstash']['conf']['filelist']}") or item == '.' or item == '..'
# do work on real items
puts "deleting #{item}"
#File.delete("#{item}")
end
end
end
我定义了属性:
default['logstash']['conf']['filelist'] = [
'01-input-01-filebeat.conf',
'11-filter-01-syslog.conf',
'11-filter-02-iptables_geoip.conf',
'11-filter-03-named_querylog.conf',
'49-output-mail_01-grokparsefailure.conf',
'49-output-mail_02-error.conf',
'50-output.conf',
'51-output-stdout.conf'
]
这导致以下输出:
deleting 49-output-mail_02-error.conf
deleting 11-filter-01-syslog.conf
deleting 80-output.conf
deleting 50-output.conf
deleting 49-output-mail_01-grokparsefailure.conf
deleting 11-filter-03-named_querylog.conf
deleting 11-filter-02-iptables_geoip.conf
deleting 51-output-stdout.conf
deleting 01-input-01-filebeat.conf
预期输出应该只是deleting 80-output.conf
,因为它是唯一不属于节点属性数组的文件。
我不明白为什么包含?方法不匹配,我该如何进一步排除故障?
@Sebastian您的建议有效:
resolving cookbooks for run list: ["logstashConfig::clean_conf"]
Synchronizing Cookbooks:
- logstashConfig (0.0.4)
Installing Cookbook Gems:
Compiling Cookbooks...
Converging 1 resources
Recipe: logstashConfig::clean_conf
* ruby_block[cleandir] action run
deleting 80-output.conf
- execute the ruby block cleandir
Running handlers:
Running handlers complete
Chef Client finished, 1/1 resources updated in 02 seconds`
谢谢Sebastian和coderanger!
所以这是我迄今为止的解决方案,感谢@Sebastian和@coderanger:
ruby "cleandir" do
(Dir.entries("#{node['logstash']['conf']['path']}") - node['logstash']['conf']['filelist']).each do |name|
next if node['logstash']['conf']['filelist'].include?(name) or name == '.' or name == '..'
FileUtils.rm "#{node['logstash']['conf']['path']}/#{name}", :verbose => true
notifies :restart, 'service[restart_logstash]', :delayed
end
end
我不知道这是最好或最有效的方法,但它可以做我需要的,即删除不属于该菜谱的文件,并重新启动服务(如果找到并删除了它)。
答案 0 :(得分:0)
如果您将default['logstash']['conf']['filelist']
定义为字符串数组,并且item是单个字符串,那么您可以尝试使用以下内容:
next if node['logstash']['conf']['filelist'].include?(item) || item =~ /\./
...
可以使用item == '.' or item == '..'
简化item =~ /\./
。
答案 1 :(得分:0)
查看zap
食谱,以便更好地实施此功能。 Chef中的一般模式称为“累加器”,并且通常非常难以正确实现,但zap
至少是一个起点。或者你也可以这样做:
(Dir.entries("/tmp/conf.d") - node['logstash']['conf']['filelist']).each do |name|
::File.unlink("/tmp/conf.d/#{name}")
end
使用Arrays上的set操作来完成繁重的工作。