Over the next few weeks I have planned a series of blog posts on how I test my Ansible roles with Molecule. Rather than assume that people are working in Ansible the same way I am, I decided to quickly write up what my testing environment looks like. These instructions were written for working in Ubuntu 18.04, but they should generally work with any OS as long as you have all the right python bits installed.

Installing Virtualenvwrapper

After being bit in the rear a number of times with Ansible upgrades, I started using virtualenv for creating individual python environments for each version of Ansible. A couple years back I was turned on to virtualenvwrapper and have used that to manage my virtualenvs ever since. Since virtualenv is a requirement for virtualenvwrapper, you can install them both with one easy command:

pip install virtualenvwrapper

Once you have virtualenvwrapper installed, you will need to add the following to your .bashrc file so that it runs every time you log in:

if [ -f /usr/local/bin/virtualenvwrapper.sh ]; then
export WORKON_HOME=~/.virtualenvs
source /usr/local/bin/virtualenvwrapper.sh
# Optional

Setting the PIP_REQUIRE_VIRTUALENV variable is optional. Setting it to true will configure pip to work only if you are in a virtual environment. I find this helpful to set so that I am not accidentally installing pip packages outside of the environment that needs them and cluttering up my laptop.

Create the Virtualenv

Once virtualenvwrapper is installed, I can create individual python environments for running and testing my Ansible code. Since we have standardized in python3 for our development work, we run our Ansible in python3 as well (you can omit the “-p python3” if you want to use python2. To create a virtual environment to work with the latest version of Ansible and Molecule, you can run the following commands:

mkvirtualenv -p python3 ansible-2.6
pip install ansible molecule docker

I also like to be able to test with other versions of Ansible, so I have a couple of older versions of Ansible setup as well. You could create an older version by specifying the Ansible version you want to install:

mkvirtualenv -p python3 ansible-2.5
pip install ansible==2.5.8 molecule docker

Now when I am working in an Ansible environment and can switch between different versions by deactivating one and working on the other:

(ansible-2.6) | ( austincloudguru:~)
% deactivate
( austincloudguru:~)
% workon ansible-2.5
(ansible-2.5) | ( austincloudguru:~)

That’s it. I can run my Ansible tests across different versions to validate compatibility with each version.