Guest User

Untitled

a guest
Apr 17th, 2018
105
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.35 KB | None | 0 0
  1. require 'chef'
  2. require 'mixlib/config'
  3.  
  4. class MyChef
  5. class Servers
  6. def initialize
  7. # use a path to a chef config file. I used /etc/client/chef.rb as a
  8. # starting point. Add user and password lines to this config file.
  9. # note that the user MUST have admin privileges - this means that the first
  10. # time you run this, if the user doesn't exist and have admin already, it will
  11. # FAIL. you must then go to the web UI, on the registrations tab, and make
  12. # this user an admin. Then you can delete all day long.
  13. ::Chef::Config.from_file(File.expand_path(File.join(File.dirname(__FILE__), '..', '..', 'config', 'chef.rb')))
  14. end
  15.  
  16. def delete(sid)
  17. # here I am using ipaddress as the key to search for a server to delete.
  18. # you can use anything you want, like node name, fqdn, or what have you.
  19. # in fact, if you pass fqdn into this method, you don't even need to do the
  20. # search for the node...
  21. results = search("ipaddress:#{sid}", "fqdn")
  22. if (results.empty?)
  23. raise "No results for search of IP address: #{sid}"
  24. elsif (results.size > 1)
  25. raise "More than one result for search of IP address: #{sid}"
  26. end
  27. node_name = results.first['fqdn'].gsub('.', '_')
  28. # delete the node
  29. rest.delete_rest("nodes/#{node_name}")
  30. # delete the registration
  31. rest.delete_rest("registrations/#{node_name}")
  32. end
  33.  
  34. def search(query, attributes="")
  35. return rest.get_rest("search/node?q=#{ERB::Util.url_encode(query)}&a=#{attributes}")
  36. end
  37.  
  38. def rest
  39. if (!@rest)
  40. ::Chef::Log.init(::Chef::Config[:log_location])
  41. ::Chef::Log.level(::Chef::Config[:log_level])
  42. @rest = ::Chef::REST.new(::Chef::Config[:registration_url])
  43. user = ::Chef::Config[:user]
  44. password = ::Chef::Config[:password]
  45. registration_attempted = false
  46. begin
  47. @rest.authenticate(user, password)
  48. rescue Net::HTTPServerException => e
  49. if (!registration_attempted)
  50. @rest.register(user, password, ::Chef::Config[:validation_token])
  51. registration_attempted = true
  52. retry
  53. else
  54. raise
  55. end
  56. end
  57. end
  58. return @rest
  59. end
  60.  
  61. end
  62. end
  63. end
Add Comment
Please, Sign In to add comment