Is it possible to use more than one config.vm.box in a Vagrantfile?

1.1k views Asked by At

I created a VM with some server settings and customizations and used vagrant to create a box. I imported the box into vagrant so I can spin up more than one server with the same configuration.

Also created a VM with client settings and boxed it with vagrant so I could create multiple clients.

I want to know whether it is possible to have in the same Vagrantfile a block of code for the server using the server_box and a block of code for the client using the client_box. I though I could use a config.vm.box for each but when I spin up the VMs, the clients pick up the client_box image, which is what I want, but the server also picks up the client_box image ignoring its own setting.

My attempt is below. NOTE: I know I can use a loop to create a series of clients. I just put the code as below for simplicity and clarity.

Vagrant.configure(VAGRANTFILE_API_VERSION) do |config|
  config.vm.box = "server_box"
  config.vm.define "server1", primary: true do |server1|
    [...vm specs here...]
  end
end


Vagrant.configure(VAGRANTFILE_API_VERSION) do |config|
  config.vm.box = "client_box"

  config.vm.define "client1", autostart: false do |client1|
    [...vm specs here...]
  end

  config.vm.define "client2", autostart: false do |client2|
    [...vm specs here...]
  end

end
1

There are 1 answers

0
kenorb On

Yes, you can specify multiple machines by using the config.vm.define method call, e.g.

Vagrant.configure("2") do |config|
  config.vm.provision "shell", inline: "echo Hello"

  config.vm.define "web" do |web|
    web.vm.box = "apache"
  end

  config.vm.define "db" do |db|
    db.vm.box = "mysql"
  end
end

See: Defining multiple machines at Vagranup Docs


You can also use a switch case syntax, so you can set box depending on some variable, e.g.

case provider
  when "virtualbox"
    config.vm.box = "ubuntu/wily64"
  when "aws"
    config.vm.box = "dummy"
end

Alternatively set the web.vm.box based on the environment variable, e.g.

config.vm.box = ENV['BOX']

and provide the value from the command line, like:

BOX=server_box vagrant up

See also: Multiple provisioners in a single vagrant file?