I'm new to Ruby and Chef I'm having trouble understanding how to get nested elements out of a databag (chef_vault). I think this is more a fundamental Ruby question, but not sure if somewhat Chef specific.
I created this vault:
$json = '{
"KEY1": [{
"SUBKEY1": "aaaaa",
"SUBKEY2": "bbbbbbb",
"SUBKEY3": "cccccccc"
}],
"KEY2": [{
"SUBKEY1": "dddddd",
"SUBKEY2": "eeeeee"
}],
"KEY3": "fffffff",
"KEY4": "ggggggg"
}'
knife vault create test_vault vaultitem1 $json --admins red888 --mode client --search 'role:testservers'
Here is what I noticed when trying to get nested elements out of it in my recipe:
test_vault = ChefVault::Item.load("test_vault", "vaultitem1")
puts test_vault.class
puts test_vault['SUBKEY1'].class
puts test_vault['SUBKEY1'].inspect
puts test_vault['SUBKEY1'][0]['SUBKEY2']
Now what I see in the console:
ChefVault::Item
Array
[{"SUBKEY1"=>"aaaaa", "SUBKEY2"=>"bbbbbbb", "SUBKEY3"=>"cccccccc"}]
{"SUBKEY1"=>"aaaaa", "SUBKEY2"=>"bbbbbbb", "SUBKEY3"=>"cccccccc"}
bbbbbbb
Originally I tried test_vault['KEY1']['SUBKEY2']
which gave me an error. My question is, why must I do test_vault['KEY1'][0]['SUBKEY2']
what am I indexing into with [0]?
KEY1
and KEY2
are both arrays containing a single hash. That's how you set up the JSON so that's how you have to use it. Not really a Ruby thing.