I’m using the find command to collect the information I need from the Puppet Database as below.
vm_name = puppetdb.find {|details| details[‘certname’]==(hostname) and details[‘name’]==‘az_metadata’}[‘value’][‘compute’][‘name’]
Some of the parameters don’t have ‘az_metadata’ parameters, and that causes the find function to show “undefined method `[]’ for nil: nil class (no method error).” How can I handle those undefined method values from the find result for that specific variable?
Thanks for your kind explanation. I’ve added as your suggestion as below and and got undefined method `&’ for {“certname”=>“vm01”, “environment”=>“production”, “name”=>“az_metadata”, etc.
vm_name = puppetdb.find {|details| details[‘certname’]==(hostname) and details[‘name’]==‘az_metadata’}&[‘value’]&[‘compute’&][‘name’]
Is it possible to first fetch the value, and then only look at its details if it’s not nil?
vm_record = puppetdb.find {|details| details[‘certname’]==(hostname) and details[‘name’]==‘az_metadata’}
unless vm_record.nil?
vm_name = vm_record['value']['compute']['name']
end
If you really want a one-line solution, there are various approaches. One way to remove the ‘nil’ is to use “select” instead of “find” to get an array, and then map the lookup:
vm_name = puppetdb.select {|details| details[‘certname’]==(hostname) and details[‘name’]==‘az_metadata’}.map{|it| it[‘value’][‘compute’][‘name’]}.first
Use Select
agent_review.rb:31:in block (2 levels) in <main>': undefined local variable or method ‘value’’ for main:Object (NameError)
from aagent_review.rb:31:in map' from agent_review.rb:31:in block in ’
from agent_review.rb:22:in each' from agent_review.rb:22:in ’