Working with Ansible

I think that the year 2013 could be remembered by most web developers as the year “DevOps” became a vital part of the workflow. From the growth that dev tools like Vagrant and Docker have seen (Docker wasn’t around before 2013) it’s sometimes hard to keep up with all of the scuttlebutt.

Ansible follows in line with it’s two closest competitors, Puppet and Chef. It fills the role to scientifically create the server/software layer your code is written against. A well written Ansible task will move a server from nothing to a fully working, ready to use process that can be repeated without differences.

Beginning with Ansible is simple; I recommend installing it first. In OSX you can install via Homebrew. For another OS, many options are available.

1
2
# Install Brew
$> ruby -e "$(curl -fsSL http://bit.ly/1jHq26L)"

Once homebrew is installed, run brew install ansible and you’re all set.

Ansible and Vagrant work well together. Using Ansible on a remote machine is as simple as it is with a Vagrant machine (and in many ways identical) so it makes sense to work develop locally via a Vagrant server.

Vagrant 1.3+ now has Ansible built in as a ‘provisioner‘. Here is a simple example Vagrantfile for getting started.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
Vagrant.configure("2") do |config|

config.vm.define "app1", primary: true do |app|

# ...

# use the ansible provisioner
app.vm.provision "ansible" do |ansible|
# inventory paths are good for default hosts
ansible.inventory_path = "files/hosts"
# run your code!
ansible.playbook = "tasks/main.yml"
# verbosity of the output v-vvvv; more v's, more verbose
# ansible.verbose = 'vvvv'
end
end

I’ve pointed Vagrant at the tasks/main.yml which begins the process tree to setting up your server. Here is a simple but eye-opening example main.yml.

1
2
3
4
5
6
---
- hosts: appserver
sudo: yes
remote_user: vagrant
tasks:
- include: nodejs.yml

I’m doing a few things here of importance, but mainly just including a nodejs.yml which, as you can guess, is going to install NodeJS.

1
2
3
4
5
- name: Grabbing the node repository
apt_repository: repo='ppa:chris-lea/node.js' state=present update_cache=yes

- name: Install node!
apt: pkg=nodejs state=latest

And that’s that. If you were to add this to your Vagrant file and paths, calling vagrant up would install NodeJS on your server (well, Debian/Ubuntu server that is!).

There’s a lot more there, and it’s hard to give a full example in a short blog post. Definitely take a look at the great documentation for more information.