chef attribute : avoiding “undefined method `[]’ for nil:NilClass” error

In chef, when a nested attribute that might not exist/or not crated yet, you can use rescue as a modifier to an if statement.

For example, assuming that only some of your nodes have node[‘install_wls’][‘isManaged’]defined:

if node['install_wls']['isManaged']
do the stuff
end rescue NoMethodError

will avoid the chef run bailing with “undefined method `[]’ for nil:NilClass” error.

Though there are any legit method errors within your if block to handle empty/nil/blank attributes, you’ve just caught an exception you shouldn’t.

I use this in cookbooks that have extra functionality if some dependency of other component recipe happens to be installed. For example, the odi cookbook  depend on wls or odi depends on oracldb.

Advertisements

About Divyashree - The GNULINUX Guy

I am a Linux and Opensource enthusiast. I started working on Linux early in 2007 while I was doing my Masters in Computer Science and passed out in 2010. Currently working as a DevOps Developer in in Public/Private cloud domain. my @github : https://github.com/kumarprd my @nagiosexchange : https://exchange.nagios.org/directory/Owner/divyaimca/1 my @linkedin : https://www.linkedin.com/in/priyadarshee-kumar-☁-a9415615
This entry was posted in ARTICLES, Configurtion management, DevOps, HOWTO and tagged , , , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s