2017-02-03 40 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本身上使用条件。