【问题标题】:Ruby / Chef: is there a way to refer to the resource 'name' and pass to a function?Ruby / Chef:有没有办法引用资源“名称”并传递给函数?
【发布时间】:2016-08-22 16:44:31
【问题描述】:

请参阅以下代码,使用 chef 中的 log 资源。

log 'Hello there' do
  level :info
  notifies :run, "log_to_chat('Hello there')"
end

当我将资源name 传递给函数log_to_chat 时,有没有办法引用资源name(在这种情况下:'Hello there')。

我想像这样:

log 'Hello there' do
  level :info
  notifies :run, "log_to_chat(#{name})"
end

添加我对 log_to_chat 的尝试。

尝试 1:

resource_name :log_to_chat

property :message, kind_of: String, name_property: true

chat_url = 'https://chat.server/abcdef'

action :run do
  execute do
    command "curl -m 5 -i -X POST -d \"payload={...}\" #{chat_url}"
    ignore_failure true
  end
end

问题:如何将:message 参数作为notifies 行中的一行传递?

notifies :run, "log_to_chat[message]", --pass :message how??--

尝试 2:

module Chat
  def log_to_chat(message)
    chat_url = 'https://chat.server/abcdef'
    action :run do
      execute "curl" do
        command "curl -m 5 -i -X POST -d \"payload={...}\" #{chat_url}"
        ignore_failure true
      end
    end
  end
end

编辑:尝试 2 无效,因为您不能在定义中使用资源

【问题讨论】:

    标签: ruby chef-infra cookbook recipe


    【解决方案1】:

    您可以参考name 变量。从documentation 你可以读到“name 是资源块的名称”。请记住,您要使用块的名称(在您的情况下为 Hello there)而不是资源名称(在问题的 sn-p 中为 log

    【讨论】:

    • 好的,谢谢,然后是:notifies :run, "log_to_chat(#{name})" ?
    • 这取决于你的代码库,但log_to_chat[#{name}] 更有可能。 docs.chef.io/resource_common.html#notifies
    • 有没有机会指导我如何编写log_to_chat 部分,这是模块中的方法,还是自定义资源,或者如何编写?它基本上是一个 curl 命令。
    • 你可以有一个红宝石块:docs.chef.io/resource_ruby_block.html.
    • 您可以使用declared_key 来获得更简洁的替代方案:notifies :run, declared_key github.com/chef/chef/blob/…
    【解决方案2】:

    如果您想通知资源 log_to_chat[some message](尝试 1),您必须在 log 'Hello there' 之前使用操作 :nothing 显式声明它。所以它应该是这样的:

    log_to_chat 'some message' do
      action :nothing
    end
    
    log 'Hello there' do
      level :info
      notifies :run, "log_to_chat[some message]"
    end
    

    只要是有效代码,它就不是最佳解决方案。要拥有 100% 的厨师方式解决方案,您应该实现新的 log resource 提供程序,默认情况下它是 Chef::Provider::ChefLog。您应该实施提到here 的“Old School LWRP”提供程序。在您的新提供者中,您可以替换标准的厨师日志资源功能,或者只是通过您的 curl 调用或本机 net/http(或任何其他网络 gem)ruby 调用来扩展它(首选)。

    【讨论】:

    • 好的,谢谢。我如何将#{name} 传递给log_to_chat[some message] 作为notifies... 行的参数或属性? (在这种情况下,“你好”)
    • 我不确定是否可能,我会在两个资源之前将其提取到变量中。
    猜你喜欢
    • 2016-10-17
    • 1970-01-01
    • 2019-05-09
    • 1970-01-01
    • 2022-01-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多