Python 3: Unexpected Exception: name 'basestring' is not defined when invoking ansible2

By: Varghese Chacko 1 year ago

Python 3: Unexpected Exception: name 'basestring' is not defined when invoking ansible2 

When we do 

ansible-playbook -vvv -i my/inventory my/playbook.yml

We may endup getting following error

Unexpected Exception: name 'basestring' is not defined the full traceback was:

Traceback (most recent call last):
  File "/usr/local/bin/ansible-playbook", line 85, in <module>
  File "/usr/local/lib/python3.4/site-packages/ansible/cli/", line 150, in run
    results =
  File "/usr/local/lib/python3.4/site-packages/ansible/executor/", line 87, in run
  File "/usr/local/lib/python3.4/site-packages/ansible/executor/", line 149, in load_callbacks
    elif isinstance(self._stdout_callback, basestring):
NameError: name 'basestring' is not defined

The reason for above error is Ansible below version 2.5 requires Python 2.6 or 2.7 on the control host: Control Machine Requirements and basestring is no longer available in Python 3. The documentation says

The builtin basestring abstract type was removed. Use str instead. The str and bytes types don’t have functionality enough in common to warrant a shared base class. The 2to3 tool (see below) replaces every occurrence of basestring with str.

If we install ansible using pip and pip3, it erroneously pointsto python3, but if you do pip2 install ansible, it will work fine, putting this at the top of each ansible utility: #!/usr/local/opt/python/bin/python2.7

Another workaround may be using the following code at top of the script.

except NameError:
  basestring = str