Skip to content

Instantly share code, notes, and snippets.

@adamhjk
Forked from rottenbytes/chef-resource.rb
Created March 11, 2011 19:42
Show Gist options
  • Save adamhjk/866448 to your computer and use it in GitHub Desktop.
Save adamhjk/866448 to your computer and use it in GitHub Desktop.
module MCollective
module Agent
# An agent that uses Opscode to manage resources
# Original credit goes to R.I. Pienaar
class ChefExistingResource < RPC::Agent
metadata :name => "SimpleRPC Existing Chef Resource Agent",
:description => "Generic resource management",
:author => "Nicolas Szalay <nico@rottenbytes.info>",
:license => "BSD",
:version => "1.0",
:url => "https://github.com/rottenbytes/mcollective",
:timeout => 60
# Does the actual work with the chef provider and sets appropriate reply options
action "handle" do
validate :resourcename, String
validate :resourceaction, String
require 'chef'
require 'chef/client'
require 'chef/run_context'
begin
Chef::Config[:solo] = true
Chef::Config[:log_level] = :debug
Chef::Log.level(:debug)
client = Chef::Client.new
client.run_ohai
client.build_node
last_run = JSON.parse(File.read(Dir["/var/chef/reports/chef-run-report-*.json"].sort.last))
run_context = Chef::RunContext.new(last_run.node, Chef::CookbookCollection.new(Chef::CookbookLoader.new))
last_run["all_resources"].each { |r| run_context.resource_collection << r }
resource = run_context.resource_collection.lookup(request[:resourcename])
resource.run_action(request[:resourceaction])
reply["status"] = resource.updated?
reply["status"] = status
rescue Exception => e
reply.fail "#{e}"
end
end
end
end
end
# In your client.rb
#
report_handlers << Chef::Handler::JsonFile.new
require 'mcollective'
include MCollective::RPC
mc = rpcclient("chefresource")
mc.progress = false
r = [ { "action" => "restart" }, { "supports" => {:status => true } } ]
mc.handle(:resourcename => "cron", :resourcetype => "service", :resourceactions => r).each do |resp|
puts resp[:sender] + " => " + resp[:status].inspect
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment