2 min read

Simplifying local Ansible and Vagrant setup

To make context switching easier it’s always a good idea to simplify project specifics with simple bin scripts. They don’t need to do everything but they should at least be a good jump start to get the project going. Here’s a few simples ones that I’ve been using to get my local Ansible and Vagrant setup configured. I utilize Vagrant and Ansible for most of my local development environments.

First there’s the bin/setup script which is essentially a bootstrap command.

#!/bin/sh

vagrant plugin install vagrant-env

example_files=(.env host_vars/rails)

for i in "${example_files[@]}"
do
  if [ ! -f $i ]; then
    echo "Creating $i for you, modify if necessary"
    cp $i.example $i
  fi
done

ansible-galaxy install -r requirements.yml --force

Utilizing vagrant-env for configuration makes it easier to customize the Vagrant VMs based on the resources of the machine that it’s running on. You can set anything you’d like in .env and then reference that via ENV in your Vagrantfile which is really useful.

For each of the files that it’s copying over it’s starting from an example file so that no intervention is requireed to get things running. host_vars/rails contains some Ansible host specific variables for a default rails box to configure locally.

After that we just ensure that all of the Ansible Galaxy roles are installed that are specified in requirements.yml. At this point we mostly just have a functioning Ansible control machine setup.

From here we’ll add another script to get the Vagrant virtual machine configured, this script will utilize the setup script as a starting point.

#!/bin/sh

./bin/setup

echo "Prompting you for your local password..."
ansible-playbook -i inventory/localhost -s osx.yml -U `whoami` -K

echo "Hit enter when it prompts for the 'SUDO password'"
vagrant up rails
vagrant provision rails

echo "All set, map a hostname in /etc/hosts to 192.168.50.4 on your local machine"

For the Vagrant script it’s first configuring a couple of things on the local machine to resolve .dev to localhost from the osx.yml playbook. Then we bring up the rails specific virtual machine and then ensure it’s provisioned. This can also be done via vagrant up rails --provision but that’s always been a bit hit or miss on failure. Then we provide a simple setup note at the end of the script to point the user in the right direction.

They’re both very simple scripts but whenever this is installed on a new machine or requirements.yml changes it’s as simple as running bin/setup or bin/vagrant instead of remembering that you have to pass --force to the ansible-galaxy install command for existing roles or that -r is the requirements file location instead of perhaps -c(for configuration).

bin/setup - Ansible/Vagrant bootstrap steps.

bin/vagrant - provision a default local VM.