What & why
Vagrant is an open-source tool that allows you to create, configure, and manage boxes of virtual machines through an easy to use command interface. It is a tool for building complete development environments with a focus on automation and easy workflow.
It is used in software development to ensure all team members are building with the same configuration. Not only does Vagrant make it possible to share environments, it also shares code as well. This allows the code from one developer to work on the system of another, making collaborative and cooperative development possible. With Vagrant, you can create virtual machines on-the-fly via a set of reusable configuration files. Developers can track environment configuration changes and share their environment so that others can spin up an identical environment.
Installation
- Download the latest version of Vagrant from:
https://www.vagrantup.com/downloads.html
- Download the latest version of VirtualBox:
https://www.virtualbox.org/wiki/Downloads
Install and restart your PC. Confirm they are properly set up:
Vagrant -v
Example
Run:
Vagrant init generic/alpine310
Vagrant up
Vagrant
Vagrant Boxes
The basic unit in a Vagrant setup is called a “box” or a “Vagrantbox.” This is a complete, self-contained image of an operating system environment. It is a clone of a base operating system image. Using a clone speeds up the launching and provisioning process.
Adding a VagrantBox:
You can add a box with the command:
vagrant box add ubuntu/trusty64
This downloads the box and stores it locally in your machine.
To see all your OS boxes, use:
Vagrant box list
To make use of a box, you need to configure the Vagrantfile and point it to the box. Make sure you’re at the desired folder. Initialize vagrant with:
Vagrant init trusty64
A “Vagrant” file will be created in the directory. Open It with the command:
sudo nano vagrantfile
Once the Vagrantfile is open, locate and change the “config.vm.box” string from what it is to “ubuntu/trusty64”:
config.vm.box = "ubuntu/trusty64"
To remove a VagrantBox:
vagrant box remove ubuntu/trusty64
VagrantFile Demystification
Vagrantfile is the file that Vagrant uses to specify the configuration of the VagrantBox. It’s a Ruby Script but doesn’t require the knowledge of Ruby to create or understand one. Note that VagrantFile has no extension.
The primary function of the Vagrantfile is to describe the type of machine required for a project, and how to configure and provision these machines. Vagrantfiles are called so because the actual literal filename for the file is Vagrantfile.
Here is a sample vagrant file (you can generate one by executing “Vagrant Init ”):
Vagrant.configure("2") do |config|
config.vm.box = "trusty64"
config.vm.box_check_update = false
# **NETWORK SETTING**
config.vm.network "forwarded_port", guest: 80, host: 8080
config.vm.network "forwarded_port", guest: 80, host: 8080, host_ip: "127.0.0.1"
config.vm.network "private_network", ip: "192.168.33.10"
config.vm.network "public_network"
# **SHARED FOLDER**
config.vm.synced_folder "../data", "/vagrant_data"
# **PROVIDER-SPECIFIC CONFIGURATION**
config.vm.provider "virtualbox" do |vb|
# # Display the VirtualBox GUI when booting the machine
vb.gui = true
# Customize the amount of memory on the VM:
vb.memory = "1024"
end
# **PROVISIONING**
config.vm.provision "shell", inline: <<-SHELL
apt-get update
apt-get install -y apache2
SHELL
end
- “#” is used to comment out a line. These can be uncommented to apply the implied setting.
- Versioning: Configuration versions are the mechanism by which Vagrant is able to remain backward compatible. It is specified by the **Vagrant.configure(“version_number”)**
- Box: A box can be used on any platform that Vagrant supports to bring up an identical working environment.
- Shared folder: Vagrant automatically synchronizes content that is in your project directory with a special directory in the guest (virtual) system
- Networking: Vagrant includes options to place your virtual machine on a network. This makes it more accessible. You can create a forwarded port for the guest system, define private networks, public networks, and other more advanced options.
- Provisioning: Provisioners in Vagrant allow you to automatically install software, alter configurations, and more on the machine as part of the vagrant up process. Some supported Provisioners includes Ansible and Shell script.
Vagrant Up
After making any modification to a VagrantFile, it is advised you save and commit it to a Version Control system. To apply the changes made, execute this command:
vagrant up
subsequently, to apply any other change while the provisioned VM is running, use the command:
vagrant reload
Vagrant SSH
After the vagrant up has successfully completed, you can connect to the created virtual machine by using an SSH connection, with:
vagrant ssh
This opens a secure shell connection to the new virtual machine. Your command prompt will change to “vagrant@trusty64” to indicate that you are logged into the virtual machine.
Once you are done exploring the virtual machine, you can exit the session with CTRL-D. The virtual machine will still be running in the background, but the SSH connection will be closed.
Vagrant on Azure
Demo
First visit www.portal.azure.com and provision a VM.
SSH into the VM
Install Vagrant on it with:
wget https://releases.hashicorp.com/vagrant/2.2.10/vagrant_2.2.10_x86_64.deb
sudo dpkg -i vagrant_2.2.10_x86_64.deb
Install the Vagrant-azure package with:
vagrant plugin install vagrant-azure
Add the Azure Dummy Box:
vagrant box add azure-dummy https://github.com/azure/vagrant-azure/raw/v2.0/dummy.box --provider azure
Install Azure-cli with:
curl -sL https://aka.ms/InstallAzureCLIDeb | sudo bash
Login to your Azure Account with:
az login
Create Azure Service Principal with:
az ad sp create-for-rbac
The output of “az ad sp create-for-rbac” should look like the following:
{
"appId": "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX",
"displayName": "some-display-name",
"name": "http://azure-cli-2017-04-03-15-30-52",
"password": "XXXXXXXXXXXXXXXXXXXX",
"tenant": "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX"
}
The values tenant, appId and password map to the configuration values azure.tenant_id, azure.client_id and azure.client_secret in your Vagrant file or environment variables.
Create a Vagrantfile and add this config:
Vagrant.configure('2') do |config|
config.vm.box = 'azure-dummy'
# use local ssh key to connect to remote vagrant box
config.ssh.private_key_path = File.join(File.dirname(__FILE__), 'azure_private_key.id_rsa')
config.vm.provider :azure do |azure, override|
# each of the below values will default to use the env vars named as below if not specified explicitly
azure.tenant_id = ENV['AZURE_TENANT_ID']
azure.client_id = ENV['AZURE_CLIENT_ID']
azure.client_secret = ENV['AZURE_CLIENT_SECRET']
azure.subscription_id = ENV['AZURE_SUBSCRIPTION_ID']
end
####### Provisioner #######
config.vm.provision "ansible" do |ansible|
ansible.playbook = "playbook.yml"
ansible.verbose = true
end
end
Since we specified Ansible as our provisioned, we need to install it on our host machine:
sudo apt update
sudo apt install software-properties-common
sudo apt-add-repository ppa:ansible/ansible
sudo apt install ansible
Set up the ENV variables with:
export AZURE_CLIENT_ID=“***************************”
export AZURE_CLIENT_SECRET=“***********************”
export AZURE_TENANT_ID=“***************************”
export AZURE_SUBSCRIPTION_ID=“*********************”
Generate your SSH key:
ssh-keygen -t rsa -f azure_private_key.id_rsa
Create a “playbook.yml” that we’ll be using for provisioning:
---
- name: install nginx on a Azure VM instance
hosts: all
become: yes
become_method: sudo
gather_facts: yes
tasks:
- name: install nginx
apt:
name: nginx
update_cache: yes
state: present
- name: stop nginx service
service:
name: nginx
state: stopped
register: nginx_down
- name: delete the default html file
file:
path: /var/www/html/index.nginx-debian.html
state: absent
- name: copy new file from template folder
template:
src: ./index.html
dest: /var/www/html/index.html
owner: root
group: root
- name: restart nginx service
service:
name: nginx
state: restarted
Create a “templates” folder and add an index.html file. Paste this inside:
<!DOCTYPE html>
<html>
<head>
<title>Welcome to DevOps - Powered by Telios</title>
<style>
body {
width: 35em;
margin: 0 auto;
font-family: Tahoma, Verdana, Arial, sans-serif;
}
</style>
</head>
<body>
<h1>Welcome to Vagrant</h1>
<p>Powered By Telios</p>
<p>If you see this page, Our page is hosted on Nginx server on our VM with Vagrant.</p>
<br />
</body>
</html>
Return back to the base folder you were with:
cd ..
Now Run:
vagrant up
When the process is done, ssh into the provisioned VM with:
vagrant ssh
Access the localhost to check if our provisioning was successful. We can use curl but lets use lynx for a more formatted output:
sudo apt install lynx -y
lynx localhost
If we get the custom page then the process was a success.
Clean Up Vagrant
Once you are done working on your guest system, you have a few options on how to end the session.
To stop the machine and save its current state-run:
vagrant suspend
You can resume by running vagrant up again. This is much like putting the machine in sleep mode.
To shut down the virtual machine use the command:
vagrant halt
Again, vagrant up will reboot the same virtual machine, and you can resume where you left off. This is much like shutting down a regular machine.
To remove all traces of the virtual machine from your system type in the following:
vagrant destroy
Anything you have saved in the virtual machine will be removed. This frees up the system resources used by Vagrant. The next time you vagrant up, the machine will have to be re-imported and re-provisioned. This is much like formatting a hard drive on a system, then reloading a fresh image.
Thanks for your time!
Questions??
Top comments (0)