Skip to content

Instantly share code, notes, and snippets.

@timdiggins
Created March 13, 2011 07:54
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save timdiggins/867960 to your computer and use it in GitHub Desktop.
Save timdiggins/867960 to your computer and use it in GitHub Desktop.
Monkeypatch for chef solo to do basic data_bag manipulations
# save this in the library folder of a cookbook
# (e.g. ./coookbooks/vagrant/library/chef_solo_patch.rb)
# see also https://gist.github.com/867958 for vagrant patch
# based on http://lists.opscode.com/sympa/arc/chef/2011-02/msg00000.html
if Chef::Config[:solo]
class Chef
module Mixin
module Language
def data_bag(bag)
@solo_data_bags = {} if @solo_data_bags.nil?
unless @solo_data_bags[bag]
@solo_data_bags[bag] = {}
data_bag_path = Chef::Config[:data_bag_path]
Dir.glob(File.join(data_bag_path, bag, "*.json")).each do |f|
item = JSON.parse(IO.read(f))
@solo_data_bags[bag][item['id']] = item
end
end
@solo_data_bags[bag].keys
end
def data_bag_item(bag, item)
data_bag(bag) unless ( !@solo_data_bags.nil? && @solo_data_bags[bag])
@solo_data_bags[bag][item]
end
end
end
end
class Chef
class Recipe
def search(bag_name, query=nil)
Chef::Log.warn("Simplistic search patch, ignoring query of %s" % [query]) unless query.nil?
data_bag(bag_name.to_s).each do |bag_item_id|
bag_item = data_bag_item(bag_name.to_s, bag_item_id)
yield bag_item
end
end
end
end
end
@timdiggins
Copy link
Author

I don't know exactly how it works, but know from experience that library files are evaluated on any node which is using a recipe from their cookbook (so probably required by chef during recipe discovery/loading).

Because the recipe files are evaluated in Chef::Recipe context (like an extend/include I suppose) which itself includes various mixins, you can see how the monkey patching above overrides the existing methods.

Might be worth asking the question on the chef-list.

@hedgehog
Copy link

hedgehog commented Jul 1, 2011

Hmm, it looks like data_bags_path is now in Vagrant

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment