[英]Iterating over a Chef array and using key in Ohai lookup
我正在遍歷一個數組,並想使用鍵作為查找Ohai值的邏輯的一部分。 在我的具體情況,我試圖source
,如果從以前的資源觸發每個用戶定義的.bashrc中。
Ohai結構:
"etc": { "passwd": { "root": { "dir": "/root", "gid": 0, "uid": 0, "shell": "/bin/bash", "gecos": "root" }, ... "foo": { "dir": "/home/foo", "gid": 501, "uid": 501, "shell": "/bin/bash", "gecos": "" }, ...
因此,當我循環瀏覽時,我正在嘗試執行以下操作:
node['my_cookbook']['managed_users'].each do |usr| bash 'reload_shell' do code "source #{node['etc']['passwd'][usr]['dir']}/.bashrc" action :nothing end end
我也嘗試過使用['usr']
, [#{usr}]
和["usr"]
表示法以及轉義引號。
要遍歷ruby中的哈希並訪問密鑰,可以執行以下操作:
node['my_cookbook']['managed_users'].each do |usr,props|
bash 'reload_shell' do
code "source #{node['etc']['passwd'][usr]['dir']}/.bashrc"
action :nothing
end
end
如果您不關心鍵或其下的值,請用_
替換相應的變量,即您的情況:
node['my_cookbook']['managed_users'].each do |usr,_|
bash 'reload_shell' do
code "source #{node['etc']['passwd'][usr]['dir']}/.bashrc"
action :nothing
end
end
如果不這樣做,您將獲得完整的基礎哈希,因此您的usr
var為
{
"root": {
"dir": "/root",
"gid": 0,
"uid": 0,
"shell": "/bin/bash",
"gecos": "root"
}
而不只是“根”。
旁注:為當前Shell進行采購工作,在bash資源內生成該Shell,執行命令並關閉該Shell。 采購文件不會有任何效果(除非.bash_rc內部有一個復雜的進程在做什么,這不會影響系統或廚師運行)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.