如何使用当前的食谱模板目录,以循环的方式recursion复制所有模板与厨师

我试图找出如何构build模板(或文件,因为它的工作方式相同)文件夹的path,然后我可以读取它,并在循环中使用模板资源,所以每个模板文件可以触发通知变化。

我无法使用remote_directory,因为我只想在模板更改时通知服务。

我也想避免手动模板规范,因为这些目录中可能有很多文件。 另外,它可以让我们只改变模板文件夹中的configuration,而无需触摸配方。

主要的问题是像默认,主机,主机版本这些子目录和逻辑厨师通过确定正确的模板文件夹。 我在想,也许我可以从自定义食谱中调用一个厨师类的方法,以达到我的逻辑(循环)的起点。

应该是这样的我想:

entry_point = CHEF::...getEntryPointDir entry_point.glob.. .each do template fname do ... end end 

我将不胜感激任何帮助!

首先,这是你如何做一个食谱:

 # Get the Chef::CookbookVersion for the current cookbook cb = run_context.cookbook_collection[cookbook_name] # Loop over the array of files. # 'templates' will also work. cb.manifest['files'].each do |cookbookfile| Chef::Log("found: " + cookbookfile['name']) end 

我已经分享了一个示例配方来显示这个上下文。

在实践中,这需要更复杂 – 例如,您可能只需要菜谱中的文件/模板的一个子集,或需要以某种方式转换path。 考虑编写一个库函数,列出你感兴趣的文件列表,然后从你的配方中调用它。

感谢“zts”。 我创build了一个创build模板目录,其中包含所有的.erb文件。

 cb = run_context.cookbook_collection[cookbook_name] # you may get 'files' OR 'templates' from manifest cb.manifest['templates'].each do |tmpl_manifest| filepath = tmpl_manifest['path'] next if not filepath =~ /#{cmk_colo}\/server\/checks\/.*erb/ filename = tmpl_manifest['name'].split(".erb")[0] fileshortpath=filepath.split("/",3)[2] template "/opt/omd/sites/prod/etc/check_mk/conf.d/checks/#{filename}" do source fileshortpath mode '0644' owner 'prod' group 'prod' end end 

这个模板目录中的所有.erb文件将获得全长path。 如果path与要循环的目录名称匹配,则通过标准模板配方创build。

感谢@zts&@Zaur。 我想我会发布我的完整答案,最终结合起来。 最重要的是要注意,你的食谱名称必须在引号中。 这对我来说并不明显,在我的情况下有点阻碍。

第二,而不是使用@ Zaur的正则expression式search过滤文件path,我使用更多的“ruby-way”进行string比较来查看path是否包含特定的目录:

 # Get the Chef::CookbookVersion for this cookbook cb = run_context.cookbook_collection['cookbook_name'] # Loop over the array of files cb.manifest['files'].each do |cbf| # cbf['path'] is relative to the cookbook root, eg # 'files/default/foo.txt' # cbf['name'] strips the first two directories, eg # 'foo.txt' filepath = cbf['path'] filename = cbf['name'] next if not filepath.include? "directory-to-filter-for/" cookbook_file "/etc/service/conf.d/#{filename}" do source "directory-to-filter-for/#{filename}" mode 0600 owner "root" group "root" end end 

我正在使用这个文件,但你也可以使用模板。 只需在第14行replace“模板”块而不是“文件”块。然后将第5行改为使用模板而不是文件:

 cb.manifest['templates'].each do |cbf|