木偶:分享类之间的信息

我认为在Puppet中还没有一个正确的方法来处理(但是),但是这样做让我感到满意。

我希望我的课程能够影响另一个课程中的模板文件的内容,这样我们就可以避免重复信息,并将信息放在其所属的位置。

比如我们有一个“iptables”类,以及各种服务类,比如“postfix”,“webappfoo”等

class webappfoo { $myfwrules +> [ "-A INPUT -p tcp --state NEW -m tcp --dport 80 -j ACCEPT" ] include apache } node webappserver { include webappfoo include iptables } 

但是这是行不通的。 $ myfwrules数组只包含webappfoo中的那一行。

请注意,一个类可以读入另一个类; 例如在这里iptables可以只读$ iptables :: myfwrules; 但我不希望iptables必须了解webappfoo。

这是一个范围问题。 从语言教程 :

类,组件和节点引入了一个新的范围。 Puppet当前是dynamic范围的,这意味着范围层次结构是根据代码的评估位置创build的,而不是定义代码的位置。

所以$myfwrules被定义在它定义的类中。在你的情况下,你将它webappfoowebappfoo类,它不知道任何以前定义的$myfwrules 。 你可以绕过这个,但更好的方法可能是使用定义 。 像这样(未经testing,YMMV等):

 class iptables { define rule($rule) { # $title is the 'name' of the resource, like ntpd in service { "ntpd": } exec { "rule-$title": command => "/sbin/iptables $rule" } } } class webappfoo { include iptables iptables::rule { "webappfoo": rule => "-A INPUT -p tcp --state NEW -m tcp --dport 80 -j ACCEPT" } } class postfix { include iptables iptables::rule { "postfix": rule => "-A INPUT -p tcp --state NEW -m tcp --dport 25 -j ACCEPT" } } node foo { include webappfoo include postfix } 

通过这种方式,您可以使用可重复使用的方法将规则添加到类中,而无需定义variables并担心范围。 你最终会得到一堆代表节点foo规则集的Exec资源( Exec["rule-webappfoo"]Exec["rule-postfix"] )。

另请参阅现成的iptables模块 。

编辑 :这只是一个例子来演示如何使用定义。 这并不意味着没有问题的解决scheme。 首先,围绕规则可能被应用的顺序(可能会before / after使用)以及每次调用/sbin/iptables的效率都存在问题。

我决定使用模板和多个连接来构buildiptables规则。 例如

 define iptables::rules { file { "$local_rules_file": ensure => "file", content => template($iptables_start, "iptables/iptables.$name.erb", $iptables_stop) } } 

这不是很好,它需要每个计算机专用的iptables.hostname.erb文件。 但它简单愚蠢。

也读了Puppet的商店configuration和多文件连接。

我有一段时间没有碰过木偶,所以我的语法可能有点生疏。 应该“+>”是“+ =”吗? 无论如何,你试过这个吗?

 class webappfoo {
    包括apache
 }
 class webappfoo :: myfwrules {
     $ webappfoo_myfwrules = [“-A INPUT -p tcp --state NEW -m tcp --dport 80 -j ACCEPT”]
 }
节点的webappserver {
    包括iptables

     $ webapplist = [“webappfoo”,“webappbar”]
     $ webappserver_myfwrules => $ iptables :: iptables_myfwrules

     $ webappserver_myfwrules + = $ webapplist?  {
          webappfoo => $ webappfoo :: myfwrules :: webappfoo_myfwrules,
          webappbar => $ webappbar :: myfwrules :: webappfoo_myfwrules,
     }
 }

这iptables模块似乎是做我想要的唯一方法; 它基本上是一个脚本,它接受iptables.d /目录中的文件,并从中build立/ etc / sysconfig / iptables。 这可能是我要使用的; 但是我觉得这种模式在Puppet本身应该是可能的。