Saturday, August 22, 2015

Getting Started with Vagrant

Vagrant is a virtualization technology that allows you to configure virtualization software such as Linux Containers and VirtualBox. It is commonly used together with orchestration tools like Ansible, and Chef.

To get started, download Vagrant here - https://www.vagrantup.com/downloads.html

Create a folder and run

vagrant init

This should create a VagrantFile.

Similar to Docker, Vagrant is dependent on base images. Let's begin by downloading an ubuntu box:

vagrant box add hashicorp/precise32

Open VagrantFile and edit the following:

config.vm.box = "hashicorp/precise32"

You can always find other boxes here:

https://atlas.hashicorp.com/boxes/search

Let's boot up the box:

vagrant up
vagrant ssh

You can check the status of the machine by running:

vagrant status

Do not delete the folder /vagrant, it's a synced folder

Let's begin by loading a script that will install apache.

In your hosts machine's root folder, create s file called bootstrap.sh

vi bootstrap.sh

Add the following:

apt-get update
apt-get install -y apache2
if ! [ -L /var/www ]; then
  rm -rf /var/www
  ln -fs /vagrant /var/www
fi

In VagrantFile, add

Vagrant.configure("2") do |config|
  config.vm.box = "hashicorp/precise32"
  config.vm.provision :shell, path: "bootstrap.sh"
end

Reload the provision:

vagrant reload --provision

Test the status of apache:

vagrant ssh
service apache2 status

Try running:

wget -qO- 127.0.0.1

Add the following line in VagrantFile for port forwarding, so we can see webpages from our host browsers

config.vm.network :forwarded_port, guest: 80, host: 4567

Run

vagrant reload

In your browser, do

http://127.0.0.1:4567

If you want to share this image to Altas to share/backup your files, register an account at

https://atlas.hashicorp.com/

Run

vagrant login
vagrant share

In the browser, access the url that's outputted by the terminal.

When you finished sharing, Ctrl = C to terminate it.

When you are done with your vagrant box, you can use the following:

vagrant suspend - state is saved, quick to start up, consumes space
vagrant halt - guest OS is shut down, consumes space
vagrant destroy - removes the guest machine

You can use vagrant up to start it again.

By default, the vagrant box is backed with Virtual Box.

But you can easily change it to VMware or AWS by:

vagrant up --provider-vmware_fusion
vagrant up --provider=aws