Create file using template.erb

14,122

Solution 1

Chef has special resource named template, to create files from templates. You need to put your template inside cookbook under templates/default directory and then use it in your recipe, providing the variables.

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

Solution 2

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

So a, b and c now availible as a variables in your template

I.E.

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

Result =>

# result.txt:
A is Hello
B is World
C is Ololo
Share:
14,122
noMAD
Author by

noMAD

"State is the root of all evil"

Updated on June 08, 2022

Comments

  • noMAD
    noMAD almost 2 years

    I am fairly new to ruby and chef, I wanted to know if there is a way to create a file using a template? I tried searching about it but couldn't find much stuff. Am try to create a blacklist file and insert some regex into it via chef. So I wanted to add the attributes and use a template.erb to create the file while running chef. Any hints, pointers?