Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using class methods from libraries in a recipe

Tags:

chef-infra

I am just trying to create a simple cookbook in chef. I am using libraries as a learning process.

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

When I call this in the recipe I get a compile error which says

undefined method `yum_package' for ABC::YumD:Class
like image 504
Sbal Avatar asked Mar 20 '23 12:03

Sbal


2 Answers

You do not have access to the Chef Recipe DSL inside libraries. The DSL methods are actually just shortcuts to full-blown Ruby classes. For example:

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

Actually "compiles" (read: "is interpreted") to:

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

So, in your case, you want to use 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
like image 109
sethvargo Avatar answered Apr 27 '23 03:04

sethvargo


To improve on sethvargo's answer, which should avoid the undefined method events for nil:NilClass error: try adding run_context to the constructor call:

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
like image 29
Jos Backus Avatar answered Apr 27 '23 04:04

Jos Backus