Skip to content
Tutorials Center
My learning

Topics

Lesson 29 of 36 ยท Team Workflows

Triggers and Automation

Use config.trigger to run scripts before or after vagrant up, halt and destroy, back up data, check prerequisites and automate common team tasks with Ruby.

Provisioners run inside the guest when a machine is created. But some jobs belong around Vagrant commands: back up a database before vagrant destroy, check that a port is free before vagrant up, or print the URL when the machine is ready. Vagrant triggers hook into the command life cycle and run actions on the host or in the guest.

Trigger basics

A trigger is declared with config.trigger.before or config.trigger.after, naming the commands it applies to.

Ruby
Vagrant.configure("2") do |config|
  config.vm.box = "ubuntu/jammy64"

  config.trigger.after :up do |trigger|
    trigger.name = "Welcome message"
    trigger.info = "Machine is ready at http://localhost:8080"
  end

  config.trigger.before :destroy do |trigger|
    trigger.name = "Warn before destroy"
    trigger.warn = "All data inside the machine will be deleted."
  end
end
  • The symbol is the command: :up, :halt, :destroy, :reload, :provision, :suspend, :resume (and others). Pass several: config.trigger.before [:halt, :destroy].
  • trigger.name labels the trigger in output.
  • trigger.info and trigger.warn print messages.
TEXT
==> default: Running action triggers before destroy ...
==> default: Running trigger: Warn before destroy...
==> default: All data inside the machine will be deleted.

Running commands on the host

trigger.run executes a command on your computer. Use it for checks and for calling other tools.

Ruby
config.trigger.before :up do |trigger|
  trigger.name = "Check that port 8080 is free"
  trigger.run = { inline: "bash -c '! lsof -i :8080'" }
  trigger.on_error = :halt           # stop vagrant up if the check fails
end
  • run = { inline: "..." } runs a shell string; run = { path: "scripts/check.sh" } runs a file.
  • on_error = :halt (default) stops the command if the trigger fails; :continue ignores the failure.
  • exit_codes = [0, 2] lists codes that count as success.

Running commands in the guest

trigger.run_remote executes inside the machine over SSH. It is the natural way to back up data before the machine is deleted.

Ruby
config.trigger.before :destroy do |trigger|
  trigger.name = "Dump the database"
  trigger.run_remote = { inline: "mysqldump -uroot app > /vagrant/backup.sql" }
  trigger.on_error = :continue        # machine may already be stopped
end

Because /vagrant is a synced folder, the dump lands in your project folder on the host and survives the destroy. Add backup.sql to .gitignore.

Limiting triggers to a machine or provider

Without limits, a trigger runs for every machine. Narrow it with only_on or by defining it inside a machine block.

Ruby
config.trigger.after :up do |trigger|
  trigger.only_on = "web"            # name or regex
  trigger.info = "Open http://localhost:8080"
end

config.vm.define "db" do |db|
  db.trigger.before :halt do |t|
    t.run_remote = { inline: "sudo systemctl stop mysql" }
  end
end

only_on takes a machine name, a regular expression, or an array of them.

Using Ruby directly

Everything outside the Vagrant.configure block (and inside it) is Ruby, so you can also do small tasks without triggers, such as creating a folder or reading Git state, at load time.

Ruby
require "fileutils"
FileUtils.mkdir_p(File.join(__dir__, "tmp"))

branch = `git rev-parse --abbrev-ref HEAD`.strip rescue "unknown"
config.vm.hostname = "dev-#{branch.gsub(/[^a-z0-9]/i, '-')}"

Use this sparingly. The Vagrantfile is evaluated on every command, including vagrant status, so keep load-time code fast and free of side effects. Side effects belong in triggers, which run only around the commands you choose.

Triggers versus provisioners

Provisioners Triggers
Run when Machine is created (or vagrant provision) Around any named command
Where Inside the guest (usually) Host or guest
Typical use Install and configure software Backups, checks, notifications, cleanup
Repeat on each up Only first time (unless run: "always") Every time the command runs

For "run on every boot", you can also use config.vm.provision "shell", run: "always", but a trigger is clearer when the job concerns the host.

A stand-in: a trigger runner

The mechanism is a list of hooks keyed by command and phase. This Ruby program models it, so you can see the order in which before-triggers, the command and after-triggers run, and how on_error changes the flow. It is a model, not the real Vagrant implementation.

Ruby Before and after hooks

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Notice the difference: the failing up check stops everything, while the failing backup is tolerated because it uses :continue.

Common mistakes

  • A trigger that fails for a normal reason, such as a dump on a machine that is already off. Use on_error = :continue or check first.
  • Heavy work at Vagrantfile load time, which slows every command.
  • Forgetting only_on in multi-machine files, so the trigger fires once per machine.
  • Putting secrets in trigger.run strings, where they appear in output.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which trigger setting runs a command inside the guest over SSH?

    run executes on the host; run_remote executes in the guest.
  2. 2. What does on_error = :continue do?

    :halt (the default) stops the command on failure; :continue ignores the failure.
  3. 3. Why put side effects in triggers and not at the top of the Vagrantfile?

    Load-time code runs even for vagrant status; triggers run only around chosen commands.
  4. 4. How do you run a trigger only for the machine named web?

    only_on accepts a name, a regular expression, or an array.

Summary

  • config.trigger.before/after hook around commands such as :up, :halt and :destroy.
  • run executes on the host, run_remote in the guest; on_error decides whether failures stop the command.
  • Limit triggers with only_on in multi-machine files.
  • Keep the Vagrantfile load fast and put side effects in triggers.

Next: Packaging and private boxes