puppet中命名的代码模块,经常需要被使用,如如重写则代码冗余,使用定义一组通用目标的资源,可在puppet全局调用,就能解决这类问题,类可以被继承,也可以包含子类。
类的语法格式有两种,调用类的方法常用的有三种,可以在类中传递参数等灵活的操作,如以下实例:
class webserver { #类申明后续调用后才生效,调用的方法常用的有三种
$webpkg = $operatingsystem ? {
/(?i-mx:(centos|redhat|Fedora))/ => 'httpd',
/(?i-mx:(Ubuntu|debian))/ => 'apache2',
default => 'httpd',
}
package{"$webpkg":
ensure => installed,
}
file{'/etc/httpd/conf/httpd.conf':
ensure => file,
owner => root,
group => root,
source => '/root/testmanifests/httpd.conf',
require => Package["$webpkg"],
notify => Service['httpd'],
}
service{'httpd':
ensure => running,
enable => true,
}
}
include webserver #使用include进行调用
#申明调用类的第二种方法
class web($webserver='httpd') { #向类中传递参数
package{"$webserver":
ensure => installed,
before => [ File['httpd.conf'], Service['httpd'] ],
}
file{'httpd.conf':
path => '/etc/httpd/conf/httpd.conf',
source => '/root/testmanifests/httpd.conf',
ensure => file,
}
service{'httpd':
ensure => running,
enable => true,
restart => 'systemctl restart httpd.service',
subscribe => File['httpd.conf'],
}
}
class{'web':
webserver => 'apache2', #调用类
}
[root@node1 ~]# puppet apply -v --noop class2.pp
Notice: Compiled catalog for node1.alren.com in environment production in 1.53 seconds
Info: Applying configuration version '1480596978'
Notice: /Stage[main]/Web/Package[apache2]/ensure: current_value absent, should be present (noop)
Notice: /Stage[main]/Web/File[httpd.conf]/content: current_value {md5}3dfa14b023127a3766bddfe15fe14b9a, should be {md5}8b01e334a6e975b659df5dd351923ccb(noop)
Info: /Stage[main]/Web/File[httpd.conf]: Scheduling refresh of Service[httpd]
Notice: /Stage[main]/Web/Service[httpd]: Would have triggered 'refresh' from 1 events
Notice: Class[Web]: Would have triggered 'refresh' from 3 events
Notice: Stage[main]: Would have triggered 'refresh' from 1 events
Notice: Finished catalog run in 0.65 seconds
[root@node1 ~]#
类的继承:子类可继承父类的资源属性,同时可定义父类不存在的额资源属性,一个父类可同时被多个子类所继承
class nginx { #定义父类信息
package{'nginx':
ensure => installed, #安装程序包
}
service{'nginx': #启动程序
ensure => running,
enable => true,
require => Package['nginx'],
}
}
class nginx::web inherits nginx { #继承父类的原有属性,同时增加file资源属性
file{'ngx-web.conf':
path => '/etc/nginx/conf.d/ngx-web.conf',
ensure => file,
require => Package['nginx'],
source => '/root/testmanifests/nginx/ngx-web.conf',
}
file{'nginx.conf':
path => '/etc/nginx/nginx.conf',
ensure => file,
content => template('/root/testmanifests/nginx.conf.erb'), #此模板需事先存在方可使用
require => Package['nginx'],
}
Service['nginx'] {
subscribe => [ File['ngx-web.conf'], File['nginx.conf'] ], #通知其他资源进行刷新操作
}
}
include nginx::web #调用声明的类
五、puppet模板(此内容不过多解释,需自行加强)