Search code examples
vagrantpuppetvagrant-provision

How to reuse class in Puppet


I have this puppet class

class project::className(
  $program_name = '',
  $command = ''
) {
   ....
}

And I'm using it like this

class { 'project::classname':
  program_name => 'programe_name',
  command => 'ls /dev/'
}

This works fine, but when I used it twice like this

class { 'project::classname':
  program_name => 'programe_name',
  command => 'ls /dev/'
}

class { 'project::classname':
  program_name => 'programe_name2',
  command => 'ls /dev/'
}

Vagrant Provision is giving me this error

Error: Duplicate declaration: Class[project::classname] is already declared in file ..

How can I reuse the class?


Solution

  • You need understand the difference of class and defined types.

    Classes Vs Defined Types

    Classes are not to be thought of in the ‘object oriented’ meaning of a class. This means a machine belongs to a particular class of machine.

    For instance, a generic webserver would be a class. You would include that class as part of any node that needed to be built as a generic webserver. That class would drop in whatever packages, etc, it needed to do.

    Defined types on the other hand (created with ‘define’) can have many instances on a machine, and can encapsulate classes and other resources. They can be created using user supplied variables. For instance, to manage iptables, a defined type may wrap each rule in the iptables file, and the iptables configuration could be built out of fragments generated by those defined types.

    Usage of classes and defined types, in addition to the built-in managed types, is very helpful towards having a managable Puppet infrastructure.

    Refer: https://web.archive.org/web/20160305195130/https://docs.puppetlabs.com/guides/best_practices.html