Solving ModuleNotFoundError: No module named ‘ansible’

My Problem

When running any ansible command, I see a stack trace similar to:

Traceback (most recent call last):
File "/usr/local/bin/ansible", line 34, in
from ansible import context
ModuleNotFoundError: No module named 'ansible'

My Solution

pip install ansible or brew install ansible or yum install ansible or…

Somehow your Ansible Python modules were removed, but the Ansible scripts in your $PATH remained. Install Ansible’s python package however makes the most sense for your platform and preferences. E.g. via pip directly or Homebrew or your package manager of choice.

The Long Story

Let’s break the error down line by line:

File "/usr/local/bin/ansible", line 34, in

Ansible is just a Python script, so let’s check out line 34:

[...]
31 import sys
32 import traceback
33
34 from ansible import context
35 from ansible.errors import AnsibleError, AnsibleOptionsError, AnsibleParserError
36 from ansible.module_utils._text import to_text
[...]

The second line in the stack trace shows that from ansible import context is just another module import in the larger context of the Python application. With that larger context clarified, this error may snap a bit more into focus:

ModuleNotFoundError: No module named 'ansible'

It’s just a Python application that can’t find a module. If there’s no module, let’s check with Python to see what packages it knows about:

$ pip list

Package    Version
---------- -------
gpg        1.14.0
pip        20.1.1
protobuf   3.13.0
setuptools 49.2.0
six        1.15.0
wheel.     0.34.2

There’s no Ansible package listed. Wait, which version of Python did I just check?

$ which pip
pip: aliased to pip3

Let’s check pip2 just to make sure there’s no version weirdness going on:

$ pip2 list

Package      Version
------------ -------
altgraph     0.10.2
asn1crypto   0.24.0
bdist-mpkg   0.5.0
bonjour-py   0.3
boto         2.49.0
cffi         1.12.2
cryptography 2.6.1
enum34       1.1.6
future       0.17.1
[...]

Nope, no Ansible. Since I’m on a Mac, let’s check Brew just to see what comes back:

brew list ansible
Error: No such keg: /usr/local/Cellar/ansible

I’m not really sure what happened. I’ve got the Ansible scripts in my path, but I don’t have the python modules. I prefer to install Ansible via pip so I simply pip install ansible and everything was right with the world.

Leave a Reply

Your email address will not be published. Required fields are marked *