配方中属性的动态使用

时间:2015-04-20 13:31:02

标签: ruby chef lazy-evaluation recipe

我正在尝试增加值并在配方中动态使用另一个资源,但仍然无法做到这一点。

Chef::Log.info("I am in #{cookbook_name}::#{recipe_name} and current disk count #{node[:oracle][:asm][:test]}") 

bash "beforeTest" do

  code lazy{ echo #{node[:oracle][:asm][:test]} }

end

ruby_block "test current disk count" do
  block do
    node.set[:oracle][:asm][:test] = "#{node[:oracle][:asm][:test]}".to_i+1
  end
end

bash "test" do
  code lazy{ echo #{node[:oracle][:asm][:test]} }
end

但是我仍然会收到错误:

NoMethodError ------------- undefined method echo' for Chef::Resource::Bash 

Cookbook Trace: --------------- 
/var/chef/cache/cookbooks/Oracle11G/recipes/testSplit.rb:3:in block (2 levels) in from_file' 
Resource Declaration: --------------------- 
# In /var/chef/cache/cookbooks/Oracle11G/recipes/testSplit.rb 
1: bash "beforeTest" do 
2: code lazy{ 
3: echo "#{node[:oracle][:asm][:test]}" 
4: } 
5: end

请问你能帮助在bash中使用懒惰吗?如果不是懒惰还有其他选择吗?

2 个答案:

答案 0 :(得分:1)

bash "beforeTest" do   
  code lazy { "echo #{node[:oracle][:asm][:test]}" }   
end

你应该引用插值的命令来工作,如果不是ruby会搜索ruby上下文中未知的echo命令(因此你在日志中得到的错误)。

警告:懒惰必须是整个资源属性类似 WON' T 工作:

bash "beforeTest" do    
  code "echo node asm test is: #{lazy { node[:oracle][:asm][:test]} }"  
end

懒惰的评估需要一段红宝石代码,如here

所述

使用log资源可能会获得更好的结果:

log "print before" do
  message lazy { "node asm test is #{node[:oracle][:asm][:test]}" }
end

答案 1 :(得分:0)

在我想出lambda表达式之前,我一直在努力解决这个问题。但是,仅仅使用lambda并没有帮助我。所以我想到使用lambda和lazy评估。尽管lambda已经是延迟加载,但在编译chef recipe时,仍在评估调用lambda表达式的资源。因此,为了防止它被评估(不知何故),我将它放在一个懒惰的评估字符串中。

lambda表达式

app_version = lambda{`cat version`}

然后是资源块

file 'tmp/validate.version' do
    user 'user'
    group 'user_group'
    content lazy { app_version.call }
    mode '0755'
end

希望这也可以帮助别人:)或者如果你有更好的解决方案,请告诉我:)