Changeset - fa1452af4f5d
[Not reviewed]
0 1 0
Branko Majic (branko) - 11 years ago 2015-03-08 11:20:11
branko@majic.rs
MAR-1: Added handling of attribute adding/removal/replacement for an existing LDAP entry.
1 file changed with 102 insertions and 8 deletions:
0 comments (0 inline, 0 general)
roles/ldap_server/library/ldap_entry.py
Show inline comments
 
@@ -18,16 +18,19 @@ options:
 
    description:
 
      - Distinguished name of the entry.
 
    required: true
 
    default: ""
 
  state:
 
    description:
 
      - LDAP entry state.
 
      - LDAP entry state. State C(present) requires that all entry attributes
 
        are listed. If you wish to add some attributes, with specific values, to
 
        existing entry, use state C(addattributes). If you wish to replace
 
        existing values for an attribute, use C(replaceattributes).
 
    required: true
 
    default: "present"
 
    choices: [ "present", "absent" ]
 
    choices: [ "present", "absent", "addattributes", "replaceattributes" ]
 
  server_uri:
 
    description:
 
      - LDAP connection URI specifying what server to connect to.
 
    required: false
 
    default: "ldapi:///"
 
  bind_dn:
 
@@ -47,13 +50,15 @@ options:
 
      - All remaining attributes are considered to be attributes for an LDAP
 
        entry. LDAP schema constraints should be kept in mind (i.e. one
 
        structural objectClass etc). Attributes can be passed in as a simple
 
        string (for one value of an attribute), for storing multiple values for
 
        same attribute. If providing a base64-encoded value, prefix it with
 
        C(base64:) (this is useful for I(usercertificate;binary) or
 
        I(displayName) attributes).
 
        I(displayName) attributes). In order to remove an attribute, set its
 
        value to an empty string (C("")), and set the state to
 
        C(replaceattributes).
 
    required: false
 
    default: ""
 
"""
 

	
 
EXAMPLES = """
 
# Create sub-trees for storing user and group information.
 
@@ -75,12 +80,30 @@ ldap_entry:
 
  givenName: John
 
  displayName: base64:Sm9obiBEb2U=
 
  initials: JD
 
  mail: john.doe@example.com
 
  mobile: +1 11 111 111 11
 
  usercertificate;binary: base64:MIIC...lotsofcharacters...+/A==
 

	
 
# Add attribute to an entry.
 
ldap_entry:
 
  dn: uid=john,ou=people,dc=example,dc=com
 
  state: addattributes
 
  mail: john.doe@example.com
 

	
 
# Make sure the configuration database has specific logging level enabled.
 
ldap_entry:
 
  dn: cn=config
 
  state: replaceattributes
 
  olcLogLevel: 256
 

	
 
# Remove attribute from an entry.
 
ldap_entry:
 
  dn: uid=john,ou=people,dc=example,dc=com
 
  state: replaceattributes
 
  uid: ""
 
"""
 

	
 

	
 
# Try to load the Python LDAP module.
 
try:
 
    import ldap
 
@@ -88,12 +111,14 @@ try:
 
    import ldap.modlist
 
except ImportError:
 
    ldap_found = False
 
else:
 
    ldap_found = True
 

	
 
from copy import deepcopy
 

	
 

	
 
def get_ldap_connection(uri, bind_dn=None, bind_password=""):
 
    """
 
    Connects and binds to an LDAP server.
 

	
 
    Arguments:
 
@@ -184,24 +209,86 @@ class LDAPEntry(object):
 
            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)
 

	
 
        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]))
 
            else:
 
                new_attributes[attribute] = values
 

	
 
        modification_list = ldap.modlist.modifyModlist(current_attributes,
 
                                                       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]
 
        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
 
@@ -232,13 +319,13 @@ def main():
 
    """
 

	
 
    # Construct the module helper for parsing the arguments.
 
    module = AnsibleModule(
 
        argument_spec=dict(
 
            dn=dict(required=True),
 
            state=dict(required=False, choices=["present", "absent"], default="present"),
 
            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
 
        )
 
@@ -247,33 +334,40 @@ def main():
 
        module.fail_json(msg="The Python LDAP module is required")
 

	
 
    # Extract the attributes.
 
    attributes = {}
 
    for name, value in module.params.iteritems():
 
        if name not in module.argument_spec:
 
            if isinstance(value, basestring):
 
            if value == "":
 
                pass
 
            elif isinstance(value, basestring):
 
                value = [ value.encode("utf-8") ]
 
            elif isinstance(value, list):
 
                value = [ i.encode("utf-8") for i in value ] 
 
            attributes[name] = value
 

	
 
    try:
 
        connection = get_ldap_connection(module.params["server_uri"],
 
                                         module.params["bind_dn"],
 
                                         module.params["bind_password"])
 
    except ldap.LDAPError as e:
 
        module.fail_json(msg="LDAP error: %s" % str(e))
 
    state = module.params["state"]
 

	
 
    entry = LDAPEntry(module.params["dn"],
 
                      attributes,
 
                      connection)
 

	
 
    # Add/remove entry as requested.
 
    try:
 
        if module.params["state"] == "present":
 
        if state == "present":
 
            changed = entry.add()
 
        elif state == "addattributes":
 
            changed = entry.addattributes()
 
        elif state == "replaceattributes":
 
            changed = entry.replaceattributes()
 
        else:
 
            changed = entry.remove()
 
    except ldap.LDAPError as e:
 
        module.fail_json(msg="LDAP error: %s" % str(e))
 

	
 
    module.exit_json(changed=changed)
0 comments (0 inline, 0 general)