【问题标题】:Library doesn't process "DSL" for 'execute'库不处理“执行”的“DSL”
【发布时间】:2016-12-31 04:58:27
【问题描述】:

谁能帮我解决这个问题?

NoMethodError
-------------
undefined method `execute' for Chat::Mattermost:Class

相关文件内容:(文件名libraries/chat.rb

4:
5:  module Chat
6:    class Mattermost
7:
8:      def self.log_to_chat(message)
9>>       execute "echo" do
10:          command "echo #{message}"
11:        end
12:      end
13:
14:    end
15:  end
16:

我读到 DSL 语法在定义中不可用,所以我猜我需要做一些类似于 r = Chef::Resource::Execute.new("echo #{message}")r.run_command :run 的事情,但我不太确定该怎么做。

其他相关代码,我的方法是这样“调用”的:

log "this is a message" do
  level :info
  notifies :run, Chat::Mattermost.log_to_chat("#{name}"), :immediately
end

编辑:第二次尝试

NoMethodError
-------------
undefined method `events' for nil:NilClass

代码:

5:  require 'chef/resource/execute'
6:
7:  module Chat
8:    class Mattermost
9:
10:      def self.log_to_chat(message)
11:        cmd = Chef::Resource::Execute.new("echo #{message}")
12>>       cmd.run_action(:run)
13:

【问题讨论】:

    标签: chef-infra dsl


    【解决方案1】:
    notifies :run, Chat::Mattermost.log_to_chat("#{name}"), :immediately
    
    1. 您不能在非资源上调用 notify。
    2. 不能只调用notify来动态创建资源,是不行的。
    3. 作为notifies 的第二个参数(从资源块调用时),您应该传递将用于在厨师上下文中搜索资源的字符串。

    如果你想增强日志资源提供者,你应该实现自己的,类似于this,把它放在libraries中,并以你新实现的类名作为提供者调用log资源。

    log 'this is a message' do
      provider Chef::Provider::Log::MyCustomLog
    end
    

    【讨论】:

    • 好吧,我的方法不对……我可以完全避免使用notifies 和日志提供程序吗……只需在log "this is a message" 块之前调用Chat::Mattermost.log_to_chat('...') - 这可能吗?如何定义log_to_chat 方法?
    • 厨师分两个“阶段”工作,compile and runtime。在资源之间使用库函数将导致所有log_to_chat 函数调用,之后将执行所有厨师资源。因此,在您的“聊天”中,您可能会看到所有日志消息,无论资源状态如何。你的函数定义是有效的(只是不要使用里面的资源),像你提到的 Chat::Mattermost.log_to_chat("message") 那样从厨师代码中调用它。
    • 再次感谢。如果您看到我的“编辑:第二次尝试”,我尝试在没有资源的情况下执行 shell 命令,但它以 undefined method events' for nil:NilClass` 失败 - 知道为什么吗?我发现很少有直接使用Chef::Resource::Execute 的例子。
    • 要在纯 ruby​​ 代码中执行 shell,您应该使用标准 ruby​​ Open3 库中的 open2e/capture2e。使用资源可能需要构建厨师上下文。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-10
    • 1970-01-01
    • 2017-02-14
    • 2021-06-08
    • 2016-06-03
    • 1970-01-01
    相关资源
    最近更新 更多