Kev*_*yer 4 ruby mongodb chef-infra
在Chef中,为什么这段代码没有捕获bash资源中抛出的异常?如果我运行此代码,即使抛出异常,我也永远不会访问python资源.错误是预期的,这就是为什么我抓住它,然后转向pymongo并以这种方式修复它.
begin
bash "mongo fix" do
code "mongo --verbose #{filename}"
action :run
end
rescue
python 'pymongo reconfig' do
code "Pymongo does a catch and reconfig"
end
end
Run Code Online (Sandbox Code Playgroud)
这是异常输出
[2013-03-05T20:03:55+00:00] FATAL: Mixlib::ShellOut::ShellCommandFailed: bash[mongo fix (noudata::mongo line 77) had an error: Mixlib::ShellOut::ShellCommandFailed: Expected process to exit with [0], but received '253'
---- Begin output of "bash" "/tmp/chef-script20130305-3916-14xxhn5-0" ----
STDOUT: MongoDB shell version: 2.2.3
Tue Mar 5 20:03:55 versionCmpTest passed
Tue Mar 5 20:03:55 versionArrayTest passed
connecting to: test
Tue Mar 5 20:03:55 creating new connection to:127.0.0.1:27017
Tue Mar 5 20:03:55 BackgroundJob starting: ConnectBG
Tue Mar 5 20:03:55 connected connection!
true
{
"errmsg" : "replSetReconfig command must be sent to the current replica set primary.",
"ok" : 0
}
Tue Mar 5 20:03:55 uncaught exception: [object bson_object]
failed to load: /tmp/test.js
STDERR:
---- End output of "bash" "/tmp/chef-script20130305-3916-14xxhn5-0" ----
Ran "bash" "/tmp/chef-script20130305-3916-14xxhn5-0" returned 253
Run Code Online (Sandbox Code Playgroud)
begin块中的代码构成Chef::Resource::Bash资源的实例,分配资源code和action属性,并将资源添加到run_context.resource_collection.资源在任何意义上都不是"运行"的.创建资源实例不会引发任何异常,因此rescue不会运行块中的代码.
稍后,一旦你的所有食谱代码都运行完毕,Chef将遍历所有的资源run_context.resource_collection.对于每个资源,Chef将运行资源的操作.对于bash资源,这意味着运行资源code属性中给出的字符串.请注意,这在配方和所有其他配方完成运行后很好地发生,因此这在begin块之外发生.运行其操作时由此资源引发的任何异常都不会传播到您的begin块,因为操作不是从begin块内调用,而是从块后调用.
你可以尝试这样的事情:
bash "mongo fix" do
code "mongo --verbose #{filename} || python pymongo reconfig"
end
Run Code Online (Sandbox Code Playgroud)