diff --git a/changelogs/fragments/5450-allow-for-xordered-dns.yaml b/changelogs/fragments/5450-allow-for-xordered-dns.yaml new file mode 100644 index 0000000000..1bb1d9c761 --- /dev/null +++ b/changelogs/fragments/5450-allow-for-xordered-dns.yaml @@ -0,0 +1,2 @@ +minor_changes: + - ldap_attrs - allow for DNs to have ``{x}`` prefix on first RDN (https://github.com/ansible-collections/community.general/issues/977, https://github.com/ansible-collections/community.general/pull/5450). diff --git a/plugins/module_utils/ldap.py b/plugins/module_utils/ldap.py index daf89f16d1..03acaa58c5 100644 --- a/plugins/module_utils/ldap.py +++ b/plugins/module_utils/ldap.py @@ -15,6 +15,8 @@ from ansible.module_utils.common.text.converters import to_native try: import ldap + import ldap.dn + import ldap.filter import ldap.sasl HAS_LDAP = True @@ -48,7 +50,6 @@ class LdapGeneric(object): self.module = module self.bind_dn = self.module.params['bind_dn'] self.bind_pw = self.module.params['bind_pw'] - self.dn = self.module.params['dn'] self.referrals_chasing = self.module.params['referrals_chasing'] self.server_uri = self.module.params['server_uri'] self.start_tls = self.module.params['start_tls'] @@ -58,6 +59,9 @@ class LdapGeneric(object): # Establish connection self.connection = self._connect_to_ldap() + # Try to find the X_ORDERed version of the DN + self.dn = self._find_dn() + def fail(self, msg, exn): self.module.fail_json( msg=msg, @@ -65,6 +69,24 @@ class LdapGeneric(object): exception=traceback.format_exc() ) + def _find_dn(self): + dn = self.module.params['dn'] + + explode_dn = ldap.dn.explode_dn(dn) + + if len(explode_dn) > 1: + try: + escaped_value = ldap.filter.escape_filter_chars(explode_dn[0]) + filterstr = "(%s)" % escaped_value + dns = self.connection.search_s(','.join(explode_dn[1:]), + ldap.SCOPE_ONELEVEL, filterstr) + if len(dns) == 1: + dn, dummy = dns[0] + except Exception: + pass + + return dn + def _connect_to_ldap(self): if not self.verify_cert: ldap.set_option(ldap.OPT_X_TLS_REQUIRE_CERT, ldap.OPT_X_TLS_NEVER)