quinot / ansible-plugin-lookup_ldap

Ansible LDAP lookup plugin
50 stars 16 forks source link

Add support for python 3 #32

Open hmooneyham opened 4 years ago

hmooneyham commented 4 years ago

This plugin currently crashes under python 3 for several reasons related to string encoding.

In python 3 the unicode type no longer exists and is simply the type str. As of Ansible 2.5 Ansible now supports the use of python 3 and this module currently fails if invoked under python 3 because the unicode function no longer exists.

Six provides a compatibility layer to support both python 2.7 and python

  1. Using six.text_type works safely in both python versions.

Additionally the encode function currently returns the raw string if no encoding is set which results in a string returned to ansible prefixed with a b which breaks compatibility with dictionary processing in Ansible. Instead this now defaults to ASCII to return ASCII strings.

aderixon commented 3 years ago

Thanks, this PR worked well for me except I had to add the following lines (based on another, similar PR) to avoid an encoding error on the uidNumber attribute (TypeError: ('attrs_from_List(): expected string in list', b'uidNumber')):

@@ -182,6 +185,12 @@
                 and key_attr not in base_args['attrlist']:
             base_args['attrlist'].append(key_attr.encode('ASCII'))

+        if not six.PY2:
+            try:
+                base_args['attrlist'] = [a.decode('ASCII') for a in base_args['attrlist']]
+            except KeyError:
+                pass 
+

I feel like there ought to be a more elegant solution for this that works across both Python 2 & 3, but I'm not fluent with it.