Puppet - 创建嵌套的自定义事实



我已经成功地创建了一个.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",
}
}

提前谢谢。

我想创建的层次结构类似于内置事实,例如 运行 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

whateverwhatever2不需要是文字字符串;它们可以或多或少是任意的 Ruby 表达式。 当然,您也可以在创建哈希时单独设置成员(但使用相同的事实解析(:

Facter.add (:custom_parent) do
value = new Hash()
value[:custom_fact_1] = 'whatever'
value[:custom_fact_2] = 'whatever2'
value
end

谢谢你@John布林格。 您的示例非常接近,但是我发现我需要使用 type => 聚合和块才能使其工作。 我还将其与定义的函数相结合,最终结果基于下面的代码。

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

# 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

最新更新