问题
I have implemented two puppet modules to setup and configure two components - A & B. The directory structure of the modules folder looks like below:
modules
modulea
manifests
init.pp
install.pp
config.pp
service.pp
templates
1.properties.erb (This one is also needed by moduleb)
2.properties.erb (This one is also needed by moduleb)
moduleb
manifests
init.pp
install.pp
config.pp
service.pp
templates
1.properties.erb (same as in modulea)
2.properties.erb (same as in modulea)
3.properties.erb
4.properties.erb
5.properties.erb
The code in install.pp and service.pp is identical in both the modules. The code in config.pp of modulea deals with 2 property files, while code in config.pp of moduleb deals with 5 property files. Out of these 5 property files, 2 property files are exactly same as modulea, while 3 property files are specific to moduleb.
Pasted below is install.pp and service.pp code:
**init.pp of modulea**
class modulea::install inherits modulea {
package { $package_name: ensure => present }
}
**init.pp of moduleb**
class moduleb::install inherits moduleb {
package { $package_name: ensure => present }
}
**service.pp of modulea**
class modulea::service inherits modulea {
service { $service_name: ensure => running, }
}
**service.pp of moduleb**
class moduleb::service inherits moduleb {
service { $service_name: ensure => running, }
}
What options do I have to reduce code duplication and improve the maintainability of code? What options do I have so that I can easily add one more module in future that has same pattern?
回答1:
To avoid puppet code duplication, I usually create "common class". I also recommend using hiera to parametrize common class. More about hiera: https://docs.puppetlabs.com/hiera/1/
As an example: class common::installer:
modules
common
installer.pp
with code:
class common::installer {
$packages = hiera("common::installer::packages")
package { $packages:
ensure => latest,
}
}
Next in all modules add
require common::installer #or include common::installer, with this you will avoid "already defined" errors in puppet.
In hiera, depend on machine configuration you define proper value of common::installer::packages
e.g in machineA.yaml
common::installer::packages:
- packageA
- packageB
- packageC
in machineB.yaml
common::installer::packages:
- packageA
- packageB
- packageD
- packageE
This also gives you opportunity to install both modules A and B on one machine without any conflicts.
Just in hiera create proper config machineAandB.yaml with
common::installer::packages:
- packageA
- packageB
- packageC
- packageD
- packageE
You can also consider using ensure_package, to avoid annoying puppet errors with duplicated definition of packages, but with the code above i will not happen.
Similar code you can use to ensure that required services are running.
来源:https://stackoverflow.com/questions/27707014/how-to-deal-with-code-duplication-in-puppet-modules