if node['foo']['bar']['baz']
do the stuff I want
end rescue NoMethodError
will avoid the chef run bailing with the dreaded "undefined method `[]' for nil:NilClass" error. Of course, if there are any legit method errors within your if block, you've just caught an exception you shouldn't, but that's another story.
I use this in cookbooks that have extra functionality if some other cookbook happens to be installed. For example, the apache cookbook doesn't depend on ganglia, but if ganglia's installed, I want it to report metrics.
if node[:ganglia][:grid_name]
include_recipe "ganglia::default"
ganglia_python "apache" do
action :enable
end
end rescue NoMethodError
If the node doesn't have ganglia isntalled, it just goes on its merry way. #win
No comments:
Post a Comment