I typically run Ansible in a virtualenv instead of using my Linux distro’s packaged version.

I started having some trouble running AWS playbooks, getting this error message on a playbook:

"Failed to import the required Python library (botocore and boto3) on x270's Python /usr/bin/python3. Please read the module documentation and install it 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"

Here are the conditions:

  • Ansible was running against localhost.
  • The virtualenv had botocore and boto3 installed.
  • The interpreter in the error message is not the virtualenv interpreter, so Ansible is selecting the wrong interpreter.

The fix was “easy”. I added this line to my ansible.cfg file:

interpreter_python = /home/mutt/.virtualenv/env.ansible/bin/python3

But:

While this made Ansible execute correctly on the local machine, the remote hosts started failing with this message:

{"module_stdout": "/bin/sh: 1: /home/mutt/.virtualenv/env.ansible/bin/python3: not found",
"msg": "The module failed to execute correctly, you probably need to set the interpreter. See stdout/stderr for the exact error"}

Oops! Ansible needs Python on the remote server and I was telling it to look in a nonexistent location for the executable.

It turns out that I had been a little too hasty in my config. According to the Ansible docs:

  • ansible_python_interpreter is for individual hosts and groups.
  • interpreter_python is a global setting meant for ansible.cfg.

ansible_python_interpreter can also be set in a hosts file, so that’s what I did:

  1. I removed the interpreter_python option from my ansible.cfg.
  2. I added ansible_python_interpreter to my hosts file for the configuration of my laptop like this:
[x270]
localhost ansible_connection=local interpreter_python=/home/mutt/.virtualenv/env.ansible/bin/python3

After this, everything executed properly.