在Puppet中改变节点声明中的类变量



我试图为我所有的服务器创建一个"模板"。我有两种构型。NTP客户端(在基类类中处理)。我想通过在节点声明中声明一些特定的东西来为NTP服务器创建一个特定的覆盖。比如"baseclass::ntp:restrict => true "。或者,我将如何改变一个已经声明的变量从基类::ntp?

有人有什么好主意吗?

这是我目前为止写的:

templates.pp

class baseclass {
    include defaultusers
    include sudoers
    include issue
    class { ntp:
            ensure => running,
            servers => ['ntpserver1.host.com',
                        'ntpserver2.host.com',],
            autoupdate => false,
    }
}

nodes.pp

node default {
    include baseclass
}
node "ntpserver1.host.com" inherits default {
    <some code here to declare new variable in baseclass::ntp>
    <some code here to change existing variable, such as "ensure">
}

您遇到了参数化类的问题:它们不支持覆盖。它们应该是这样的,但是由于Puppet中事物初始化顺序的各种问题,您不能覆盖类的参数。一旦你设置了它们,你就完成了。这与定义不同,在定义中,重写参数按预期工作。这是一个公开的bug,我们很多人已经投票并正在关注,但似乎没有什么进展。

考虑到这一点,我的建议是将参数化的ntp类重定义为定义类,因为定义类将完全按照您的需要工作。将类更改为如下内容:

define ntp($servers, $autoupdate = false, $ensure = 'running') {
  # ... put code from class here ...
}

,然后将基类更改为:

ntp { $fqdn:
  servers => [ 'ntpserver1.host.com',
               'ntpserver2.host.com',],
}

您必须更改类结构以添加新类,因为您不能从节点中的类继承,因此将节点更改为:

node "ntpserver1.host.com" inherits default {
  include hosts::ntpserver1
}

或者你想命名的每台主机配置类。然后,在这个类中,你可以做你期望能够做的事情:

class hosts::ntpserver1 inherits baseclass {
  Ntp["$fqdn"] { ensure => 'stopped' }
}

我知道这看起来像是一个巨大的迂回,特别是如果你习惯于在节点内做一堆东西(不参与类继承树)。但是,如果不能覆盖类的参数,似乎就没有一个好的替代方案。(我们管理500多个节点和大约100个完全独立的服务定义,数百个模块和大量主机之间的变化,包括每台主机的覆盖,使用这种方法,它工作得非常好。)

TL,DR summary:不能重写类参数。一旦将参数传递给Puppet中的类,就完成了。您可以覆盖定义参数。因此,您想要重写的任何内容最好写成定义而不是类。但是,请记住,重写层次结构意味着必须将节点定义的核心放在类中,因为只有类才能继承和重写另一个类。因此,如果您大量使用覆盖,请养成让节点定义简单的习惯(只包括一个完成所有工作的类),以便您的类可以继承基类并覆盖定义的参数。

我接受了rra的回答,但我发现了一个对我更好的解决方案。这是一个小hack,我想:

template.pp

class baseclass ($ntprestrict = 'false') {
    include defaultusers
    include sudoers
    include issue
    class { ntp:
            ensure => running,
            servers => ['ntpserver1.host.com',
                        'ntpserver2.host.com',],
            autoupdate => false,
            restrict => $ntprestrict,
    }
}

nodes.pp

node "ntpserver1.host.com" {
    class { baseclass: ntprestrict => 'true' }
}
node "client.host.com" {
    class { baseclass: ntprestrict => 'false' }
}

最新更新