2013-07-29

Using attributes that might not exist in Chef

In chef, when testing a nested attribute that might not exist, you can use rescue as a modifier to an if statement. For example, assuming that only some of your nodes have node['foo']['bar']['baz'] defined:
 

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