如何将文件内容分配给chef节点属性

时间:2016-04-25 21:21:25

标签: ruby ruby-on-rails-3 chef chef-recipe chef-solo

我在fingreprint.txt

位置"#{node['abc.d']}/fingreprint.txt"

文件内容如下:
time="2015-03-25T17:53:12C" level=info msg="SHA1 Fingerprint=7F:D0:19:C5:80:42:66"

现在我想检索指纹的值并将其指定给chef属性
我使用以下红宝石块

ruby_block "retrieve_fingerprint" do  
    block do  
        path="#{node['abc.d']}/fingreprint.txt"  
        Chef::Resource::RubyBlock.send(:include, Chef::Mixin::ShellOut)  
        command = 'grep -Po '(?<=Fingerprint=)[^"]*' path '  
        command_out = shell_out(command)  
        node.default['fingerprint'] = command_out.stdout  
    end  
    action :create  
end  

由于command = 'grep -Po '(?<=Fingerprint=)[^"]*' path '中缺少转义字符,似乎无法正常工作。 如果有其他方法可以将文件内容分配给节点属性

,请告诉我

1 个答案:

答案 0 :(得分:1)

有两种方法可以回答这个问题:首先我会在Ruby中进行读取(IO.read)和解析(RegExp.new和朋友)而不是炮轰grep

if IO.read("#{node['abc.d']}/fingreprint.txt") =~ /Fingerprint=([^"]+)/
  node.default['fingerprint'] = $1
end

其次,根本不要这样做,因为它可能不会表现出你的期望。您必须考虑两遍加载过程以及每次运行时重置默认属性的事实。如果您正在尝试制作Ohai插件,请改为使用。如果您尝试在以后的资源中使用此数据,您可能希望将其存储在全局变量中,并大量使用lazy {}帮助程序。