Cryptocracy

A blog

Chef LWRP - managed_directory

A common configuration management pattern is to generate snippets of configuration into a “.d” directory, which are subsequently compiled into a complete configuration – either by a script, or through support from the application itself.

This pattern works well when you’re maintaining a set of snippets, or adding to it, but removing snippets from the set can present a challenge. If you need to specifically remove a snippet from a node, you can always use the File resource with action :delete to do so. But what do you do if you don’t know which snippets need to be removed?

The managed_directory LWRP (Github Repo) inspects the node’s resource collection to identify the Chef-managed files in a given directory. It then compares this to the list of files actually present in the directory and removes the difference.

Walking the resource collection is pretty easy, although I had trouble finding examples when I sat down to try it. Hence this simple one:

Excerpt from managed_directory LPFull Source
1
2
3
  managed_files = run_context.resource_collection.all_resources.map { |r|
    r.name if r.name.start_with?("#{new_resource.path}/")
  }.compact

(Follow the “full source” link to see it in context.)

I haven’t uploaded this cookbook to the community site yet, as the list of assumptions and caveats is almost as long as this post. If there’s sufficient interest, I’ll fix a few of those and put it up.

Suggestions and pull requests are welcome.

Comments