这种事情在厨师食谱中很常见:
%w{foo bar baz}.each do |x|
file "#{x}" do
content "whatever"
end
end
Run Code Online (Sandbox Code Playgroud)
但我想读取与菜谱保存的文件循环的项目,例如:
File.open('files/default/blah.txt').each do |x|
file "#{x}" do
content "whatever"
end
end
Run Code Online (Sandbox Code Playgroud)
如果我给出了blah.txtchef-client碰巧缓存它的完整路径,那么这是有效的,但它不可移植.如果我像在示例中那样编写它,它"无效","希望"当前目录是cookbook的根目录.有没有办法在编制食谱时获取cookbook根目录?
在 Chef 11 中,您可以聪明地使用 Dir 通配符来实现您想要的行为:
禁用资产的延迟加载。启用延迟资产加载后,Chef 将在 Chef 客户端运行期间根据请求获取资产(如说明书文件、模板等)。在您的用例中,您需要在配方执行开始之前这些资产存在于服务器上。将以下内容添加到client.rb:
no_lazy_load true
Run Code Online (Sandbox Code Playgroud)查找磁盘上食谱缓存的路径。这是一点点魔法和实验,但是:
"#{Chef::Config[:file_cache_path]}/cookbooks/NAME"
Run Code Online (Sandbox Code Playgroud)获取正确的文件:
path = "#{Chef::Config[:file_cache_path]}/cookbooks/NAME/files/default/blah.txt"
File.readlines(path).each do |line|
name = line.strip
# Whatever chef execution here...
end
Run Code Online (Sandbox Code Playgroud)您可能还想看看您Cookbook.preferred_filename_on_disk是否关心使用文件特异性处理程序。