Monday, March 28, 2016

Vagrant : An amazing tool to manage VMs

Vagrant is an amazing tool for managing VMs. Why it is so amazing is because of the convenience it adds in the aspect of managing VMs. It can work with VirtualBox which makes it possible to get the advantage of vagrant for free.
If you have installed Vagrant and VirtualBox starting a vagrant and spawning up a virtual machine is super simple. You just need to enter 2 commands below.

vagrant init hashicorp/precise64
vagrant up

First command creates a configuration file in your current directory with the name "Vagrantfile" and this file can be used to configure the VMs as required. The second command will create and start the VM with the name "default". With these two commands, you will have your VM up and running in VirtualBox.

But most of the time we may need to start several VMs and manage them. The Vagrantfile can be used to support that. Given below is a sample Vagrantfile (without comments) that was used to spawn up 3 VMs: vm1, vm2 and vm3 with the specified IPs. The memory of each VM, number of cpus, etc can be configured in the Vagrantfile as required.

Vagrant.configure(2) do |config|
  config.vm.box = "hashicorp/precise64"
  config.vm.provider "virtualbox" do |vb|
  vb.memory = "3072"
  vb.cpus = 2
end

config.hostmanager.enabled = true
config.hostmanager.manage_host = false
config.hostmanager.ignore_private_ip = false
config.hostmanager.include_offline = true

  config.vm.define "vm1" do |vm1|
    vm1.vm.hostname = 'vm1-hostname'
    vm1.vm.network "private_network", ip: "172.28.128.5"
  end

  config.vm.define "vm2" do |vm2|
    vm2.vm.hostname = 'vm2-hostname'
    vm2.vm.network "private_network", ip: "172.28.128.6"
  end

  config.vm.define "vm3" do |vm3|
    vm3.vm.hostname = 'vm3-hostname'
    vm3.vm.network "private_network", ip: "172.28.128.7"
  end
end


Below are some useful commands that are be required to manage these VMs.
  • vagrant up vm1 (create vm1 if not created and start the vm1)
  • vagrant ssh vm1 (ssh into vm1)
  • vagrant halt vm1 (gracefully shutdown vm1)
  • vagrant destroy vm1 (destroy vm1)
  • vagrant status (shows status of the VMs created in current directory)
  • vagrant global-status (shows status of all the VMs in your host)

And one another useful feature is the easiness of copying the files to your VM. You can simply copy whatever the files you need to the same directory where the Vagrantfile is and those files will be available in /vagrant directory in your VM.
Give it a try when you need to work with VMs.