Using Chef, can I use include_recipe in an If statement and count on it working multiple times

chef

I would like to include a recipe based on a conditional branch in another recipe. This is currently planned to be during the execution of a Ruby .each iterator.

The opscode wiki says the following about include_recipe, "…subsequent calls to include_recipe for the same recipe will have no effect."

I am assuming that this means one may not use include_recipe for the same recipe multiple times during a run. However, does this apply if it's being called during execution of an iterator?

Thanks!

UPDATE for Clarification:

So, just to clarify. recipe_1 is the main recipe. In recipe_1, I iterate through apps on the node and I want to include recipe_2 if Application_2 is on the node or recipe_3 if App_3 is on the node. If I have both Apps on the node, I want to make sure that the first iteration that includes recipe_2 is not still included in recipe_1 when the next iteration starts to run for App_3. Again, I'm wary of the documentation that states: The included recipe's resources will be inserted in order, at the point where include_recipe was called.

Best Answer

Your suspicion is correct. include_recipe is cumulative within a RunContext (chef-client run). Pasted below is RunContext#load_recipe which is called by IncludeRecipe#load_recipe.

# Evaluates the recipe +recipe_name+. Used by DSL::IncludeRecipe
def load_recipe(recipe_name)
  Chef::Log.debug("Loading Recipe #{recipe_name} via include_recipe")

  cookbook_name, recipe_short_name = Chef::Recipe.parse_recipe_name(recipe_name)
  if loaded_fully_qualified_recipe?(cookbook_name, recipe_short_name)
    Chef::Log.debug("I am not loading #{recipe_name}, because I have already seen it.")
    false
  else
    loaded_recipe(cookbook_name, recipe_short_name)

    cookbook = cookbook_collection[cookbook_name]
    cookbook.load_recipe(recipe_short_name, self)
  end
end
Related Topic