ruby - 通过迭代 gem 查询输出来创建嵌套的 Puppet fact (Ruby)
问题描述
我有工作 Ruby 代码来查询 DNS 详细信息并创建 Puppet 自定义事实(puppet 5,Facter 3.11.6)但是我正在尝试修改它以从查询获得的键/值对创建嵌套事实。
用于使用键名设置单个事实的代码是:
require 'resolv'
Resolv::DNS::Config.default_config_hash.each do | key, value |
if !value.nil?
Facter.add("dns_#{key}") do
if value.is_a?(Array)
setcode { value.join(',') }
else
setcode { value }
end
end
end
end
从而创造了个人事实:
dns_nameserver => 192.168.1.1,192.168.1.2
dns_ndots => 1
dns_search => test.domain
到目前为止,我在“DNS”的父事实下创建嵌套事实的失败尝试是:
require 'resolv'
Facter.add("dns") do
value ={}
Resolv::DNS::Config.default_config_hash.each do | key, result |
if !result.nil?
if result.is_a?(Array)
setcode { value['#{key}'] = result.join(',') }
else
setcode { value['#{key}'] = result }
end
end
end
end
这给出了一个有限的结果:
dns => 1
我尝试过的其他代码似乎将数组输出放入字符串中,并且多个 IP 在方括号内被引用超过 2 行,而不是按照页面顶部的第一个代码块输出。
我试图实现的事实结构(通过修改页面顶部的代码)是:
dns => {
nameserver => 192.168.1.1,192.168.1.2,
ndots => 1,
search => test.domain,
}
提前感谢您的任何帮助。
解决方案
我终于在一位发布者的帮助下得到了这个,他在这里放了一些很棒的代码线索,但不幸的是不久之后就将其删除了。这是有效的代码:
require 'resolv'
Facter.add(:networking_dns) do
setcode do
Resolv::DNS::Config.default_config_hash.each_with_object({}) do | (key, value), sub|
if !value.nil?
sub[key] = value
sub
end
end
end
end
现在需要一些解释性说明(请随时纠正我或对此提供任何优化):
# the resolv gem is required
require 'resolv'
# create the parent fact (has no value of its own)
Facter.add(:networking_dns) do
# start building instructions in the fact
setcode do
# use the resolv gem to lookup values in /etc/resolv.conf and add .each to process all key/value pairs returned
# also add _with_object({}) and sub in the variables to set a blank value for sub. Saves doing it separately. Sub can be any name but denotes the declaration for the nested facts
Resolv::DNS::Config.default_config_hash.each_with_object({}) do | (key, value), sub|
# create facts only when the value is not nil
if !value.nil?
sub[key] = value
sub
# using a closing blank entry for a nested fact is critical or they won't create! Place this outside of the case statement to prevent blank values
end
end
end
end
# use the appropriate number of ends and indent for readability
感谢在删除之前在此处发布指导的人。如果您再次发帖,我想为您投票。
欢迎任何有关优化可行解决方案的提示,因为我仍在掌握 Ruby(在这上面花了几个小时!)
推荐阅读
- r - 如何根据字符串过滤行,但前提是字符串出现多次
- excel - VBA代码在列中查找字符串,然后按空格将字符串拆分到偏移位置
- reactjs - Firebase 动态链接不适用于带有电容器的 ios
- hive - 如何在 2.2.0 以上版本的 hive 中开启隐式类型转换?
- javascript - 问题设置从 react-native-location 取消订阅到状态变量
- angular - Angular / .NET Core 项目上的 Cors 问题
- php - 从 MySQL 获取项目数组
- algorithm - 如何在 ECC 中创建构造函数点?(请帮助)
- angular - 如何使用离子打字稿解决 Firebase 未捕获的错误?
- asp.net - IIS下的VB自动实现属性