2013-10-10 126 views
1

夥計們我不知道紅寶石,但被迫玩弄chef recipe。有人可以幫我解決一個語法問題嗎?廚師配方中的Ruby語法

這些線是造成問題,當我運行配方

old_configs = node["monitoring"]["configs"] || [] 

,異常是:

NoMethodError: undefined method `[]' for nil:NilClass /var/chef/cache/cookbooks/collectd/recipes/default.rb:100:in `from_file' 
/opt/chef/embedded/lib/ruby/gems/1.9.1/gems/chef-11.6.0/lib/chef/mixin/from_file.rb:30:in `instance_eval' 
/opt/chef/embedded/lib/ruby/gems/1.9.1/gems/chef-11.6.0/lib/chef/mixin/from_file.rb:30:in `from_file' 
/opt/chef/embedded/lib/ruby/gems/1.9.1/gems/chef-11.6.0/lib/chef/cookbook_version.rb:237:in `load_recipe' 
/opt/chef/embedded/lib/ruby/gems/1.9.1/gems/chef-11.6.0/lib/chef/run_context.rb:151:in `load_recipe' 
/opt/chef/embedded/lib/ruby/gems/1.9.1/gems/chef-11.6.0/lib/chef/run_context/cookbook_compiler.rb:139:in `block in compile_recipe 
/opt/chef/embedded/lib/ruby/gems/1.9.1/gems/chef-11.6.0/lib/chef/run_context/cookbook_compiler.rb:137:in `each' 
/opt/chef/embedded/lib/ruby/gems/1.9.1/gems/chef-11.6.0/lib/chef/run_context/cookbook_compiler.rb:137:in `compile_recipes' 
/opt/chef/embedded/lib/ruby/gems/1.9.1/gems/chef-11.6.0/lib/chef/run_context/cookbook_compiler.rb:74:in `compile' 
/opt/chef/embedded/lib/ruby/gems/1.9.1/gems/chef-11.6.0/lib/chef/run_context.rb:86:in `load' 
/opt/chef/embedded/lib/ruby/gems/1.9.1/gems/chef-11.6.0/lib/chef/client.rb:249:in `setup_run_context' 
/opt/chef/embedded/lib/ruby/gems/1.9.1/gems/chef-11.6.0/lib/chef/client.rb:492:in `do_run' 
/opt/chef/embedded/lib/ruby/gems/1.9.1/gems/chef-11.6.0/lib/chef/client.rb:199:in `block in run' 
/opt/chef/embedded/lib/ruby/gems/1.9.1/gems/chef-11.6.0/lib/chef/client.rb:193:in `fork' 
/opt/chef/embedded/lib/ruby/gems/1.9.1/gems/chef-11.6.0/lib/chef/client.rb:193:in `run' 
/opt/chef/embedded/lib/ruby/gems/1.9.1/gems/chef-11.6.0/lib/chef/application.rb:183:in `run_chef_client' 
/opt/chef/embedded/lib/ruby/gems/1.9.1/gems/chef-11.6.0/lib/chef/application/client.rb:302:in `block in run_application' 
/opt/chef/embedded/lib/ruby/gems/1.9.1/gems/chef-11.6.0/lib/chef/application/client.rb:294:in `loop' 
/opt/chef/embedded/lib/ruby/gems/1.9.1/gems/chef-11.6.0/lib/chef/application/client.rb:294:in `run_application' 
/opt/chef/embedded/lib/ruby/gems/1.9.1/gems/chef-11.6.0/lib/chef/application.rb:66:in `run' 
/opt/chef/embedded/lib/ruby/gems/1.9.1/gems/chef-11.6.0/bin/chef-client:26:in `<top (required)>' 

回答

4

這可能是由於一個事實,即節點「監控」屬性不存在引起,在嘗試查找節點[「monitoring」] [「configs」之前,您應該先檢查是否存在節點[「monitoring」]]

執行此操作的簡單方法是:

if node["monitoring"] 
    old_configs = node["monitoring"]["configs"] || [] 
end 
+5

另一個訣竅是使用Chef的屬性系統來定義一個默認值,以使if語句不必要。在'attributes/default.rb'中加入'default [「monitoring」] [「configs」] = []'。 –