Reputation: 1
I am encountering an issue in my Chef recipe, it suddenly stop working and giving me the error that **undefined method '[]' for nil:NilClass**
This error is occurring in the following section of my Chef recipe:
deploy_user_data_bag = data_bag_item('linux_users', node['machinename'])
deploy_username = deploy_user_data_bag['deploy_user']['username'] if deploy_user_data_bag && deploy_user_data_bag['deploy_user']
mysql_data_bag = data_bag_item('mysql', node['machinename'])
mysql_users = mysql_data_bag['users'] if mysql_data_bag && mysql_data_bag['users']
postgres_data_bag = data_bag_item('postgres', node['machinename'])
postgres_users = postgres_data_bag['users'] if postgres_data_bag && postgres_data_bag['users']
postgres_databases = postgres_data_bag['databases'] if postgres_data_bag && postgres_data_bag['databases']
I suspect the issue is related to the data bag items or keys not being present as expected. I have tried to handle nil values with conditional checks, but the error persists.
**Additional Information:**
------------
chef_version=14.14.29
platform=centos
platform_version=7.9.2009
ruby=ruby 2.5.7p206 (2019-10-01 revision 67816) [x86_64-linux]
program_name=/bin/chef-client
executable=/opt/chef/bin/chef-client`
Any insights into what might be causing this error or suggestions for improvement in my code would be greatly appreciated. Additionally, if there's a better approach to handling data bags in Chef recipes, I'm open to suggestions.
Thank you in advance for your help!
Upvotes: 0
Views: 311
Reputation: 23
With the ruby dig
function, you can safely query hashes even if some intermediary levels don't exist, without getting an error. Your result will just be nil
in that case, e.g.
deploy_user_data_bag = data_bag_item('linux_users', node['machinename'])
deploy_username = deploy_user_data_bag.dig('deploy_user', 'username')
mysql_data_bag = data_bag_item('mysql', node['machinename'])
mysql_users = mysql_data_bag.dig('users')
postgres_data_bag = data_bag_item('postgres', node['machinename'])
postgres_users = postgres_data_bag.dig('users')
postgres_databases = postgres_data_bag.dig('databases')
and then
if deploy_username
...
end
if mysql_users
...
end
if postgres_users
...
end
if postgres_databases
...
end
Upvotes: 1