Skip to content

Instantly share code, notes, and snippets.

@rottenbytes
Created March 11, 2011 19:01
Show Gist options
  • Save rottenbytes/866379 to your computer and use it in GitHub Desktop.
Save rottenbytes/866379 to your computer and use it in GitHub Desktop.
Generic client
module MCollective
module Agent
# An agent that uses Opscode to manage resources
# Original credit goes to R.I. Pienaar
class Chefresource<RPC::Agent
metadata :name => "SimpleRPC 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 :resourcetype, String
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
run_context = Chef::RunContext.new(client.node, Chef::CookbookCollection.new(Chef::CookbookLoader.new))
recipe = Chef::Recipe.new("adhoc", "default", run_context)
# create the resource
resource = recipe.send(request[:resourcetype].to_sym, request[:resourcename])
# insert action, attribute, whatever supported by your resource type
request[:resourceactions].each { |action|
action.each_pair { |k,v|
resource.send(k,v)
}
}
status=Chef::Runner.new(run_context).converge
reply["status"] = status
rescue Exception => e
reply.fail "#{e}"
end
end
end
end
end
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