2015-04-28 230 views
1

我正在通過廚師創建一個用戶。他的屬性存儲在數據包:廚師有條件的資源參數

{ 
    "id": "developer", 
    "home": "/home/developer", 
    "shell": "/bin/zsh", 
    "password": "s3cr3t" 
} 

配方是:

developer = data_bag_item('users', 'developer') 

user developer['id'] do 
    action :create 

    supports :manage_home => true 
    home developer['home'] 
    comment developer['comment'] 
    shell developer['shell'] 
    password developer['password'] 
end 

的問題是,如果zsh上沒有安裝節點,我無法登錄爲developer。所以,我希望有條件申請論據user資源,如:

user developer['id'] do 
    action :create 

    supports :manage_home => true 
    home developer['home'] 
    comment developer['comment'] 
    if installed?(developer['shell']) 
    shell developer['shell'] 
    end 
    password developer['password'] 
end 

我怎樣才能做到這一點?

+0

是否安裝了帶有軟件包資源的zsh不是一個選項? – Tensibai

+0

@Tensibai,好吧,實際上我使用該食譜來安裝'zsh'。我只是不想依賴它。 – madhead

+0

在這種情況下,@mudasobwa答案是正確的(如果答案中包含了一個關於ruby代碼如何適用於未來讀者的小解釋,我已經投了贊成票) – Tensibai

回答

5

爲了補充@ mudasobwa的答案正確的方式做到這一點的廚師和避免丟失shell,如果它是由安裝另一個配方或包裝資源必須使用相同的配方lazy attribute evaluation

龍版thoose興趣在如何以及爲什麼:

這是廚師是如何工作的一個副作用,有一個第一次編譯的資源建立一個集合,在這個階段在配方中的任何Ruby代碼(在ruby_block資源之外)。一旦完成,資源收集就會收斂(所需狀態與實際狀態進行比較,並完成相關操作)。

下面的食譜會做:

package "zsh" do 
    action :install 
end 

user "myuser" do 
    action :create 
    shell lazy { File.exists? "/bin/zsh" ? "/bin/zsh" : "/bin/bash" } 
end 

這裏什麼hapens是Shell屬性值的評估延遲到收斂階段,我們必須使用IF-THEN-ELSE結構(這裏一個三元運算符,因爲我發現它更可讀)回退到我們肯定會出現的shell中(我使用/bin/bash,但故障安全值爲/bin/sh)或shell屬性爲零,這是不允許的。

通過此延遲評估,在安裝軟件包並顯示文件後,將對「/ bin/zsh」的存在性進行測試。如果軟件包中存在問題,用戶資源仍然會創建用戶,但使用「/ bin/bash」

1

達到你想要什麼,最簡單的方法是檢查外殼是否存在明確:

shell developer['shell'] if File.exist? developer['shell']