Vagrant is a command-line tool that provides you with a configurable, reproducible, and portable development environment using VMs. It lets you define and use preconfigured disk images to create new VMs from. Also, you can configure Vagrant to use provisioners such as Shell scripts, Puppet, or Chef to bring your VM into the desired state.
In this recipe, we will see how to use Vagrant to manage VMs using VirtualBox and Chef client as the provisioner.
The Vagrantfile
is written in a Ruby Domain Specific Language (DSL) to configure the Vagrant virtual machines. We want to boot a simple Ubuntu VM. Let's go through the Vagrantfile
step by step.
First, we create a config
object. Vagrant will use this config
object to configure the VM:
Inside the config
block, we tell Vagrant which VM image to use, in order to boot the node:
We want to boot our VM using a so-called Bento Box, provided by Chef. We use Ubuntu Version 16.04 here.
Note
If you have never used the box before, Vagrant will download the image file (a few hundred megabytes) when you run vagrant up
for the first time.
As we want our VM to have the Chef client installed, we tell the omnibus vagrant plugin to use the latest version of the Chef client:
After selecting the VM image to boot, we configure how to provision the box by using Chef. The Chef configuration happens in a nested Ruby block:
Inside this chef
block, we need to instruct Vagrant on how to hook up our virtual node to the Chef server. First, we need to tell Vagrant where to store all the Chef stuff on your node:
Vagrant needs to know the API endpoint of your Chef server. If you use hosted Chef, it is https://api.chef.io/organizations/<YOUR_ORG>
. You need to replace <YOUR_ORG>
with the name of the organization that you created in your account on hosted Chef. If you are using your own Chef server, change the URL accordingly:
While creating your user on hosted Chef, you must have downloaded your private key. Tell Vagrant where to find this file:
Also, you need to tell Vagrant which client it should use to validate itself against in the Chef server:
Finally, you should tell Vagrant how to name your node:
After configuring your Vagrantfile
, all you need to do is run the basic Vagrant commands such as vagrant up
, vagrant provision
, and vagrant ssh
. To stop your VM, just run the vagrant halt
command.