12

我对 ruby​​ 和 chef 还很陌生,我想知道是否有办法使用模板创建文件?我尝试搜索它,但找不到太多东西。我尝试创建一个黑名单文件并通过厨师将一些正则表达式插入其中。所以我想template.erb在运行 chef 时添加属性并使用 a 创建文件。任何提示,指针?

4

2 回答 2

22

Chef 具有名为template的特殊资源,用于从模板创建文件。您需要将模板放在模板/默认目录下的食谱中,然后在您的食谱中使用它,并提供变量。

食谱/my_cookbook/templates/default/template.erb:

# template.erb
A is: <%= @a %>
B is: <%= @b %>
C is: <%= @c %>

食谱/my_cookbook/recipes/default.rb:

template "/tmp/config.conf" do
  source "template.erb"
  variables( :a => 'Hello', :b => 'World', :c => 'Ololo' )
end
于 2012-10-05T16:29:22.123 回答
6
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

所以ab现在c可以作为模板中的变量使用

IE

# template.erb
A is: <%= @a %>
B is: <%= @b %>
C is: <%= @c %>

结果 =>

# result.txt:
A is Hello
B is World
C is Ololo
于 2012-10-05T15:14:01.947 回答