0

我已经成功创建了一个 .rb 自定义事实,它解析一个内置事实以创建一个新值,但是我现在正尝试将它用作Puppet 的嵌套自定义事实。

我要创建的层次结构类似于内置事实,例如运行 Facter(或 Facter -p)将显示:

custom_parent => {
  custom_fact_1 => whatever
  custom_fact_2 => whatever2
}

木偶清单中的用法是:

$custom_parent.custom_fact_1

到目前为止,我已经尝试过领先的语法,例如:

Facter.add (:custom_parent)=>(custom_fact_1) do
Facter.add (:custom_parent)(:custom_fact_1) do
Facter.add (:custom_parent.custom_fact_1) do
Facter.add (:custom_parent:custom_fact_1) do
Facter.add (custom_parent:custom_fact_1) do

...然而,许多其他变体无法创建嵌套的自定义事实数组。我已经用谷歌搜索了一段时间,如果有人知道是否有可能,我将不胜感激。

我确实发现可以使用 /etc/puppetlabs/facter/facts.d/ 目录中的 .yaml 文件中的数组来创建嵌套事实,如下所示,但是这会设置 FIXED 值并且不会处理我在自定义中需要的逻辑事实。

{
  "custom_parent":
  {
    "custom_fact_1": "whatever",
    "custom_fact_2": "whatever2",
  }
}

提前致谢。

4

2 回答 2

3

我要创建的层次结构类似于内置事实,例如运行 Facter(或 Facter -p)将显示:

custom_parent => {
  custom_fact_1 => whatever
  custom_fact_2 => whatever2
}

没有“嵌套”的事实。但是,存在“结构化”事实,这些事实可能具有哈希值作为其值。就 Facter 呈现您将其描述为“嵌套”的输出而言,这肯定是您正在查看的内容。

由于结构化事实值的元素本身不是事实,因此需要在事实本身的解析中指定它们:

Facter.add (:custom_parent) do
    {
        :custom_fact_1 => 'whatever',
        :custom_fact_2 => 'whatever2',
    }
end

whateverandwhatever2不需要是文字字符串;它们或多或少可以是任意的 Ruby 表达式。当然,您也可以将成员与创建哈希分开设置(但在相同的事实解析中):

Facter.add (:custom_parent) do
    value = new Hash()
    value[:custom_fact_1] = 'whatever'
    value[:custom_fact_2] = 'whatever2'
    value
end
于 2018-06-25T20:20:54.310 回答
0

谢谢@John Bollinger。您的示例非常接近,但是我发现我需要使用 type => aggregate 和 chunk 才能使其工作。我还将它与定义的函数结合起来,最终结果基于下面的代码。

如果您有任何其他建议来提高代码一致性,请随时指出。干杯

# define the function to process the input fact
def dhcp_octets(level)
  dhcp_split = Facter.value(:networking)['dhcp'].split('.')
  if dhcp_split[-level..-1]
    result = dhcp_split[-level..-1].join('.')
    result
  end
end

# create the parent fact
Facter.add(:network_dhcp_octets, :type => :aggregate) do
  chunk(:dhcp_ip) do
    value = {}

# return a child => subchild array
    value['child1'] = {'child2' => dhcp_octets(2)}

# return child facts based on array depth (right to left)
    value['1_octets'] = dhcp_octets(1)
    value['2_octets'] = dhcp_octets(2)
    value['3_octets'] = dhcp_octets(3)
    value['4_octets'] = dhcp_octets(4)

# this one should return an empty fact
    value['5_octets'] = dhcp_octets(5)
    value
  end
end
于 2018-06-26T10:00:17.297 回答