Ansible fails with ModuleNotFoundError: No module named 'pexpect'

Viewed 7350

I have three hosts, all running Ubuntu 18.04 with latest updates:

  • master and staging are hosts that I have installed myself from an Ubuntu 18.04 image.
  • prod is a host that I have leased from a provider, so I have no control on the basic installation beyond selecting Ubuntu 18.04.
  • master has Ansible installed.

ansible --version yields:

ansible 2.9.6
  config file = /home/marco/Desktop/playbook/ansible.cfg
  configured module search path = [u'/home/marco/.ansible/plugins/modules', u'/usr/share/ansible/plugins/modules']
  ansible python module location = /usr/lib/python2.7/dist-packages/ansible
  executable location = /usr/bin/ansible
  python version = 2.7.17 (default, Nov  7 2019, 10:07:09) [GCC 7.4.0]

ansible.cfg contains the line interpreter_python = auto.

My playbook works fine when run with target host staging. But when running with target host prod, it fails when running the expect module:

An exception occurred during task execution. To see the full traceback, use -vvv. The error was: ModuleNotFoundError: No module named 'pexpect'
fatal: [prod]: FAILED! => {"changed": false, "msg": "Failed to import the required Python library (pexpect) on prod's Python /usr/bin/python3. 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"}

I have tried to solve the problem by installing libries on master by

apt-get install python-pexpect
apt-get install python-pip
pip install pexpect

and on prod by adding

- name: Install packages
  apt:
   name:
      - python-pexpect
      - python-pip
- name: Install Python modules
  command: pip install pexpect

to the playbook, but it did not help.

3 Answers

Try the built-in pip Anisble module, it will detect which version of pip Ansible is using on the controlled node.

    - name: Install pip
      apt:
        update_cache: yes
        name:
          - python3-pip

    - name: Install pexpect
      pip:
        name: pexpect

this is how i solved it

- name: Install pexpect
  pip:
     name: pexpect
  become: true

You can install geerlingguy.pip role from ansible galaxy with the following command :

ansible-galaxy install geerlingguy.pip

then add this on top of your playbook :

hosts: "{{myhost}}"
vars:
  pip_install_packages:
    - name: pexpect
  pip_package: python-pip
  pip_executable: pip
roles:
  - geerlingguy.pip

You can then use expect in ansible normally.

Related