How can I use a Chef resource in a library module? (Or should I ...)?

I'm trying to better organize chef recipes by collecting common Ruby logic in a helper library. I saw examples declaring a class in a library (i.e. the Chef :: Recipe :: MyHelper Class) with several reusable methods inside. I also saw examples using the module in a similar way. In my case, I wanted to use the resource in several of these methods.

For example, let's say I want to provide a helper method that takes an array of service names and loops, stopping each of them using a service resource. I want to clean up the recipe files as much as possible and save some of this logic by simply calling the "stopServices (serviceList)" method.

If I define a helper library, for example:

class Chef::Recipe::MyHelper
  def self.stopServices(serviceList)
    serviceList.each do |svc|
      service "#{svc}" do
        action :stop
      end
    end
  end
end

:

MyHelper.stopServices(serviceList)

: "undefined " " Chef:: Recipe:: MyHelper: Class".

? ( , MyHelper )? , ? , - , , , , , , .

+4
1

Libraries - Ruby .

( DSL Chef),

  • Definitions ( ), Chef ;
  • LWRPs, , ( service , :start, :stop, :restart .. package , :install, :upgrade, :remove ..).

, :

# cookbooks/common/definitions/common_stop_services.rb
define :common_stop_services, :services => [] do
  params[:services].each do |svc|
    service svc do
      action :stop
    end
  end
end

:

# my_cookbook/recipes/my_recipe.rb
common_stop_services "my_recipe_services" do
  services [ 'svc1', 'svc2' ]
end

: , , , . - ( - , , ).

Obs2: CamelCase Classes Modules Ruby. .

Obs3: , , , Class. MyHelper, Module.

+1

Source: https://habr.com/ru/post/1536168/


All Articles