Skip to content

Instantly share code, notes, and snippets.

@skippy
Forked from xdissent/middleware.rb
Created June 6, 2011 17:19
Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 5 You must be signed in to fork a gist
  • Save skippy/1010660 to your computer and use it in GitHub Desktop.
Save skippy/1010660 to your computer and use it in GitHub Desktop.
delete vagrant vm's chef client and node from chef server on destroy
class OnDestroyMiddleware
def initialize(app, env)
@app = app
end
def call(env)
env["config"].vm.provisioners.each do |provisioner|
env.ui.info "Attempting to remove client #{provisioner.config.node_name}"
`knife client show #{provisioner.config.node_name}`
if $?.to_i == 0
env.ui.info "Removing client #{provisioner.config.node_name}"
`knife client delete #{provisioner.config.node_name} -y`
end
env.ui.info "Attempting to remove node #{provisioner.config.node_name}"
`knife node show #{provisioner.config.node_name}`
if $?.to_i == 0
env.ui.info "Removing node #{provisioner.config.node_name}"
`knife node delete #{provisioner.config.node_name} -y`
end
end
@app.call(env)
end
end
Vagrant::Action[:destroy].use(OnDestroyMiddleware)
@skippy
Copy link
Author

skippy commented Jun 6, 2011

I put this in my Vagrantfile at the top, and it works like a charm! The one catch is that knife needs to be correctly setup; usually knife is setup to run in your chef-repo, but you'll probably be running vagrant destroy in a separate folder (like your rails app)... so just be aware and setup knife to read from ~/.chef/knife.rb

@patcon
Copy link

patcon commented Jul 5, 2011

This is great man. Thanks for tossing it out there!

@franklouwers
Copy link

Actually, Vagrant already provides a cleanup method in the provisioners base class that gets called on vm destroy. It just ins't filled in for most Provisioners. See http://frank.be/articles/2011/12/16/vagrant-and-chef-auto-deregister-on-vm-destroy/ for quick and dirty example

@patcon
Copy link

patcon commented Dec 16, 2011

WHOA. world rocked. Had totally forgotten this once i actually started using the chef_client provisioner

thanks guys

@skippy
Copy link
Author

skippy commented Dec 16, 2011

@franklouwers; perfect! thanks

@c10l
Copy link

c10l commented Dec 6, 2012

I adapted both cited works here and came to this: https://gist.github.com/4223941

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment