Create Users in Directory Service using LDAP (Python)

0

I have AWS Managed Directory Service. I have also created an Administration Instance to manage this. I have also enabled Client Side LDAPS on the directory after registering a certificate. By logging into the Administration EC2 instance, I am able to create users manually. However, I would like to automate this using LDAP with Python. Can anyone please help? I searched but didn't find anything useful.

質問済み 4ヶ月前410ビュー
2回答
0

Hi,

Thanks for the additional info. I think this is what you are looking for:

  1. Create a lambda function [with python runtime] in the VPC and Subnets where you have deployed the AWS Managed AD or alternatively, another VPC which is peered [it is your networking choice]
  2. We will use the python-ldap package which gives you ultilities to interact with an AD using the ldap/ldaps protocol. So, build a Lambda layer for the python-ldap package Refer this: https://docs.aws.amazon.com/lambda/latest/dg/chapter-layers.html, there are many other videos/articles how to build a lambda layer for your python dependencies
  3. Add that layer to the lambda function
  4. Here is the sample code for the lambda function, this is just for logical idea [not tested], you would need to adapt this accordingly.
import ldap

def lambda_handler(event, context):
    """Creates a user in LDAP.

    Input event expects the following event structure:
    {
        "username": "username_to_create",
        "password": "user_password",
        "givenName": "user_given_name",
        "sn": "user_surname",
        "mail": "user_email",
        "ldap_uri": "ldap://ldap_server_uri",
        "base_dn": "base_distinguished_name",
        "bind_dn": "bind_distinguished_name",
        "bind_password": "bind_password"
    }
    """

    # Extract required parameters from the event
    username = event.get("username")
    password = event.get("password")
    givenName = event.get("givenName")
    sn = event.get("sn")
    mail = event.get("mail")
    ldap_uri = event.get("ldap_uri")
    base_dn = event.get("base_dn")
    bind_dn = event.get("bind_dn")
    bind_password = event.get("bind_password")

    # Validate required parameters
    if not all([username, password, givenName, sn, mail, ldap_uri, base_dn, bind_dn, bind_password]):
        raise ValueError("Missing required parameters in the event")

    try:
        # Connect to LDAP with TLS
        with ldap.initialize(ldap_uri, tls=True)) as connection:
            
            # Optionally specify the CA certificate file path if needed
            # connection.set_option(ldap.OPT_X_TLS_CACERTFILE, "path/to/ca_cert.pem")
            connection.simple_bind_s(bind_dn, bind_password)

            # Construct user DN
            user_dn = f"cn={username},{base_dn}"

            # Create user attributes
            attrs = [
                ("objectclass", ["top", "person", "organizationalPerson", "inetOrgPerson"]),
                ("cn", [username]),
                ("sn", [sn]),
                ("givenName", [givenName]),
                ("mail", [mail]),
                ("userPassword", [password]),
            ]

            # Add the user to LDAP
            connection.add_s(user_dn, attrs)

            return {"statusCode": 200, "message": f"User {username} created successfully"}

    except ldap.LDAPError as e:
        raise Exception(f"Error creating user: {e}")


I hope this is helpful!

Thanks

profile pictureAWS
Rama
回答済み 4ヶ月前
  • Thanks a lot. Really sorry for the delayed response. This task went on hold for sometime due to a few other priority tasks. I am continuing now. However, I am not sure how to get the ldap_uri. I tried using the IP and the name of the EC2 Administration instance created for the Directory Service. However, it didn't work. Unfortunately, there doesn't seem to be good documentation around this. Do you think you can still help, please?

  • Hi, the ldap server uri is generally the Directory DNS name found in Directory service --> Directories as an example it could be like this ldap://corp.example.com . I hope this is helpful.

  • Hello. Do you know if the directory needs some additional or specific configuration? I'm trying to follow your response but i keep getting "Transport endpoint is not connected" error.

    I am using Simple AD for added context Thank you.

0

Hi

From my previous experience working with Active Directories, I used the open LDAP utility which is available in most linux distributions. So, essentially you should be able to use this utility in a bash/python script.

Please refer the below examples, you can adapt the values as per your use-case. There are finer nuances like connectivity, certificates etc. You should be able to find a lot of resources on how to setup open LDAP for your use-case.

Step-1: Create an LDIF File for the user

dn: cn=John Doe,ou=maketing,dc=yourdomain,dc=com
objectclass: inetOrgPerson
cn: John Doe
cn: John Doe
sn: Doe
uid: jdoe
userpassword: <password>
homephone: <phone>
mail: j.doe@yourdomain.com
mail: jdoe@yourdomain.com
ou: Marketing

Step-2: Use the ldapadd command

ldapadd -x -W -D "cn=admin,dc=example,dc=com" -f new_entry.ldif

Step-3: Write a script to execute these lidf files and ldap add commands for a bulk set of users, capture the output of these commands in another file e.g. output.txt

Hope this gives you a direction.

Thanks

profile pictureAWS
Rama
回答済み 4ヶ月前
  • Thank you for your response. Let me provide some more detail. I am using a Windows Server for Administration of Directory Service. I am looking for the detailed steps to set up LDAP access with this. Although I have enabled Client Side LDAPS access, I think there are many more steps. Also, I need to be able to add users programmatically, say from a Python based Lambda without any file or CLI.

ログインしていません。 ログイン 回答を投稿する。

優れた回答とは、質問に明確に答え、建設的なフィードバックを提供し、質問者の専門分野におけるスキルの向上を促すものです。

質問に答えるためのガイドライン

関連するコンテンツ