Changeset - 6b57aabf9556
[Not reviewed]
0 1 0
Branko Majic (branko) - 11 years ago 2015-03-08 11:22:24
branko@majic.rs
MAR-1: Fixed the handling of state addattributes in ldap_entry module to be more optimal (which also fixes some issues with cn=config additions related to inability to remove some attribute values).
1 file changed with 11 insertions and 6 deletions:
0 comments (0 inline, 0 general)
roles/ldap_server/library/ldap_entry.py
Show inline comments
 
@@ -135,203 +135,208 @@ def get_ldap_connection(uri, bind_dn=None, bind_password=""):
 
      Password to be used for simple bind. Needs to be set only if bind_dn is
 
      set as well. Default is "".
 

	
 
    Returns:
 

	
 
    LDAP connection object.
 
    """
 

	
 
    connection = ldap.initialize(uri)
 

	
 
    if bind_dn:
 
        connection.simple_bind_s(bind_dn, bind_password)
 
    else:
 
        connection.sasl_interactive_bind_s("", ldap.sasl.external())
 

	
 
    return connection
 

	
 

	
 
class LDAPEntry(object):
 
    """
 
    Implements a convenience wrapper for managing an LDAP entry.
 
    """
 

	
 
    def __init__(self, dn, attributes, connection):
 
        """
 
        Initialises class instance, setting-up the necessary properties.
 

	
 
        Arguments:
 

	
 
        dn
 
          Distinguished name (DN) of an entry.
 

	
 
        attributes
 
          Attributes that should be set for an entry.
 

	
 
        connection
 
          An instance of LDAPObject class that will be used for running queries
 
          against an LDAP server.
 
        """
 

	
 
        self.connection = connection
 
        self.dn = dn
 
        self.attributes = attributes
 

	
 
    def add(self):
 
        """
 
        Adds entry to the LDAP directory.
 

	
 
        Returns:
 

	
 
        True, if entry was added, or had to be updated to match with requested
 
        attributes. False, if no change was necessary.
 
        """
 

	
 
        # If entry already exists with set attributes, only update it.
 
        if self.exists():
 
            return self._update()
 

	
 
        # Otherwise we need to add a new entry.
 
        self.connection.add_s(self.dn, ldap.modlist.addModlist(self.attributes))
 

	
 
        return True
 

	
 
    def delete(self):
 
        """
 
        Removes entry from an LDAP directory.
 

	
 
        Returns:
 

	
 
        True, if entry was removed. False if no change was necessary (entry is
 
        already not present).
 
        """
 

	
 
        if self.exists():
 
            self.connection.delete_s(self.dn)
 

	
 
            return True
 

	
 
        return False
 

	
 
    def addattributes(self):
 
        """
 
        Adds attributes to an existing entry.
 

	
 
        Returns:
 

	
 
        True, if entry was updated with new attribute values. False if no change
 
        was necessary (values are already present).
 
        """
 

	
 
        if not self.exists():
 
            raise Exception("Module error: Can't add attributes for an entry. Entry does not exist.")
 

	
 
        attribute_list = self.attributes.keys()
 

	
 
        current_attributes = self.connection.search_s(self.dn, ldap.SCOPE_BASE, attrlist=attribute_list)[0][1]
 
        new_attributes = deepcopy(self.attributes)
 

	
 
        # This dictionary will contain all new attributes (or attribute values)
 
        # that should be added to the entry. We can't rely on modifyModlist
 
        # unfortunately, since if the values already exists, it will try to
 
        # remove and re-add them.
 
        new_attributes = {}
 

	
 
        # If attribute is already present, only add the difference between
 
        # requested and current values.
 
        for attribute, values in current_attributes.iteritems():
 
            if attribute in new_attributes:
 
                new_attributes[attribute].extend(values)
 
                new_attributes[attribute] = list(set(new_attributes[attribute]))
 
            if attribute in self.attributes:
 
                new_attributes[attribute] = [ item for item in self.attributes[attribute] if item not in values ]
 
            else:
 
                new_attributes[attribute] = values
 

	
 
        modification_list = ldap.modlist.modifyModlist(current_attributes,
 
                                                       new_attributes)
 
        modification_list = ldap.modlist.modifyModlist({}, new_attributes)
 

	
 
        if not modification_list:
 
            return False
 

	
 
        self.connection.modify_s(self.dn, modification_list)
 

	
 
        return True
 

	
 
    def replaceattributes(self):
 
        """
 
        Replace attributes of an existing entry.
 

	
 
        Returns:
 

	
 
        True, if entry was updated with new attribute values. False if no change
 
        was necessary (values are already present).
 
        """
 

	
 
        if not self.exists():
 
            raise Exception("Module error: Can't replace attributes for an entry. Entry does not exist.")
 

	
 
        attribute_list = self.attributes.keys()
 

	
 
        current_attributes = self.connection.search_s(self.dn, ldap.SCOPE_BASE, attrlist=attribute_list)[0][1]
 

	
 
        modification_list = ldap.modlist.modifyModlist(current_attributes,
 
                                                       self.attributes, ignore_oldexistent=1)
 

	
 
        if not modification_list:
 
            return False
 

	
 
        self.connection.modify_s(self.dn, modification_list)
 

	
 
        return True
 

	
 
    def _update(self):
 
        """
 
        Updates an LDAP entry to have the requested attributes.
 

	
 
        Returns:
 

	
 
        True, if LDAP entry was updated. False if no change was necessary (entry
 
        already has the correct attributes).
 
        """
 

	
 
        self.current_attributes = self.connection.search_s(self.dn, ldap.SCOPE_BASE)[0][1]
 

	
 

	
 
        modification_list = ldap.modlist.modifyModlist(self.current_attributes,
 
                                                       self.attributes)
 

	
 
        if not modification_list:
 
            return False
 

	
 
        self.connection.modify_s(self.dn, modification_list)
 

	
 
        return True
 

	
 
    def exists(self):
 
        """
 
        Checks if the entry already exists in LDAP directory or not.
 

	
 
        Returns:
 
        True, if entry exists. False otherwise.
 
        """
 

	
 
        try:
 
            self.connection.search_s(self.dn, ldap.SCOPE_BASE, attrlist=["dn"])
 
        except ldap.NO_SUCH_OBJECT:
 
            return False
 

	
 
        return True
 

	
 

	
 
def main():
 
    """
 
    Runs the module.
 
    """
 

	
 
    # Construct the module helper for parsing the arguments.
 
    module = AnsibleModule(
 
        argument_spec=dict(
 
            dn=dict(required=True),
 
            state=dict(required=False, choices=["present", "absent", "addattributes", "replaceattributes"], default="present"),
 
            server_uri=dict(required=False, default="ldapi:///"),
 
            bind_dn=dict(required=False, default=None),
 
            bind_password=dict(required=False)
 
            ),
 
        check_invalid_arguments=False
 
        )
 

	
 
    if not ldap_found:
 
        module.fail_json(msg="The Python LDAP module is required")
 

	
 
    # Extract the attributes.
 
    attributes = {}
0 comments (0 inline, 0 general)