How to use current cookbook template dir to copy all templates recursively in a loop with chef

cheftemplates

I'm trying to figure out how can I construct the path to templates (or files, since it works the same way) folder, then I could read it and use template resource in the loop, so each template file could trigger notification on change.

I can't use remote_directory because I want to notify services only if template changes.

I also would like to avoid manual template specification, since there could be many files inside those dirs. Plus it would allow us to change just configs in the templates folder without touching recipe.

The main problem is those subdirectories like default, host, host-version and the logic chef goes through to determine correct templates folder. I was thinking maybe there is a method in one of the Chef classes I could call from my custom cookbook to get to the starting point for my logic (loop).

It should be something like this I think:

entry_point = CHEF::...getEntryPointDir

entry_point.glob..
.each do

    template fname do
    ...
    end

end

I would appreciate any help!

Best Answer

WARNING: This solution uses a private interface which may change or be removed without warning. Chef does not currently (13.x) provide a supported way of solving this problem - consider an alternative approach to solving your requirement.

Now that you've been warned, here's how you would do it in a recipe:

# Get the Chef::CookbookVersion for the current cookbook
cb = run_context.cookbook_collection[cookbook_name]

# Loop over the array of files.
# 'templates' will also work.
cb.manifest['files'].each do |cookbookfile|
  Chef::Log("found: " + cookbookfile['name'])
end

I've shared an example recipe to show this in context.

In practice, this needs to be more complicated - for example, you may only want a subset of the files/templates in the cookbook, or need to transform paths in some way. Consider writing a library function that makes a list of the files you are interested in, and calling that from your recipe.

Related Topic