【问题标题】:Puppet - create NESTED custom factPuppet - 创建嵌套的自定义事实
【发布时间】:2018-12-03 03:18:00
【问题描述】:

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

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

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

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

提前致谢。

【问题讨论】:

标签: ruby hashmap puppet facter


【解决方案1】:

我要创建的层次结构类似于内置事实,例如 运行 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 Bollinger 提供的示例和 Matt Schuchard 将我指向正确的页面
【解决方案2】:

谢谢@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

【讨论】:

  • 我很高兴你能成功。但是,我向您保证,没有必要将其作为一个总体事实来实现。即使您不接受我的权威保证,但您的汇总决议只有一大块这一事实也表明确实如此。
  • @JohnBollinger,你是对的。初始测试仅使用聚合进行,但是一旦从最终代码中删除并将“块”替换为“setcode do”,它仍然可以按需要运行。但是,子事实似乎确实需要用单引号括起来,而不是以冒号开头。再次感谢。
猜你喜欢
  • 2017-10-11
  • 1970-01-01
  • 2015-07-17
  • 2013-10-08
  • 1970-01-01
  • 2013-03-09
  • 2021-09-18
  • 1970-01-01
  • 2021-12-17
相关资源
最近更新 更多