How to get ansible to use virtual environment on remote side with a role and local connection

I am using a role which should in theory install psycopg2 into my python (3.12.9) virtual environment (among other things), but after running it is installed into my system python (3.9.21). I am installing ansible 11.3 via pip into my python3.12 virtual environment and running it through that. AlmaLinux 9.5.

requirements.yml

- src: galaxyproject.galaxy
  version: 1.1.7

ansible.cfg

[defaults]
inventory=inventory.ini

inventory.ini

[local]
localhost ansible_connection=local

playbook.yml

- hosts: local
  roles:
    - galaxyproject.postgresql

Ansible informs it me it discovers my virtual environment (if i name it .venv) but regardless the step Install psycopg2 appears to install it into my system python.

The docuemntation for the module says that it attempts to install it into the “Python interpreter that ansible uses on the remote side” so how can I configure that.

I run the playbook as root using the virtual environment.

You need to explicitly tell Ansible which Python interpreter to use by setting the ansible_python_interpreter variable to point to your virtual environment’s Python binary.

For example, update your inventory.ini to something like:

[local]
localhost ansible_connection=local ansible_python_interpreter=/path/to/your/venv/bin/python

replace /path/to/your/venv/bin/python with the absolute path to your virtual environment’s Python executable.


You can olso specify the Python interpreter in your playbook.
Set the ansible_python_interpreter variable at the play level.

For example:

- hosts: local
  vars:
    ansible_python_interpreter: /path/to/your/venv/bin/python
  roles:
    - galaxyproject.postgresql

This documentation talks about how ansible discovers what interpreter to use, and how you can override that on a per host/group basis (using inventory variables) or globally (in ansible.cfg).

I’m not sure how that will interact with ansible_connection=local, but you should be able to set the path to the interpreter you want (full path to.venv/bin/python3) for localhost in the inventory.ini you’ve shown above.

Thanks for the help, this does work. But it turns out the specific role I was using was installing the python package through DNF instead of python pip. Not sure why. It was hardcoded to be installed to the system python.