2017-05-29 15 views
0

我目前有一個包含一些祕密配置的數據包。每當一個新的配置而成,它會被添加到databag如下所示:循環播放EncryptedDataBagItems從一個特定索引開始,或者在廚師中沒有特定的對象

{ 
    "id": "config-databag", 
    "config1": { 
     "name": "config1", 
     "secret": "supersecretpassword" 
    }, 
    "config2": { 
     "name": "config2", 
     "secret": "supersecretpassword" 
    } 
} 

在我的食譜,我檢索databag,有一個模板,將使用部分模板渲染的所有配置到一個文件:

secret_key = Chef::EncryptedDataBagItem.load_secret('/path/to/data_bag_key'); 
configurations = Chef::EncryptedDataBagItem.load('my-databag', 'config-databag', secret_key).to_hash 

template 'file' do 
    source 'file.erb' 
    owner 'root' 
    group 'root' 
    mode '644' 
    variables(
     'configurations' => configurations 
    ) 
    notifies :restart, 'service[foo]' 
end 

file.erb

<% @configurations.each do |config| %> 
<%= render 'append-config.erb', :variables => { :name => config[name], :secret => config[secret] } %> 
<% end %> 

追加-config.erb

special config <%= @name %> : <%= @secret %> 

有沒有辦法讓我可以遍歷數據包中除「id」對象外的所有數據項?我目前在Ubuntu 14.04上使用Chef版本11.8.2。

回答

1

您可以使用each_pair迭代器,可以使用next跳過id,也可以在傳遞給變量(delete_if方法)之前將其刪除。

hash = { 
    "id" => "config-databag", 
    "config1" => { 
     "name" => "config1", 
     "secret" => "supersecretpassword" 
    }, 
    "config2" => { 
     "name" => "config2", 
     "secret" => "supersecretpassword" 
    } 
} 

現在它可以走兩條路。

hash.each_pair do |key, value| 
    next if key == "id" 
    puts key 
    puts value["name"] 
    puts value["secret"] 
end 

hash.delete_if { |key, _| key == "id" } 
hash.each_pair do |key, value| 
    puts key 
    puts value["name"] 
    puts value["secret"] 
end 
+0

這是好得多比有一個if語句檢查是否值是一個字符串我。非常感謝。 – leeeennyy

相關問題