DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Related

  • Why Use AWS Lambda Layers? Advantages and Considerations
  • How to Configure AWS Glue Job Using Python-Based AWS CDK
  • Alexa Skill With Python
  • Building Scalable Data Lake Using AWS

Trending

  • Building Custom Tools With Model Context Protocol
  • The Human Side of Logs: What Unstructured Data Is Trying to Tell You
  • Build Your First AI Model in Python: A Beginner's Guide (1 of 3)
  • Analyzing Techniques to Provision Access via IDAM Models During Emergency and Disaster Response
  1. DZone
  2. Software Design and Architecture
  3. Cloud Architecture
  4. Managing AWS Managed Microsoft Active Directory Objects With AWS Lambda Functions

Managing AWS Managed Microsoft Active Directory Objects With AWS Lambda Functions

In this tutorial, you will learn to manage AWS Managed Microsoft Active Directory objects with AWS Lambda Functions with code examples.

By 
Avik Bose user avatar
Avik Bose
·
Dec. 17, 24 · Tutorial
Likes (0)
Comment
Save
Tweet
Share
5.9K Views

Join the DZone community and get the full member experience.

Join For Free

AWS Managed Microsoft Active Directory provides the ability to run directory-aware workloads in the AWS Cloud, including Microsoft SharePoint and custom .NET and SQL Server-based applications. AWS Managed Microsoft Active Directory also provides the ability to access AWS resources through Identities stored in on-premise or self-managed Active Directory through Trusts.

AWS Lambda runs code on a high-availability compute infrastructure and performs all of the administration of the compute resources, including server and operating system maintenance, capacity provisioning, automatic scaling, and logging.

Traditionally, provisioning users and objects in AWS Managed Microsoft Active Directory has been done through domain-joined systems leveraging LDAP tools. This would often result in building infrastructure to run these LDAP tools and maintenance of that infrastructure such as installing monthly security updates and updating the LDAP tools. This process adds the overhead of maintaining the underlying infrastructure and associated costs.

In this post, you will learn how to leverage serverless compute such as AWS Lambda functions to manage AWS Managed Microsoft Active Directory objects.

Step 1

Create a new AWS Managed Microsoft Active Directory. If you already have an existing AWS Managed Microsoft Active Directory then skip to Step 2.

  • Navigate to the AWS Directory Service console and select "Set up a directory." Under the available directory types, select AWS Managed Microsoft AD.
  • In the next screen, select your edition and enter the directory information.
  • Select your VPC subnets, select Next to review, and submit the request.

Step 2

In order to use the Directory Service APIs that allow AD object management, you will need to enable the functionality on the directory.

Step 3

Now that you have enabled the feature to manage AWS Managed Microsoft Active Directory users and groups (objects), you can use the AWS CLI/SDK to provision/manage objects stored in your AWS Managed Microsoft Active Directory. In this step, we will see an example of using AWS Lambda to manage AWS Managed Microsoft Active Directory objects.

  • Create a Lambda Function with an execution role that has access to the AWSDirectoryServiceData operations that you want to use.
  • If you are using Python for the Lambda runtime, like in this example, remember to update the boto3 package to the latest version.
  • For this tutorial, I have created a Python 3.12 runtime Lambda function with default settings.
  • For this tutorial, I am:
    1. Creating a new AD user
    2. Creating a new AD group
    3. Adding the user to the group

For a full set of available operations please read their documentation.

  • I have also structured the input in a JSON format to simplify the Lambda invocation, but this is optional, and you can continue to ingest the input from your existing sources such as HR systems/events to trigger the Lambda function and perform operations on your objects stored in your directory.

Sample Code

  • Sample JSON input for creating a new AD user:
JSON
 
{
    "DirectoryId": "d-9067db949e",
    "EmailAddress": "mcandella@tutorial.com",
    "GivenName": "Molly Candella",
    "SAMAccountName": "mcandella",
    "Surname": "Candella"
}


  • Sample Python code to create an AD user in your AWS Managed Microsoft AD through a Lambda function:
Python
 

"""
This is an example Python Lambda function to managed AD objects (users and groups) in AWS Managed Microsoft Active
Directory. For production use cases, please use better error handling, logging and retry mechanisms.
"""


import uuid
import traceback
import boto3


def create_ad_user(ds_client, client_token, directory_id, given_name, email_address, surname, sam_account_name):
    """
     method to create a new Active Directory user
    """
    try:
        response = ds_client.create_user(
            ClientToken=client_token,
            DirectoryId=directory_id,
            EmailAddress=email_address,
            GivenName=given_name,
            SAMAccountName=sam_account_name,
            Surname=surname
        )
        return response

    # broader exceptional handling used for tutorial. Please be specific for your use case
    except Exception as e:
        tb = traceback.format_exc()
        print(tb)
        print("Failed to create user:{0} in directory:{1}".format(sam_account_name, directory_id))

def lambda_handler(event, context):

    """
     main method
    """

    # create a ds-data client/ for production code, use error handling for your client initialization
    ds_data_client = boto3.client('ds-data', region_name='us-east-1')

    # generate the unique client token
    client_token = str(uuid.uuid4())

    # create user/ printing for tutorial,you should ideally log the response for audit and troubleshooting
    print(create_ad_user(ds_data_client, client_token, event["DirectoryId"], event["GivenName"], event["EmailAddress"],
                         event["Surname"], event["SAMAccountName"]))
    return {
        'statusCode': 200
    }


  • Sample JSON input for creating an AD group:
JSON
 
{
    "DirectoryId": "d-9067db949e",
    "GroupScope": "DomainLocal",
    "GroupType": "Distribution",
    "SAMAccountName": "AcctngMail"
}


  • Sample Python code to create an AD group in your AWS Managed Microsoft AD through a Lambda function:
Python
 
"""
This is an example Python Lambda function to managed AD objects (users and groups) in AWS Managed Microsoft Active
Directory. For production use cases, please use better error handling, logging and retry mechanisms.
"""

import uuid
import traceback
import boto3


def create_ad_group(ds_client, client_token, directory_id, sam_account_name, group_type, group_scope):
    """
     method to create a new Active Directory group
    """

    try:
        response = ds_client.create_group(
            ClientToken=client_token,
            DirectoryId=directory_id,
            GroupScope=group_scope,
            GroupType=group_type,
            SAMAccountName=sam_account_name
        )
        return response
    # broader exceptional handling used for tutorial. Please be specific for your use case
    except Exception as e:
        tb = traceback.format_exc()
        print(tb)
        print("Failed to create group:{0} in directory:{1}".format(sam_account_name, directory_id))

        
def lambda_handler(event, context):

    """
     main method
    """

    # create a ds-data client/ for production code, use error handling for your client initialization
    ds_data_client = boto3.client('ds-data', region_name='us-east-1')

    # generate the unique client token
    client_token = str(uuid.uuid4())

    # create group/ printing for tutorial but should be logged for audit
    print(create_ad_group(ds_data_client, client_token, event["DirectoryId"], event["SAMAccountName"],
                          event["GroupType"], event["GroupScope"]))

    return {
        'statusCode': 200
    }


  • Sample JSON input for adding an AD user to an AD group membership:
JSON
 
{
  "DirectoryId": "d-9067db949e",
  "GroupName": "AcctngMail",
  "MemberName": "mcandella",
  "MemberRealm": "tutorial.com"
}


  • Sample Python code to add an AD user to a group in your AWS Managed Microsoft AD through a Lambda function:
Python
 
"""
This is an example Python Lambda function to managed AD objects (users and groups) in AWS Managed Microsoft Active
Directory. For production use cases, please use better error handling, logging and retry mechanisms.
"""

import uuid
import traceback
import boto3


def add_member_to_group(ds_client, client_token, directory_id, group_name, member_name, member_realm):
    """
     method to add an Active Directory user to an Active Directory group
    """
    try:
        response = ds_client.add_group_member(
            ClientToken=client_token,
            DirectoryId=directory_id,
            GroupName=group_name,
            MemberName=member_name,
            MemberRealm=member_realm
        )
        return response
    # broader exceptional handling used for tutorial. Please be specific for your use case
    except Exception as e:
        tb = traceback.format_exc()
        print(tb)
        print("Failed to add user:{0} to AD group:{1} in directory:{2}".format(member_name, group_name, directory_id))


def lambda_handler(event, context):

    """
     main method
    """

    # create a ds-data client/ for production code, use error handling for your client initialization
    ds_data_client = boto3.client('ds-data', region_name='us-east-1')

    # generate the unique client token
    client_token = str(uuid.uuid4())

    # add member to group / printing for tutorial but response should be logged for audit.
    print(add_member_to_group(ds_data_client, client_token, event["DirectoryId"], event["GroupName"],
                              event["MemberName"], event["MemberRealm"]))

    return {
        'statusCode': 200
    }


Conclusion

In this tutorial, you learned how to manage AD objects in your AWS Managed Microsoft Active Directory through a Lambda function. This system can allow you to fully automate your new employee onboarding process by triggering the Lambda functions from your HR systems or your cloud-based Identity Providers (IDP). This can further be used to take actions based on events in your organization such as employee termination, organization changes, etc.

AWS AWS Lambda Directory Object (computer science) Python (language)

Opinions expressed by DZone contributors are their own.

Related

  • Why Use AWS Lambda Layers? Advantages and Considerations
  • How to Configure AWS Glue Job Using Python-Based AWS CDK
  • Alexa Skill With Python
  • Building Scalable Data Lake Using AWS

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!