我正在使用厨师独奏来测试我的食谱。我正在尝试使用库来触发电子邮件。这就是我所做的。
在我的cookbook目录中创建了一个库目录
cat /tmp/chefrepo/cookbooks/poc/libraries/helper.rb
require 'net/smtp'
module HandlerSendEmail
class Helper
def send_email_on_run_failure(node_name)
message = "From: Chef <chef@chef.io>\n"
message << "To: Grant <grantmc@chef.io>\n"
message << "Subject: Chef run failed\n"
message << "Date: #{Time.now.rfc2822}\n\n"
message << "Chef run failed on #{node_name}\n"
Net::SMTP.start('localhost', 25) do |smtp|
smtp.send_message message, 'chef@chef.io', 'grantmc@chef.io'
end
end
end
end
一个简单的食谱
cat /tmp/chefrepo/cookbooks/poc/recipes/default.rb
#
# Cookbook:: poc
# Recipe:: default
#
# Copyright:: 2017, The Authors, All Rights Reserved.
ruby_block 'fail the run' do
block do
fail 'deliberately fail the run'
end
end
Chef.event_handler do
on :run_failed do
HandlerSendEmail::Helper.new.send_email_on_run_failure(
Chef.run_context.node.name
)
end
end
当我使用chef-solo -c solo.rb -j node.json
运行厨师独奏时
我得到了
Running handlers:
[2017-09-29T12:49:09+00:00] ERROR: Running exception handlers
[2017-09-29T12:49:09+00:00] ERROR: Running exception handlers
Running handlers complete
[2017-09-29T12:49:09+00:00] ERROR: Exception handlers complete
[2017-09-29T12:49:09+00:00] ERROR: Exception handlers complete
Chef Client failed. 0 resources updated in 03 seconds
[2017-09-29T12:49:09+00:00] ERROR: uninitialized constant #<Class:#<Chef::Recipe:0x0000000004875ee8>>::HandlerSendEmail
[2017-09-29T12:49:09+00:00] ERROR: uninitialized constant #<Class:#<Chef::Recipe:0x0000000004875ee8>>::HandlerSendEmail
[2017-09-29T12:49:09+00:00] FATAL: Chef::Exceptions::ChildConvergeError: Chef run process exited unsuccessfully (exit code 1)
[2017-09-29T12:49:09+00:00] FATAL: Chef::Exceptions::ChildConvergeError: Chef run process exited unsuccessfully (exit code 1)
我缺少什么?我尝试将库目录位置更改为与cookbooks目录相同的级别,但它不起作用。
答案 0 :(得分:0)
您错过了混合助手资源的命令。在库文件的底部添加以下
Chef::Recipe.include(HelperSendEmail)
Chef::Resource.include(HelperSendEmail)
这将使您的资源可用。
来源:https://www.sidorenko.io/post/2016/10/writing-helper-cookbooks-with-shared-functions/