RoleSpec does a great job helping out testing your roles. It is
maintained and used primarily to test the DebOps role suite by the
fine folks hanging out in #debops IRC channel.
RoleSpec handles all the boiler plate to run tests (installing the right version
of Ansible, adjusting paths, taking care of the inventory, wrapping your role in
a playbook, …) and privides a simple DSL to write tests.
However, in its current state, RoleSpec is mostly intended to run a test suite
on travis. And this test suite is separated from your role.
I personally prefer to have my role tests along the Ansible role, in a tests
We see below how we can achieve this with RoleSpec, and will leverage Vagrant
for this. We’ll also use Guard to continuously test our role while writing it.
A simple role
Let’s start by creating a simple nginx role:
The tests directory will be used for our tests later.
If you already have a role want to convert it, create the tests/ansible-
nginx/ directory and skip straight to
In default/main.yml, we’ll declare a few default values for our role. We won’t do much,
in our role, just install nginx and set a few variables, so let’s keep this
For the handlers part, handlers/main.yml will contain a basic restart handler, followed by a port check for good measure:
Now the task part. I always put my tasks in a separate file, and include this
file from main.yml. This trick will allow you to set a tag for the whole
included file, like so:
And then, in nginx.yml, put the real tasks:
We just need to add 2 templates, and our role will be ready. The first one is the main nginx.conf.j2 file:
The file is a bit long, but it just contains basic settings. Note that we’re
aligning the number of worker processes to the number of processors reported by
Ansible for the host.
We are also switching cipher suites depending on whether we want to support IE8
Then, we just add a default virtualhost on our server:
Our role is now ready. We can now setup the tooling for our tests as explained in part 2