Search code examples
scopevagrantprovisioning

How do I loop vagrant provisioning in multi-machine environments to switch back and forth between machines?


I have a multi-machine Vagrantfile setting up a 5 node environment.

I've been looking around to see what levels of control you have over the order of provisioning, but it's pretty limited:

https://docs.vagrantup.com/v2/multi-machine/

I want to provision 5 nodes, then go back to the first node, and run other provisioning steps there.

What I mean is that you have a Vagrantfile like this:

Vagrant.configure('2') do |config|
   config.vm.provision some stuff

   config.vm.define 'node1' do |node1|
      node1.vm.provision some more stuff
   end

   config.vm.define 'node2' do |node2|
      node2.vm.provision some other stuff
   end

   ... node3 node4 node 5 ...
end

But after vagrant has finished starting and provisioning the all the machines up to node5, I then want to run another provisioner on node1. Does anyone know how to do this? Maybe some ruby hackery?


Solution

  • One possible way of doing this is to execute commands between machines from ssh. The only additional thing you need to do is copy the vagrant insecure private key to each of the guests.

    Then you can ssh between the machines in your cluster (always handy) and also do stuff like this:

    Vagrant.configure('2') do |config|
    config.vm.provision some stuff
    
    config.vm.define 'node1' do |node1|
      node1.vm.provision some more stuff
    end
    
    config.vm.define 'node2' do |node2|
      node2.vm.provision "shell", inline: "/vagrant/bootstrap-webserver.sh"
      node2.vm.provision "shell", inline: "ssh vagrant@node1 sh /vagrant/trigger-build.sh"
    end
    
    config.vm.define 'node3' do |node3|
      node3.vm.provision "shell", inline: "/vagrant/create-database.sh"
      node3.vm.provision "shell", inline: "ssh vagrant@node1 sh /vagrant/initialise-database.sh"
    end
    
    ... node4 node 5 ...
    end
    

    You probably also want to set "PasswordAuthentication no" in your sshd_config on the guests and add "-o StrictHostKeyChecking=no" to the ssh command above to get it to work.