3

I'm in a situation where, for ease of management reasons, I would like to use the same config file template for two classes. I only expect a small section of the config file to be different between the two, and since I expect both classes to be included for most nodes, I would like to have a simple conditional to determine which class is including the file.

As an example, let's assume both sensor and snuffler are included in the same node. I would like the template to look something like this

<% if scope.name == "sensor" %>
 include sensor/file1
 include sensor/file2
<% else %>
 include snuffler/file1
 include snuffler/file2
<% end %>

Is this possible directly or do I need to fall back to something like defining variables in the class definitions?

Scott Pack
  • 14,717
  • 10
  • 51
  • 83

2 Answers2

3

The easiest way to do this is to look at the scope.tags variable, and check for a member with the name of the class you're interested in. By default, a resource is tagged with it's type (like 'class' or 'type'), as well as the name of the defining resource (like 'sensor', or 'snuffler'). In my quick test I did something like this:

class other {
  file { '/etc/test':
    content => template('test/test.erb'),
  }
}

class test {
  file { '/etc/test':
    content => template('test/test.erb'),
  }
}

include test

With a template that looked like:

I am an erb template:
<% if scope.tags.member? 'test' %>
I was made in the Test class!
<% end %>

When called from the 'test' class, the extra content was displayed.

Kyle Smith
  • 9,563
  • 1
  • 30
  • 32
3

The "scope" variable refers to the Puppet::Parser::Scope class, which also seems to keep track of the source. You can refer to it with scope.source.name:

class classname::foo {
  notice(inline_template("scope='<%= scope.source.name %>'"))
}

prints

notice: Scope(Class[Classname::Foo]): scope='classname::foo'
Dominic Cleal
  • 3,120
  • 17
  • 16