1

I would like to execute a custom ruby code after doing vagrant destroy.

That's the code:

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 

I'm trying this but isn't working:

Vagrant::Action[:destroy].use(OnDestroyMiddleware) 

All of this code is from https://gist.github.com/skippy/1010660

I've got this error on Vagrant::Action[:destroy]

Message: NoMethodError: undefined method `[]' for Vagrant::Action:Module

1 Answer 1

2

You can look at the vagrant trigger plugin. It allows you to run code after a specific vagrant command.

First you need to install the plugin

$ vagrant plugin install vagrant-triggers 

You'll add the code directly in your Vagrantfile, like

Vagrant.configure("2") do |config| # Your existing Vagrant configuration ... # run some script before the guest is destroyed config.trigger.after :destroy do info "Attempting to remove client..." run "knife client show .." end 
Sign up to request clarification or add additional context in comments.

5 Comments

I've got the following error: * Unknown configuration section 'trigger'.
did you install the plugin ?
I forgot it. The problem now is how to call the function: OnDestroyMiddleware.new.call?? What about the two parameters?
either you convert your code like it is shown, if you want to use your class, you need to call it action = OnDestroyMiddleware.new(config.vm) seems config.vm is only what you need
action = OnDestroyMiddleware.new(config.vm).call(config.vm) : undefined method `call' for nil:NilClass (NoMethodError)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.