【问题标题】:How to use a chef helper library from another chef cookbook in a ruby_block如何在 ruby​​_block 中使用另一本厨师食谱中的厨师助手库
【发布时间】:2015-11-02 23:10:12
【问题描述】:

AWS Opsworks:Chef 版本 11.10,Berkshelf 版本 3.2.0。

我不知道如何在食谱 B 的 ruby_block 中使用食谱 A 中的帮助程序库。

我发现 post 讨论如何在 ruby​​_block 中包含一个方法,another 讨论如何跨说明书共享库,但我无法同时工作。

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'

以下 setup.rb 有效。

cookbookB/recipes/setup.rb

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

但是,当我在 ruby​​ 块中使用日志功能时,它会失败。 以下 setup.rb 不起作用:

cookbookB/recipes/setup.rb

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

P.S.:我也试过使用::Chef::Resource.send(:include, libraryA::Helpers)

更新代码块:

::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

收到错误:NoMethodError - libraryA::Helpers:Module 的未定义方法 ttlog

更新的助手

cookbookA/libraries/helpers.rb

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

P.S: 移除了模块结构

【问题讨论】:

  • 根据 Sethvargo 在第一个链接上的回答,您提供的库已加载到全局命名空间中,因此您可以使用对您的方法的完全限定访问:block { libraryA::Helpers.log("message") } 应该这样做。 (旁注:我确实使用了括号而不是 do end ,因为我将它写成一个衬里,但这不会改变行为)
  • 嗨。谢谢回复。我尝试过使用完全限定的访问权限。但我收到一个错误“未定义的方法 `log'”。
  • 您可以用完整的错误输出更新问题吗? (它是否显示完全限定的方法?)我还建议使用另一个名称以避免与厨师 log 资源冲突
  • @Tensibai 嗨。回复较晚,抱歉。该错误未显示完全限定的方法。它显示(ttlog 是方法名称 - 从日志更改它)NoMethodError ------------- undefined method ttlog for Chef::Resource::RubyBlock
  • 您是否在 ruby​​ 块中使用了完整的方法?问题的更新可能会很好地了解错误来自哪里

标签: ruby chef-infra


【解决方案1】:

我认为 ruby​​_block 在其他上下文中运行,在其他对象下。 您可以尝试将该库包含到提供程序中,但我不能保证它会起作用。

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

ps。资源确实有定义和参数列表,但是代码是从Provider执行的。

【讨论】:

  • 嗨。谢谢回复。我确实记得阅读过有关提供者的信息。但是,目前我们的代码不是基于提供者的。然而,我们计划很快转移到供应商。当我们这样做时,我一定会尝试的。
猜你喜欢
  • 2015-05-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-01-29
相关资源
最近更新 更多