使用配方中库的类方法

时间:2014-02-20 12:54:45

标签: chef

我只是想在厨师面前制作一本简单的食谱。我正在使用库作为学习过程。

module ABC
  class YumD
    def self.pack (*count)
      for i in 0...count.length
        yum_packag "#{count[i]}" do
          action :nothing
        end.run_action :install
      end
    end
  end
end

当我在配方中调用它时,我得到一个编译错误,上面写着

undefined method `yum_package' for ABC::YumD:Class

2 个答案:

答案 0 :(得分:4)

您无权访问图书馆内的Chef Recipe DSL。 DSL方法实际上只是完整的Ruby类的快捷方式。例如:

template '/etc/foo.txt' do
  source 'foo.erb'
end

实际上“编译”(读作:“被解释”)为:

template = Chef::Resource::Template.new('/etc/foo.txt')
template.source('foo.erb')
template.run_action(:create)

因此,在您的情况下,您希望使用YumPackage

module ABC
  class YumD
    def self.pack(*count)
      for i in 0...count.length
        package = Chef::Resource::YumPackage.new("#{count[i]}")
        package.run_action(:install)
      end
    end
  end
 end

答案 1 :(得分:2)

改进sethvargo的答案,这应避免undefined method events for nil:NilClass错误:尝试将run_context添加到构造函数调用中:

module ABC
  class YumD
    def self.pack(*count)
      for i in 0...count.length
        package = Chef::Resource::YumPackage.new("#{count[i]}", run_context)
        package.run_action(:install)
      end
    end
  end
 end