Search code examples
puppet

Puppet templates in templates and variable scopes


I've got a puppet 6.28 ERB template in a class that takes an array of hashes and iterates over it. Within each iteration it uses values from the hash and sets its own variables. Variables that come from puppet are prefixed with @ and those set in the template are just the bare name.

@puppetvar.each do |erbvar|
...
end

puppetvar is a parameter of the class.

Because there is some duplication within the iteration I'm trying to separate a sections into its own template, figuring I can include templates from within a template. With <%= scope.call_function('template', ["..."]) %> I can include a template in the template and have it rendered, but, I don't see to be able to find any of the variables I need. The scope of the sub-template appears to be solely and the same as the scope of the top-template, none of the variables set in the iteration are there not even erbvar.

Am I doing something wrong, misunderstanding scoping, etc?


Solution

  • Given the response by John Bollinger I went looking for pure ruby ways of doing this.

    <%= ERB.new(File.read(File.dirname(__FILE__) + "/" + "template.erb"), nil, nil, '_sub01').result(binding).strip %>
    

    Did what I wanted. The variables from puppet were still prefixed with @, and the variables set in that iteration of the top-level template were still available as bare words.

    The _sub01 thing was necessary or I was left with only what the "sub-template" output on the last iteration, with nothing at all from the top-level template. I must admit I don't know exactly what it does though.

    .strip just takes off some whitespace.