Parameterized classes are a language construct to help you structure your code better. It prevents you from excessively using global variables (like in your example).
Imagine you included 20 more classes in your node description and all would need some variables being set in the manifest's global or node scope. Also parameterized classes allow you to have default parameters easily, so you could use a default value for the $file_owner
instead of having to provide the same value (e. g. larry
) in several different places.
Your example snippet (with two additional nodes) could be written as follows:
node 'example.com' {
class { bar: }
}
node 'example.net' {
class { bar: owner = "harry" }
}
node 'example.net' {
class { bar: file_name = "barry.txt" }
}
class bar($owner = "larry", $file_name = "larry.txt") {
class { do_stuff: owner => $owner, file_name => $file_name }
}
class do_stuff($owner, $file_name) {
file { $file_name:
ensure => file,
owner => $owner,
}
}
With your usage of global variables, you'd need to declare a variable named $owner
in each node and you would not be able to overwrite the $file_name
variable/parameter per node. Instead you'd need to declare another bar
class for each node.
The document on Puppet's language evolution and of course the language guide provide some good examples on how to use parameterized classes and the rationale behind this language construct:
$bar::file_name
and$::file_owner
to access those respective variables. However, when using parametrized classes, the variables passed into a class via the parameters become locally scoped variables.