Using venv in Ansible's projects

by (December 08, 2016)

Posted in Tools  Tags:Ansible, virtualenv

Everyone who is using Ansible sooner or later will encounter some version incompatibiliity problems. Usually problems are related to behavior changes, new features and other things in new release.

Not surprisingly, most urgent work could be blocked by those ansible incompatibiliity problems which tend to appear on a deployment scripts used rarely. Moreover, those bugs start to appear in the time when we run some rarely used deployment script, and we need to run it now, and urgently.

Our solution is on the surface: because Ansible is the Python project, thus we can rely on Python management and virtual environment:

So let’s create in a project directory script called venv-ansible-playbook

#!/bin/bash

PROJECT_ROOT="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
VENV="$PROJECT_ROOT/.venv"

if [ ! -e "$VENV" ]; then
    virtualenv $VENV
    source $VENV/bin/activate
    pip install -r $PROJECT_ROOT/requirements.txt
    if [ $? -ne 0 ]; then
        rm -rf $VENV
        exit 1
    fi
fi

if [ ! -z "$1" ]; then
    source $VENV/bin/activate
    $VENV/bin/ansible-playbook $*
fi

and requirements.txt

ansible==2.1.2

Now we should change the instructions to work with Ansible’s playbooks.

Before:

ansible-playbook -i inventory_file playbook.yaml

Now:

./venv-ansible-playbook -i inventory_file playbook.yaml

That’s all, folks. So, without any dependency on upcoming changes appearing in Ansible, your project will work - because it uses Ansible version you hardcoded when configured the project.

Is it so easy?

Let us know!

Contact details:

 

Services you are interested in: