Installing Ansible in a Python virtual environment enables us to maintain the Ansible dependencies which are basically python packages, independent of the ones used by the Operating System.

Below are the steps involved in installing Ansible in a virtual environment, in Red Hat Enterprise Linux 7 Operating System.

Install preliminary packages

sudo easy_install virtualenv

sudo yum -y install git gnupg2 python-devel python-crypto python-setuptools python2-pip python-virtualenv sshpass gcc openssl-devel

Create directory for Ansible

mkdir -p ~/virt/ansible-2.7.0

Create virtual environment for Ansible

virtualenv --no-site-packages ~/virt/ansible-2.7.0

Create alias for activating Ansible in virtual environment

echo "alias virtansible='source ~/virt/ansible-2.7.0/bin/activate'" >> ~/.bashrc && source ~/.bashrc

Activate virtual environment


In virtual environment, Upgrade python pip and setup-tools

(ansible-2.7.0) $ pip install --upgrade pip

(ansible-2.7.0) $ pip install --upgrade setuptools

Install Ansible in virtual environment

(ansible-2.7.0) $ pip install ansible

Note, any python packages that you may require can be installed similarly by running command ‘pip install package_name. Example: pip install git.

You should be able to verify installation of ansible in the virtual environment, by checking the Ansible and python path, which should show up under ~/virt/ansible-2.7.0

[admin@unixutils ~]$ virtansible
(ansible) [admin@unixutils ~]$ which ansible
(ansible) [admin@unixutils ~]$ which python
(ansible) [admin@unixutils ~]$ deactivate
[admin@unixutils ~]$ 

Note, you can exit from the Ansible virtual environment by running the command ‘deactivate’.