Ansible testing strategy using Docker

If you have been working on Ansible roles one thing you might have come across is how to test it? Well great news, in this article I’m going to show you how to test Ansible roles using Docker containers in TravisCI.

Testing Ansible roles is a great practice! Some of us work on a certain type of OS and so when we are developing our Ansible roles we could write it in a way such that can support multiple OS versions. This is why we would need to utilize a Continous Integration tool that will test our Ansible roles across several OS.

Ex: In CentOS 7 if you are installing PHP 7 the libmemcached module does not exist. But, it does on CentOS 6.

How to test Ansible roles?

In this example, let’s consider you have multiple roles which install.

  1. Apache
  2. PHP

our role directory structure will include a tests folder by default:

-- roles
 |- apache
      - tests
        - inventory
        - test.yml
 |- php
      - tests
        - inventory
        - test.yml
 |- test.sh
  - test.yml

There are two new files that we need to add “test.sh” and “test.yml”. The test.sh is a shell script which will launch a Docker container, copy the roles and run the test.yml playbook.

#test.yml
---
- hosts: localhost
  remote_user: root
  roles:
    - apache
    - php

Download the test.sh from Jeff Geerling  Gist.

The test.sh will launch a Docker container with Ansible installed. Checks the Ansible role syntax and then installs it locally.

Travis CI build file

Our Travis CI build will be simple. We want to achieve the below points:

  • Test on multiple OS CentOS 6, CentOS7
  • Check the Ansible role syntax is valid.
  • Successfully install the Apache and PHP role without any errors.

There are few reasons in are using a Docker container to test the Ansible roles. Launching Docker is fast and we could have a Docker image preinstalled with Ansible.

In our Travis CI build will include the different OS types.

---
services: docker

env:
  - os: centos7
  - os: centos6

script:
  
  - ${PWD}/roles/test.sh

It is a good practice to test Ansible roles on different versions of OS. Travis CI is a great CI tool as part of your DevOps culture.

When a push is made, this will trigger a Travis CI build.

 

If you receive “role” not found, look into the shell script path it could be the path of Role is incorrect as the shell script mounts the roles to the Docker container.