Take the 2-minute tour ×
Server Fault is a question and answer site for professional system and network administrators. It's 100% free, no registration required.

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?

share|improve this question

2 Answers 2

up vote 3 down vote accepted

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.

share|improve this answer

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'
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.