2017-02-03 43 views
1

我有幾本食譜,其中包括其他幾本食譜,這取決於每本食譜的需求。 附帶的食譜宣佈通知其他服務的服務。建議在包含的配方中使用return語句嗎?

其中一本食譜common_actions包含在所有其他食譜中,因爲它包含所有人共同的操作。

include_recipe 'cookbook1' 
include_recipe 'common_actions' 
include_recipe 'cookbook2' 
# Several cookbooks have such includes, but 'common_actions' 
# is included in almost all the cookbooks. 

# cookbook specific conditional logic that should be 
# executed only if some condition in 'common_actions' is true 

是不是一個明智的主意,包括在common_actions菜譜條件return語句,這樣就會迫使不對其進行編譯執行的基礎/根據這一條件的,包括食譜?對於這個問題的目的,請考慮像假的條件:

if node['IP'] == 'xyz' 
    # All including cookbooks should execute only IP is xyz 
    return 
end 

能與這樣一個return語句原因只有特定的食譜菜譜運行?這是可取的嗎?

注意:我這樣做是因爲我不想在所有其他食譜中複製粘貼相同的代碼。

回答

1

如果我理解你正確,這不會做你以後因爲:

  1. 配方將只包含一次,如果在運行列表有數倍的食譜呼籲include_recipe A::B然後食譜配方乙A只會編譯一次,連續調用將不會執行(不會重複配方資源)。
  2. return聲明將結束實際的配方編譯,在您的情況下,它將停止編寫食譜common_actions中的配方default

你可以做的是使用node.run_state,它是一個只在運行期間可用的散列。
例如,您可以使用它來存儲來自command_actions cookbookn的另一個條件散列。

node.run_state['IP_allowed'] = node['IP'] == 'xyz' 
# Probabaly a little silly, but that's the easier I can think of 
if node.chef_environment == 'Test' 
    if node['DoDebugLog'] == true 
    node.run_state['LoggerLevel'] = 'debug' 
    else 
    node.run_state['LoggerLevel'] = 'info' 
else 
    node.run_state['LoggerLevel'] = 'warn' 
end 

現在,您可以在其他食譜中使用這些值來控制其行爲,同時仍將條件定義保留在中心位置。

在配方應該運行,如果node['IP']'xyz'你會開始使用配方:

return if node.run_state['IP_allowed'] 

並在一個應該運行只有如果node['IP']'xyz'你會開始配方:

return unless node.run_state['IP_allowed'] 

其他值可用於在不同環境中記錄食譜e:

log "Message to log" do 
    level node.run_state['LoggerLevel'] 
end 
-1

您可以像這樣放置頂級返回,或者您可以在include_recipe本身上使用條件。