在 puppet 中循环内容文件

问题描述

如何使用 puppet 遍历文件中的行? 我试图在我的清单中做这样的事情:

$tables = file('/home/myhome/tables')

$tables.each |String $table| {
    exec {"/usr/bin/${binary}":
        command => "/bin/echo '${table}'",}
}

我得到了错误

错误:无法从远程服务器检索目录:服务器上的错误 500:服务器错误:评估错误:评估函数调用时出错,无法从 /home/rraposo/tables(文件:/etc/puppetlabs)中找到任何文件/code/environments/production/manifests/11_fhc/alfresco-para-testes.pp,line: 92,column: 11) 在节点 fhc-prod-pt-alfresco-para-testes-01

我的文件有这样的行:

act_evt_log
act_evt_log_log_nr__seq
act_ge_bytearray
act_ge_property
act_hi_actinst
act_hi_attachment
act_hi_comment
act_hi_detail
act_hi_identitylink

解决方法

我假设您的代码位于 Puppet 服务器上,而 /home/myhome/tables 文件位于目标节点上,因此 Puppet 代理运行生命周期为;

  1. 代理将事实发送到 Puppet 服务器,您可以通过在命令行上运行 facter 来查看确切的事实。 Puppet 服务器唯一知道节点的是代理发送的事实。
  2. Puppet 服务器编译目录,这是运行 lambda 的点。
  3. 编译后的目录被发送回节点。
  4. 代理收到目录并纠正与目录的任何偏差。

对此的修复是以某种方式获取包含在发送到 Puppet 服务器的事实中的该文件的内容。您可以使用外部事实 https://puppet.com/docs/puppet/5.5/custom_facts.html#external-facts 来做到这一点。

您可以让 Puppet 部署一个文件 /etc/facter/facts.d/tables.sh,然后在该文件中包含类似的内容;

#!/usr/bin/env bash
tables=($(grep act_ /home/myhome/tables))
echo "tables=${tables[*]}"

这将包括一个名为 tables 的事实,该事实将包含一个数组,该数组列出了您的 lambda 应该能够使用的该文件的内容。

虽然这不是使用 Puppet 的好方法,但我们真正想要的是在代码中指定我们希望节点看起来像什么,然后应用它。有效地从节点读取配置文件允许它确定自己的配置。更好的解决方案是在 hiera https://puppet.com/docs/puppet/7.5/hiera_intro.html 中指定该列表,请查看此处的快速入门指南 https://puppet.com/docs/puppet/7.5/hiera_quick.html