Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create file using template.erb

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?

like image 855
noMAD Avatar asked Oct 05 '12 15:10

noMAD


People also ask

What is an ERB template?

An ERB template looks like a plain-text document interspersed with tags containing Ruby code. When evaluated, this tagged code can modify text in the template. Puppet passes data to templates via special objects and variables, which you can use in the tagged Ruby code to control the templates' output.

How do ERB files work?

An ERB object works by building a chunk of Ruby code that will output the completed template when run. If safe_level is set to a non-nil value, ERB code will be run in a separate thread with $SAFE set to the provided level. eoutvar can be used to set the name of the variable ERB will build up its output in.

What are the necessary steps to get from file ERB to file HTML?

erb file into a string, create an ERB object, and then output the result into an html file, passing the current binding to the ERB. result method. where @my_erb_string . You could then write the html string into an html file.


2 Answers

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
like image 58
fl00r Avatar answered Oct 15 '22 19:10

fl00r


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
like image 34
Draco Ater Avatar answered Oct 15 '22 17:10

Draco Ater