If you use chef bookmark this page as you will need to access nested keys at some point.Chef uses ohai to build a hash of each host chef-client is installed on.In a recipe this is stored in a hash named node.If you want to access a value for a key its simple.
ip = node['ipaddress']
Also if you want to determine if a key exists before you try and access it you can use attribute?()
BTW in most cases you will want to make sure the key exists because if it doesn’t chef-client will throw an error.
For nested keys its a bit more difficult, first of all you should always make sure the keys exists. This involves using the has_key? method in nested if statements.Then you can just pull the value from the keys.Below is one way to do it in a recipe.In this example I am making sure the keys filesystem>/dev/sda6>mount exist in the node hash.Then once I’m sure the hash exists I pull out the value.
if node.has_key? "filesystem" if node["filesystem"].has_key? "/dev/sda6" if node["filesystem"]["/dev/sda6"].has_key? "mount" if node['filesystem']['/dev/sda6']['mount'] == '/srv' execute "foo" do command "touch /tmp/nested_keys_exist!" action :run end end end end end