Access Node attributes in Chef Library

主宰稳场 提交于 2019-11-30 05:14:45

You don't have access to the node object in a library unless you pass it into the initializer:

class MyHelper
  def self.get_inputs_for(node)
    # Your code will work fine
  end
end

Then you call it with:

inputs = MyHelper.get_inputs_for(node)

Alternative, you can to create a module and mix it into the Chef Recipe DSL:

module MyHelper
  def get_inputs
    # Same code, but you'll get "node" since this is a mixin
  end
end

Chef::Recipe.send(:include, MyHelper)

Then you have access to the get_inputs method right in a recipe:

inputs = get_inputs

Notice this is an instance method versus a class method.

In short, libraries don't have access to the node object unless given as a parameter. Modules will, if they are mixed into the Recipe DSL. Additionally, the node object is actually an instance variable, so it's not available at the class level (i.e. self.).

Arya

I think there is a scoping issue here as the Node's scope is under Chef::Recipe. So try omitting MyLib in the definition and see if it works. I have a library defined this way that works:

class Chef
  class Recipe
    def my_library_method
      #access node stuff here should be fine
    end
  end
end
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!