Search code examples
pythonpython-3.xansiblevirtualenv

Using pymongo installed via virtualenv and Ansible returns an error


Since it's good practice to install pip modules in virtual environment, I have the following task in place:

- name: Install python packages
  ansible.builtin.pip:
    name:
      - pymongo
    virtualenv: /home/user/.venv

However, the taks that supposed to use pymongo returns an error: ModuleNotFoundError: No module named 'pymongo'

This is the task:

- name: Create database database user
  community.mongodb.mongodb_user:
    login_user: root
    login_password: 12345
    database: somedb
    name: some_user
    password: 12345
    state: present
    roles:
       - { db: "xxx", role: "dbOwner" }
       - { db: "yyy", role: "dbOwner" }

How can I fix the Ansible playbook so that the pymongo installed in the virtual environment is found? Also, if I run pip list pymongo is not listed and this let me think that I'm missing a piece in the chain.


Solution

  • I might have found a solution that works, I'm just unsure if it is the right approach. I added a task that switch the Python interpreter to the one created within the virtual environment:

    - name: set new Python interpreter
      ansible.builtin.set_fact:
        ansible_python_interpreter: /home/user/.venv/bin/python
    

    Maybe someone can confirm if this is the right way.