Search code examples
vagrantvagrantfilevagrant-provision

How do I provision a personal database during first vagrant up?


We've got a multi-machine Vagrantfile in our project repo which sets up a LAMP stack and creates some common MySQL databases. Now, each of us also have a personal database that we'd like Vagrant to create as part of the initial "vagrant up" provisioning. I've placed my personal provisioning code in ~/.vagrant.d/Vagrantfile, but according to the load order of Vagrantfiles, that code runs before the provisioning code of the common Vagrantfile. My personal provisioning code is unable to add any MySQL database because MySQL simply hasn't been installed yet, as that is the responsibility of the common Vagrantfile.

How can I have it so that the common Vagrantfile installs MySQL and the personal Vagrantfile adds a database once MySQL is in place?

Update Here is what I ended up doing.

Vagrantfile (shared with other developers):

Vagrant.configure("2") do |config|

  config.vm.define "dev14" do |dev14|

    dev14.vm.box = "ubuntu/trusty64"

    dev14.vm.provision "file", source: "common.sql", destination: "common.sql"

    dev14.vm.provision "shell", inline: <<-SHELL

      sudo apt-get update
      sudo apt-get install -y apache2
      sudo apt-get install -y php5
      sudo apt-get install -y mysql-server
      sudo apt-get install -y mysql-client

      mysql -uroot -proot -e "CREATE DATABASE IF NOT EXISTS common"
      mysql -uroot -proot common < common.sql

    SHELL

    # User specific provisioning
    $dev14 = dev14
    load './provision.dev14.rb' if File.exists?('./provision.dev14.rb')

  end

end

provision.dev14.rb (my personal provisioning file, Git ignored):

$dev14.vm.provision "file", source: "personal.sql", destination: "personal.sql"

$dev14.vm.provision "shell", inline: <<-SHELL

  mysql -uroot -proot -e "CREATE DATABASE IF NOT EXISTS personal"
  mysql -uroot -proot personal < personal.sql

SHELL

These are of course sanitised and simplified excerpts.


Solution

  • We found the easiest solution for this was to specify multiple provision scripts and have your 'create the database' Vagrant file script detect whether or not it needs to do anything.

    Also, can you parameterise the personalization stage e.g. base database creation on ENV['DB_USERNAME'] etc.? This would allow you to benefit from trying each other's setup.

    Beyond this, you can write a plugin to have finer control over which Vagrant action is running and hook in to pre/post action events.