[英]Ruby / Chef: is there a way to refer to the resource 'name' and pass to a function?
请使用chef中的log
资源查看以下代码。
log 'Hello there' do
level :info
notifies :run, "log_to_chat('Hello there')"
end
当我将它传递给函数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
问题:如何从notifies
行传递:message
参数作为一个班轮?
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不起作用,因为您无法在定义中使用资源
您可以参考name
变量。 从文档中,您可以读到“ name
是资源块的名称”。 请记住,您要使用块的名称(在您的情况下是Hello there
)而不是资源名称(从问题的片段中log
)
如果你想通知资源log_to_chat[some message]
(尝试1)你必须用行动明确声明它:nothing
在log 'Hello there'
之前log 'Hello there'
。 所以看起来应该是这样的:
log_to_chat 'some message' do
action :nothing
end
log 'Hello there' do
level :info
notifies :run, "log_to_chat[some message]"
end
它是有效的代码,它不是最好的解决方案。 要拥有100%的厨师方式解决方案,您应该实现新的日志资源提供程序,默认情况下它是Chef::Provider::ChefLog
。 您应该实现此处提到的“Old School LWRP”提供程序。 在新的提供程序中,您可以替换标准的自定义日志资源功能,或者只需通过curl调用或本机net/http
(或任何其他网络gem)ruby调用(首选)进行扩展。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.