Creating a Python Virtual Environment in Debian via Ansible
July 24, 2021
Debian is my preferred Linux distribution, particularly for servers. Although it is the base from which so many other distros are derived, it seems that it gets short shrift by a lot of packages. It took me a little while to figure out how to create a Python virtual environment on it with Ansible, so here is a quick example in the hopes that it may help others who hit this particular hurdle.
Two system installations are necessary:
- name: Install system packages
apt:
name:
- python3-pip
- python3-venv
# others you need
state: present
I prefer to use built-ins wherever possible, so I use venv
rather than packages like virtualenv
or pyenv
for virtual environments. Here is the task that will create one, using the pip module. It will also install any dependencies listed in a requirements.txt file:
- name: Set up virtual environment and install requirements.
pip:
virtualenv_command: /usr/bin/python3 -m venv
virtualenv: "/project/path/ve" # the directory to install the ve
requirements: "/project/path/requirements.txt"
You would think that would be all it takes, but for some reason, Ansible still appears to want to use Python 2 with Debian, so you need to tell it again that you want to use Python 3, this time at the inventory level. Declare the executable explicitly in the inventory file with the ansible_python_interpreter
variable, e.g.:
all:
hosts:
my_host:
ansible_host: # domain or ip
ansible_private_key_file: # /path/to/key
ansible_python_interpreter: /usr/bin/python3
Voilà, you should have a Python 3 virtual environment using the built-in venv
module.