Vagrant config and shell provisioning with JSON

There’s a lot of YAML Vagrant confs out there and I have personally not seen that many with JSON. As I was updating wp-scratch-box , I thought it would be cool to make a sample template out of the Vagrant bits and write a post. The link to the example repo with the code for this post is below.

For Vagrant itself there’s not much difference from YAML. You require Rubys’ JSON module and replace the configuration values for your JSON ones:

The advantage of using JSON shines in the shell provisioning of a Vagrant box combined with the nifty CL tool JQ: you can pass values to your Bash script easily this way. Here is an example with an Ubuntu box. In your provisioning script:

1. #!/bin/bash
2. IFS=$'\n\t'
3. sudo apt-get -qq update && sudo apt-get -qq install jq -y
6. config=($(jq -r '.Project.provision|.[]' /vagrant/Vagrant.json))
7. printf "%s\n" ${config[@]}

Line 2 is an important part of the script as it prevents wordsplitting. Setting IFS to handle line breaks and tabs properly will prevent a JSON value with space to be read as two values.  It has more usefulness than that, you can read up more about it in Aaron Maxwells’ unofficial strict mode for Bash (link below).

After that comes installing JQ from the package repo. Once installed, we can start reading the Vagrant JSON file for any options defined. In this example (line 6) an array is created which stores values read by JQ. Line 7 prints out the array that has just been created.

This is a very basic example of course but I hope this gets you started writing what I like to think of modular/reusable Vagrant configs.