Skip to content

Instantly share code, notes, and snippets.

@X0nic
Last active August 29, 2015 13:59
Show Gist options
  • Save X0nic/10777783 to your computer and use it in GitHub Desktop.
Save X0nic/10777783 to your computer and use it in GitHub Desktop.
Clean up chef server on vagrant destroy
# Customize node name
vm_name = "vagrant-#{name}-#{ENV['USER']}"
config.vm.host_name = vm_name
# Borrowed from https://coderwall.com/p/sikrdw
module Vagrant
module Provisioners
class Base
require 'chef'
require 'chef/config'
require 'chef/knife'
end
class ChefClient
::Chef::Config.from_file(File.join(File.dirname(__FILE__), '.chef', 'knife.rb'))
def cleanup
node = env[:vm].config.vm.host_name
env[:ui].info "Attempting to clean up client '#{node}' on chef server."
begin
::Chef::REST.new(::Chef::Config[:chef_server_url]).delete_rest("clients/#{node}")
rescue Net::HTTPServerException => e
if e.message == '404 "Not Found"'
env[:ui].info "Client '#{node}' not found."
else
env[:ui].error "An error occured. You will have to remove the client manually."
end
rescue Exception => e
env[:ui].error "An error occured. You will have to remove the client manually."
else
env[:ui].info "Client '#{node}' successfully removed from chef server."
end
env[:ui].info "Attempting to clean up node '#{node}' on chef server."
begin
::Chef::REST.new(::Chef::Config[:chef_server_url]).delete_rest("nodes/#{node}")
rescue Net::HTTPServerException => e
if e.message == '404 "Not Found"'
env[:ui].info "Node '#{node}' not found."
else
env[:ui].error "An error occured. You will have to remove the node manually."
end
rescue Exception => e
env[:ui].error "An error occured. You will have to remove the node manually."
else
env[:ui].info "Node '#{node}' successfully removed from chef server."
end
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment