noM*_*MAD 12 ruby erb chef-infra
我是红宝石和厨师的新手,我想知道是否有办法使用模板创建文件?我试着搜索它但找不到太多东西.我尝试创建一个黑名单文件,并通过厨师插入一些正则表达式.所以我想template.erb在运行chef时添加属性并使用a 来创建文件.任何暗示,指针?
Dra*_*ter 23
Chef具有名为template的特殊资源,用于从模板创建文件.您需要将模板放在cookbook的templates/default目录下,然后在配方中使用它,提供变量.
cookbooks/my_cookbook/templates/default/template.erb:
# template.erb
A is: <%= @a %>
B is: <%= @b %>
C is: <%= @c %>
cookbooks/my_cookbook/recipes/default.rb:
template "/tmp/config.conf" do
  source "template.erb"
  variables( :a => 'Hello', :b => 'World', :c => 'Ololo' )
end
require 'erb'
class Foo
  attr_accessor :a, :b, :c
  def template_binding
    binding
  end
end
new_file = File.open("./result.txt", "w+")
template = File.read("./template.erb")
foo = Foo.new
foo.a = "Hello"
foo.b = "World"
foo.c = "Ololo"
new_file << ERB.new(template).result(foo.template_binding)
new_file.close
所以a,b和c现在菱在你的模板中的变量
IE
# template.erb
A is: <%= @a %>
B is: <%= @b %>
C is: <%= @c %>
结果=>
# result.txt:
A is Hello
B is World
C is Ololo