简体   繁体   English

试图了解chef_vault和ruby的收藏

[英]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). 我是Ruby和Chef的新手,我很难理解如何从数据包(chef_vault)中获取嵌套元素。 I think this is more a fundamental Ruby question, but not sure if somewhat Chef specific. 我认为这是一个更基本的Ruby问题,但不确定是否有些厨师特定。

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. 最初,我尝试了test_vault['KEY1']['SUBKEY2'] ,这给了我一个错误。 My question is, why must I do test_vault['KEY1'][0]['SUBKEY2'] what am I indexing into with [0]? 我的问题是,为什么我必须做test_vault['KEY1'][0]['SUBKEY2']用[0]索引到什么?

KEY1 and KEY2 are both arrays containing a single hash. KEY1KEY2都是包含单个哈希的数组。 That's how you set up the JSON so that's how you have to use it. 这就是设置JSON的方式,因此必须使用它。 Not really a Ruby thing. 并不是真正的Ruby。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM