Getting started with Vagrant Shell Provisioning

When working on a project, it is not unknown for there to be problems when moving code from the development/testing environment – on which everything appears to work perfectly – to a live environment, at which point errors start to occur due to differences in the two servrer setups. For example, suppose you are working on some PHP code and you make use of DateTime::diff(). The code may work perfectly fine in your development environment, which is running PHP 5.3, but when you put the code into production it turns out that your live server is running PHP 5.2 – and the code stops working.

Recently I decided to try out Vagrant for setting up development environments, which is a tool to help developers to create virtual machines which match the setup of the environment they will eventually deploy to. In following the Get Started guide, I wasn’t sure whether to go Chef or Puppet for provisioning, and on looking further into the docs I found this:

Which Provisioner Should I Use?

Ah, with the freedom of choice comes the complication of choosing what is right for you. However, if you’re asking this question, then almost certainly the best choice for you to get started is the shell provisioner. This provisioner lets you run a shell script with root privileges within your virtual machine. It doesn’t get any simpler than that!

So, Shell it is, I thought: this will give me a chance to learn a bit of Bash at the same time. However, I couldn’t find a lot of info on what to put in my shell script, so for those looking to get started a bit quicker than I did I present my basic shell script to serve the index.html file from the Get Started tutorial.

Save the following in a file called in the same directory as your Vagrantfile

# Run check for whether apache2 has been installed
dpkg -l apache2 >/dev/null 2>&1

# Get return value of our check

# Act on our return value
if [ $INSTALLED == '0' ]; then
  echo "apache2 is already installed."
  # Install apache2
  apt-get install -y apache2

  # Change DocumentRoot to match Vagrant's VirtualBox shared folder
  sed -i 's/var\/www/vagrant/g' /etc/apache2/sites-enabled/000-default

  # Restart Apache for changes to take effect
  service apache2 restart

Then follow the instructions in the Shell Provisioner docs to reference your new shell script (just add the following in your Vagrantfile): do |config|
  config.vm.provision :shell, :path => ""

If, like me, you’re new to bash and would like to know more about the first two lines of code in the script, then the following posts might be useful:

Leave a Reply

Unable to load the Are You a Human PlayThru™. Please contact the site owner to report the problem.