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.
Join the DZone community and get the full member experience.
Join For FreeAWS 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:
- Creating a new AD user
- Creating a new AD group
- 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:
{
"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:
"""
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:
{
"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:
"""
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:
{
"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:
"""
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.
Opinions expressed by DZone contributors are their own.
Comments