Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to test the result of applying a puppet template to given test parameters

Tags:

ruby

erb

puppet

I have the following puppet template file solr.json.erb:

{
  "servers" : [ {
    "port" : "<%= jmx_port %>",
    "host" : "localhost",

    "queries" : [
      <% @markets.each do |market| -%>
    {
      "outputWriters" : [ {
        "@class" : "com.googlecode.jmxtrans.model.output.StdOutWriter",
      } ],
      "obj" : "solr/market_<%= market %>:type=queryResultCache,id=org.apache.solr.search.LRUCache",
      "attr" : [ "hits","hitratio"]
    },
    <% end -%>
    ],
    "numQueryThreads" : 2
  } ]
}

and I want to test the result of applying the template to some test parameters before executing this in puppet.

how can I do that?

before, I tried with a script like this, my_script.ruby

require 'erb'
require 'ostruct'
namespace = OpenStruct.new(:jmx_port => 9200, :markets=> ['CH', 'FR'])
template = File.open("solr.json.erb", "rb").read;
puts ERB.new(template).result(namespace.instance_eval { binding })

but it didn't work out, because OpenStruct does not have instance variables, so I cannot use @markets.

the documentation mentions that you can check the syntax with this command: http://docs.puppetlabs.com/guides/templating.html

erb -P -x -T '-' mytemplate.erb | ruby -c

but that's not what i am asking. i am asking to get the result of applying some test parameters (jmx_port=9200, markets=['CH', 'FR']) to the template.

how can I do that?

like image 715
David Portabella Avatar asked Dec 21 '22 01:12

David Portabella


2 Answers

I dont think you need the openstruct stuff. This works for me:

require 'erb'
#Test Variables
jmx_port = 9200
@markets = ['CH', 'FR']

temp = File.open("testerb.erb", "rb").read;
renderer = ERB.new(temp)
puts output = renderer.result()

Though I did have to alter your template a fraction:

I've removed the - from the -%> you had in your template. These prevented it from compiling, as they're supposed to be paired with <%=

{
  "servers" : [ {
    "port" : "<%= jmx_port %>",
    "host" : "localhost",

    "queries" : [
      <% @markets.each do |market| %>
    {
      "outputWriters" : [ {
        "@class" : "com.googlecode.jmxtrans.model.output.StdOutWriter",
      } ],
      "obj" : "solr/market_<%= market %>:type=queryResultCache,id=org.apache.solr.search.LRUCache",
      "attr" : [ "hits","hitratio"]
    },
    <% end %>
    ],
    "numQueryThreads" : 2
  } ]
}
like image 82
Miles Wilson Avatar answered Apr 28 '23 04:04

Miles Wilson


If you turn on trim mode for ERB, you don't have to remove the "-%>" from the template:

renderer = ERB.new(temp, nil, '-')
like image 28
Chris Manly Avatar answered Apr 28 '23 06:04

Chris Manly