emyl / vagrant-triggers

Allow the definition of arbitrary scripts that will run on the host before and/or after Vagrant commands.
MIT License
546 stars 35 forks source link

Run before destroy trigger only for specific provider #92

Closed joum closed 6 years ago

joum commented 6 years ago

I have a Vagrantfile which describes two different providers.

Is there any way to make the before destroy trigger run only for one of those providers?

For instance, at the moment, my Vagrantfile describes a virtualbox provider and an aws provider. I set up the destroy trigger to run some cleanup tasks, but I need them to run only on the aws provider, not the virtualbox one.

Is this even possible?

thecjharries commented 6 years ago

+1

Here's a quick example:

unless Vagrant.has_plugin?('vagrant-triggers')
  `vagrant plugin install vagrant-triggers`
end

Vagrant.configure('2') do |config|
  config.vm.box = 'centos/7'

  config.vm.provider 'virtualbox' do
    config.trigger.before :up do
      info "Running virtualbox trigger"
      raise "Whoops"
    end
  end
end
PS$ vagrant up -provider=hyperv
Bringing machine 'default' up with 'hyperv' provider...
==> default: Running triggers before up...
==> default: Running virtualbox trigger
Vagrantfile:14:in `block (3 levels) in <top (required)>': Whoops (RuntimeError)

Because Hyper-V does its own thing, it would be nice to have triggers specific to Hyper-V.

Unfortunately, you can't use something like this because the providers don't inherit trigger.

unless Vagrant.has_plugin?('vagrant-triggers')
  `vagrant plugin install vagrant-triggers`
end

Vagrant.configure('2') do |config|
  config.vm.box = 'centos/7'

  config.vm.provider 'hyperv' do |hyperv|
    hyperv.trigger.before :up do
      info "Running hypervtrigger"
    end
  end
end
PS$ vagrant up -provider=hyperv
Bringing machine 'default' up with 'hyperv' provider...
==> default: Verifying Hyper-V is enabled...
There are errors in the configuration of this machine. Please fix
the following errors and try again:

Hyper-V:
* The following settings shouldn't exist: trigger
agriffis commented 6 years ago

Provider blocks receive the provider as the first argument, config override as the second argument. See https://www.vagrantup.com/docs/providers/configuration.html#overriding-configuration

So this should work for you:

Vagrant.configure('2') do |config|
  config.vm.box = 'centos/7'

  config.vm.provider :hyperv do |hyperv, override|
    override.trigger.before :up do
      info "Running hypervtrigger"
    end
  end
end