Using Including Class Name in Conditionals with Puppet Templates

puppettemplate

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?

Best Answer

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.