在厨师食谱中编写Ruby类
我正在尝试“清理”我的厨师食谱以安装Zabbix代理,我知道有一百万,但这是我的测试案例,以供我理解。我将我的厨师指令分为一个类,并为每个需要完成的步骤提供单独的方法。我把这个类放在配方文件中。因此,当我执行配方时,我收到以下错误:在厨师食谱中编写Ruby类,ruby,chef-infra,chef-recipe,Ruby,Chef Infra,Chef Recipe,我正在尝试“清理”我的厨师食谱以安装Zabbix代理,我知道有一百万,但这是我的测试案例,以供我理解。我将我的厨师指令分为一个类,并为每个需要完成的步骤提供单独的方法。我把这个类放在配方文件中。因此,当我执行配方时,我收到以下错误: NoMethodError ------------- undefined method `execute' for #<Class:0x000000030e42c0>::Recipe_Zabbix_Agent_Unix nomethoderor --
NoMethodError
-------------
undefined method `execute' for #<Class:0x000000030e42c0>::Recipe_Zabbix_Agent_Unix
nomethoderor
-------------
未定义的#:Recipe_Zabbix_Agent_Unix的方法“execute”
我绝不是Ruby大师,所以我想,我打赌这个类将自己从Chef继承中“分离”,所以我需要使用
让类继承Chef库一般来说,基于类的资源放在库文件中,而不是食谱中。有关使用Poise在基于类的资源中获取LWRP DSL元素的示例,请参见。您可以创建一个将配方作为参数的类,以便资源定义方法在范围内
在库/有用的东西.rb
中:
class UsefulThing
def initialize(blah)
@blah = blah
end
def apply(recipe)
# Chef resources use instance_eval for blocks, which hides self
outer_self = self
recipe.directory "/foo/#{@blah}" do
user ...
group outer_self.latest_group
...
end
...
end
...
end
ut = UsefulThing.new(...)
ut.apply(self)
然后在recipes/default.rb
中:
class UsefulThing
def initialize(blah)
@blah = blah
end
def apply(recipe)
# Chef resources use instance_eval for blocks, which hides self
outer_self = self
recipe.directory "/foo/#{@blah}" do
user ...
group outer_self.latest_group
...
end
...
end
...
end
ut = UsefulThing.new(...)
ut.apply(self)
在重量级提供程序中,您没有访问Chef DSL的权限。我如何继承这些提供程序?使用类形式execute=Chef::Resource::execute.new(command)
我是否必须为我放入其中的Ruby类中的每个“Chef块”都这样做?是的,您必须这样做。因此,我将类作为库文件编写,然后需要或包含它,然后从中调用我想要的函数?所有cookbook库文件都是由Chef在converge开始时自动加载的。我认为您和@sethvargo都是正确的,因为我要做的是,我必须按照他说的做,并将Chef函数分配给我的类中的execute等对象,我的类属于库。因为我试图在我的类中调用Chef函数,所以我将首先尝试sethvargo的想法,然后尝试将我的代码放入库文件夹。@Pred进行得如何?我想我没有通过@vikingsteve。我最终放弃了课堂上的想法,只使用函数。如果您检查我链接的代码,我只声明一些def
。