Created
October 5, 2009 19:40
-
-
Save stormsilver/202373 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'chef' | |
require 'mixlib/config' | |
class MyChef | |
class Servers | |
def initialize | |
# use a path to a chef config file. I used /etc/client/chef.rb as a | |
# starting point. Add user and password lines to this config file. | |
# note that the user MUST have admin privileges - this means that the first | |
# time you run this, if the user doesn't exist and have admin already, it will | |
# FAIL. you must then go to the web UI, on the registrations tab, and make | |
# this user an admin. Then you can delete all day long. | |
::Chef::Config.from_file(File.expand_path(File.join(File.dirname(__FILE__), '..', '..', 'config', 'chef.rb'))) | |
end | |
def delete(sid) | |
# here I am using ipaddress as the key to search for a server to delete. | |
# you can use anything you want, like node name, fqdn, or what have you. | |
# in fact, if you pass fqdn into this method, you don't even need to do the | |
# search for the node... | |
results = search("ipaddress:#{sid}", "fqdn") | |
if (results.empty?) | |
raise "No results for search of IP address: #{sid}" | |
elsif (results.size > 1) | |
raise "More than one result for search of IP address: #{sid}" | |
end | |
node_name = results.first['fqdn'].gsub('.', '_') | |
# delete the node | |
rest.delete_rest("nodes/#{node_name}") | |
# delete the registration | |
rest.delete_rest("registrations/#{node_name}") | |
end | |
def search(query, attributes="") | |
return rest.get_rest("search/node?q=#{ERB::Util.url_encode(query)}&a=#{attributes}") | |
end | |
def rest | |
if (!@rest) | |
::Chef::Log.init(::Chef::Config[:log_location]) | |
::Chef::Log.level(::Chef::Config[:log_level]) | |
@rest = ::Chef::REST.new(::Chef::Config[:registration_url]) | |
user = ::Chef::Config[:user] | |
password = ::Chef::Config[:password] | |
registration_attempted = false | |
begin | |
@rest.authenticate(user, password) | |
rescue Net::HTTPServerException => e | |
if (!registration_attempted) | |
@rest.register(user, password, ::Chef::Config[:validation_token]) | |
registration_attempted = true | |
retry | |
else | |
raise | |
end | |
end | |
end | |
return @rest | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment