Search code examples
vagrantvagrantfile

Run code in Vagrantfile only if provisioning


I want to display some text on the screen when running vagrant up (or vagrant provision, etc.) if and only if provisioning is being done. (For vagrant up it is only run the first time, or if specifically forced with --provision.)

How can this be done?


Solution

  • Adding a shell provisioner is probably the easiest solution, with the small cost that it is executed on the VM over SSH.

    Another option is to use the vagrant-host-shell plugin:

    Vagrant.configure('2') do |config|
      # other config and provisioners
      # [...]
    
      config.vm.provision :host_shell, inline: 'echo "Provisioned!"'
    end
    

    If you like over-engineering, you can even make your own plugin in Vagrantfile. ;)

    class EchoPlugin < Vagrant.plugin('2')
      class EchoAction
        def initialize(app, env)
          @app = app
        end
    
        def call(env)
          @app.call(env)
          puts "Provisioned!"
        end
      end
    
      name 'echo'
    
      action_hook 'echo' do |hook|
        hook.before Vagrant::Action::Builtin::Provision, EchoAction
      end
    end
    
    Vagrant.configure('2') do |config|
      # ...
    end