Can’t Use postgresql_db Module with Ansible

ansiblepostgresqlpython

Target server:

-bash-4.2$ python -V
Python 2.7.5
-bash-4.2$ pip list | grep psycopg2
psycopg2 (2.8.3)

But if run ansible playbook with this task will fail:

- name: Create repmgr database
  postgresql_db:
    name: repmgr
  become: true
  become_user: postgres

Error:

TASK [db : Create repmgr database] ***************************************************************************
fatal: [192.168.0.1]: FAILED! => {"changed": false, "msg": "Failed to import the required Python library (psycopg2) on db's Python /usr/bin/python. Please read module documentation and install in the appropriate location. If the required library is installed, but Ansible is using the wrong Python interpreter, please consult the documentation on ansible_python_interpreter"}

Why can't it import psycopg2?

Best Answer

You should make sure that the python autodiscovery or the fixed ansible_python_interpreter for your particular host is not pointing to an other version of python (than the one you used to install the lib).

If this is the case you can either:

  1. fix the version to the one you installed the library in (set ansible_python_interpreter for your host)
  2. install the library in the other version (e.g. pip3 install psycopg2)

Meanwhile, the best solution to make sure the requirement is always covered (in the correct python version) is to add the install to your playbook just before you actually use the postgres module:

- name: Make sure psycopg2 is installed
  pip:
    name: psycopg2
    state: present