What is the correct way to check for the existence of a nested attribute in Chef?

borntyping picture borntyping · Sep 24, 2013 · Viewed 28.5k times · Source

There are multiple ways to check for the existence of a nested attribute in chef, and I'm not sure which is correct/best, and if any will result in empty attributes being stored on the node:

node[:parent] and node[:parent][:child]

node.attribute?(:parent) and node[:parent].attribute?(:child))

node[:parent].nil? and node[:parent][:child].nil?

It'd be greatly preferred to be able to check for the parent and child at the same time, but I don't know if that's possible. I am using Chef 10, not Chef 11, though answers explaining either are welcome.

Answer

shawnzhu picture shawnzhu · Sep 25, 2013

Node attribute object is HashMap. You can use ruby native API to lookup nested attributes.

Chef Node Object provides a number of helper methods like:

node.attribute?()
node[:foo].attribute?(:bar)
node[:foo].member?(:bar)

There is also a new method node.debug_value() in chef 11 to help you debug node attributes which is also helpful:

node.debug_value(:foo, :bar)

Details can be found from the article Chef 11 In-Depth: Attributes Changes