red888 red888 - 1 year ago 56
JSON Question

Trying to understand chef_vault and ruby collections

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:

[{"SUBKEY1"=>"aaaaa", "SUBKEY2"=>"bbbbbbb", "SUBKEY3"=>"cccccccc"}]
{"SUBKEY1"=>"aaaaa", "SUBKEY2"=>"bbbbbbb", "SUBKEY3"=>"cccccccc"}

Originally I tried
which gave me an error. My question is, why must I do
what am I indexing into with [0]?

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download