Install Ansible with Python3 (Ubuntu, Debian)

Article on the 12/12/2021 by Jules SAGOT

Do you want to start or use an Ansible project? This article explains how to install Ansible for your project using Python 3 and the venv module on Debian or Ubuntu.

Installing Python and its dependency manager

You need Python and a Python package manager to install Ansible. In this tutorial, we will use Pip as the package manager. On Debian or Ubuntu, you can install it with apt:

sudo apt update
sudo apt install python3 python3-pip python3-venv

Creating a virtualenv in the root of your project

Open a terminal in the root folder of your project:

# optional: mkdir -p ~/path/to/your-project
cd ~/path/to/your-project

Then, create a virtualenv called .venv that will contain the Python packages useful for this project (including Ansible). To do this, we use the Python venv module (with the -m venv option) that was previously installed on your machine, passing as an argument the name of the folder that will contain the Python virtualenv (here, .venv).

python3 -m venv .venv

Next, you need to activate the virtualenv. Once the virtualenv is activated, your shell will no longer use the Python interpreter located at /usr/bin/python3. Instead, the Python program located in the virtualenv will be used. Once the virtualenv is activated:

  • All Python library installations made with Pip will be installed in the virtualenv.
  • The libraries available for import will be those installed in the virtualenv.
  • The Python program located at /usr/bin/python3 will not have access to the libraries installed in the virtualenv.

Using a Python virtual environment allows you to isolate packages between your different projects. This helps avoid Python dependency conflicts between projects.

which python3
# result: /usr/bin/python3

source .venv/bin/activate

which python3
# result: ~/chemin/de/votre-projet/.venv/bin/python3

Installing Ansible in the virtualenv

Now that we have created our virtualenv, we will install the Python packages for Ansible and wheel (dependency) using Pip:

pip3 install wheel ansible

To verify that Ansible is properly installed, you can display the software version or test the connection to yourself using the ansible ping module:

ansible --version
# résultat:
# ansible [core 2.12.1]
#   ...

ansible localhost -m ping
# résultat:
# localhost | SUCCESS => {
#     "changed": false,
#     "ping": "pong"
# }

Nota bene

To use Ansible, you must have activated your project’s Python environment with the source .venv/bin/activate command. You will need to do this each time you use a new terminal.

You can exit the activated virtualenv with the deactivate command.

Final word

You now have Ansible installed in your project’s virtual environment.

Wishing that your infrastructure-as-code project is as clean as this Ansible installation :smile: