Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
857 views
in Technique[技术] by (71.8m points)

ruby - How can I access the current node from a library in a Chef cookbook?

I'm attempting to write a library for a chef cookbook that simplifies some common searches.

For example, I'd like to be able to do something like this in cookbook/libraries/library.rb and then use it from a recipe in the same cookbook:

module Example
    def self.search_attribute(attribute_name)
        return search(:nodes, node[attribute_name])
    end
end

The problem is that, inside a Chef library file neither the node object or search function are available.

Search seems to be possible by using Chef::Search::Query.new().search(...), but I can't find anything that works to access node. The resulting error from this is:

undefined local variable or method `node' for Example:Module

Using Chef 10.16.4.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

What you can do is to include the module in your recipe. That way, your module functions get access to the methods of the recipe, including node.

I normally do this for my library modules:

# my_cookbook/libraries/helpers.rb
module MyCookbook
  module Helpers
    def foo
      node["foo"]
    end
  end
end

Then, in the recipe, I include the module into the current instance of a recipe:

# my_cookbook/recipes/default.rb
extend MyCookbook::Helpers

That way, only the current recipe gets the module included, not all of them in the whole chef run (you thus avoid name clashes).

Alternatively, you could pass the current node as a parameter to the function. That way, you don't need to include the module (which has the upside of keeping the module namespaces) but has the downside of a more convoluted method call.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...