简体   繁体   中英

How to use a chef helper library from another chef cookbook in a ruby_block

AWS Opsworks: Chef version 11.10, Berkshelf version 3.2.0.

I can't figure out how to use a helper library from cookbook A in a ruby_block in cookbook B.

I found a post discussing how to include a method in a ruby_block and another discussing how to share libraries across cookbooks but I can't get both working at the same time.

cookbookA/libraries/helpers.rb

module libraryA
    module Helpers
        def log(output)
            Chef::Log.info("#{cookbook_name}:#{recipe_name}: #output}")
        end
    end
end

cookbookB/metadata.rb

depends 'cookbookA'

The following setup.rb works.

cookbookB/recipes/setup.rb

 ::Chef::Recipe.send(:include, libraryA::Helpers)
 log("this is a log")

However, when I use the log function in a ruby block, it fails. The following setup.rb does not work:

cookbookB/recipes/setup.rb

 ::Chef::Recipe.send(:include, libraryA::Helpers)
 ruby_block "logging-function" do
      block do
           log("this is a log")
      end
 end

PS: I have also tried using ::Chef::Resource.send(:include, libraryA::Helpers)

Updated code block:

::Chef::Recipe.send(:include, libraryA::Helpers) 
ruby_block "logging-test" do 
    block do 
        ::Chef::Recipe.send(:include, libraryA::Helpers)    
        ::libraryA::Helpers.ttlog("message") 
    end 
end

Received error: NoMethodError - undefined method ttlog for libraryA::Helpers:Module

Updated helpers

cookbookA/libraries/helpers.rb

def log(output)
    Chef::Log.info("#{cookbook_name}:#{recipe_name}: #output}")
end

PS: Removed the modules structure

I think ruby_block runs in other context, under other object. You can try to include that library into provider, but I can't guarantee it would work.

::Chef::Provider::RubyBlock.send(:include, libraryA::Helpers)

ps. Resource does have definition and list of parameters, but code is executed from Provider.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM