首页 > 解决方案 > 如何在每个循环的 hiera_hash 中设置 puppet 类变量?

问题描述

分层数据

ae::namespace_by_fqdn_pattern:
  '((^dfw-oel6)|(^dfw-oel7)|(^dfw-ubuntu1604))-((client))([0-9]{2}).pp-devcos-ae.us-central1.gcp.dev.blah.com': '/test/blah/regression/client'
  '((^dfw-oel6)|(^dfw-oel7)|(^dfw-ubuntu1604))-((server))([0-9]{2}).pp-devcos-ae.us-central1.gcp.dev.blah.com': '/test/blah/regression/server'

班级

class ae {
    $namespace              = hiera('ae::namespace')
    $target_host_patterns   = hiera('ae::target_host_patterns')
    hiera_hash('ae::namespace_by_fqdn_pattern').each |String $pattern, String $ns| {
        if $facts['networking']['fqdn'].match($pattern) {
            $ae::namespace = "${ns}"
        }
    }
    <snip>

...产量

Error: Could not retrieve catalog from remote server: Error 500 on SERVER: Server Error: Illegal attempt to assign to 'ae::enforcerd_namespace'. Cannot assign to variables in other namespaces (file: /etc/puppetlabs/code/environments/ar/modules/ae/manifests/init.pp, line: 21, column: 13) on node dfw-ubuntu1604-client02.pp-devcos.us-central1.gcp.dev.blah.com

...这里有人知道如何正确执行此操作吗?试图有条件地覆盖该 $ae::namespace 变量,但我太无知了,不知道如何让它工作:(

循环和模式匹配位起作用。只是无法弄清楚如何从 hiera_hash().each 循环中正确设置该类变量。

标签: puppethiera

解决方案


如何在每个循环的 hiera_hash 中设置 puppet 类变量?

你不能。调用的关联块each()为每次迭代建立一个本地范围。内的变量分配适用于该本地范围,因此仅在块的一次执行期间持续。无论如何,您不能在变量的生命周期内为其分配新值,因此即使您可以从each()调用中分配给类变量,也很难使用该功能(并且您的方法不起作用)。

有几种方法可以在不修改数据形式的情况下解决问题。例如,您可以利用该filter()功能,但我个人的建议是使用该reduce()功能,如下所示:

$namespace = lookup('ae::target_host_patterns').reduce(lookup('ae::namespace')) |$ns, $entry| {
  $facts['networking']['fqdn'].match($entry[0]) ? { true => $entry[1], default => $ns }
}

这几乎完全符合您的原始代码似乎正在尝试做的事情,除了reduce()调用返回选定的命名空间,通过类范围内的代码将其分配给变量,而不是 lambda 试图直接分配它。另请注意,它不仅要测​​试模式,还要在没有模式匹配时分配默认命名空间,因为它需要这样做,因为您只能分配给namespace变量一次。


推荐阅读