“include_recipe” vs. Vagrantfile “chef.add_recipe”

2019-03-20 14:17发布

问题:

Just ran nginx::source recipe on my vagrant box, and I have very unusual behaviour.

When I include a recipe from the Vagrantfile (as below), everything works like a charm,

chef.add_recipe("project::nginx")
chef.add_recipe("nginx::source")

(project::nginx recipe is very simple. Using it to override default attributes of the nginx cookbook)

but if I include a recipe at the very end of project::nginx (mentioned up), everything falls apart:

node.default['nginx']['server_names_hash_bucket_size'] = 128
include_recipe "nginx::source"

Until now I didn't know there's any difference in behaviour between those two invocations. Does anybody here knows what's the difference?

回答1:

Gotya! Chef 11 feature. Issue with it exist in chef-solo solely :)

To make a quick resume, difference is:

  • chef.add_recipe() - loads entire cookbook context (all the files, e.g. recipes, definitions, attributes...)
  • include_recipe "" - files(attributes, definitions etc.) that are not in the expended run list are not loaded.

There are at least 4 ways to solve the issue(put files in the run list):

  • include_attribute - include desired attribute file explicitly.
  • metadata.rb->dependency - if your cookbook is using recipe from another cookbook, put that cookbook in metadata.rb's dependency section, and all it's files will be loaded.
  • chef.add_recipe() - Load recipe via Vagrantfile. (Mentioned here just for reference)
  • Berkshelf - you may use this cookbook manager to solve the issue as well. Here's the Stackoverflow thread about this exact problem and some Docs

For those who are interested in further reading, Chef 11 introduced dependency-based cookbook loading for non-recipe files. The new loading logic means that files belonging to cookbooks which exist in the cookbook_path but are not in the expanded run_list or dependencies of the cookbooks in the expanded run_list will no longer be loaded. REF: Opscode breaking changes documentation, and if you need a signature of the error I got, here's the exactly same one, even for the same cause.