如何从Chef Cookbook中的库访问当前节点? [英] 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.
例如,我希望能够做类似的事情在 cookbook / libraries / library.rb
中,然后从同一食谱中的食谱中使用它:
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
问题在于,Chef库文件中的节点
对象或 search
函数可用。
The problem is that, inside a Chef library file neither the node
object or search
function are available.
似乎可以使用 Chef进行搜索:: Search :: Query.new()。search(...)
,但找不到任何可用来访问 node
的东西。由此产生的错误是:
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
使用Chef 10.16.4。
Using Chef 10.16.4.
推荐答案
您可以做的是将模块包含在配方中。这样,您的模块函数就可以访问配方的方法,包括 node
。
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
或者,您可以将当前节点传递为函数的参数。这样,您就不需要包含模块(保留模块名称空间的好处),而具有更复杂的方法调用的缺点。
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.
这篇关于如何从Chef Cookbook中的库访问当前节点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!