Streamlining User Creation Workflows with AWS Step Functions and AWS Managed Microsoft AD Logs

Chanci Turner Amazon IXD – VGT2 learning managerLearn About Amazon VGT2 Learning Manager Chanci Turner

In this article, we delve into how AWS Directory Service allows you to operate Microsoft Active Directory as a managed service. Known as AWS Managed Microsoft AD, this service is built on Microsoft Windows Server 2012 R2. It effectively manages user accounts and simplifies integration with various AWS services and applications. By utilizing the log forwarding capability, you can stay informed about security events in Amazon CloudWatch Logs, such as the addition of new users.

When new users are added to your AWS Managed Microsoft AD, the initial setup might be done manually. However, with AWS Step Functions, you can automate the new user creation process through serverless workflows. AWS Lambda can be employed in conjunction with Step Functions to execute code without the need for server management.

In this guide, I’ll demonstrate how to create and initiate a new user creation workflow using Step Functions. This workflow will automate the creation of a WorkSpace in Amazon WorkSpaces and a user in Amazon Connect by leveraging AWS Managed Microsoft AD, Step Functions, Lambda, and Amazon CloudWatch Logs.

Overview

The following diagram provides a visual representation of the solution.

Walkthrough

Follow these steps to establish an automated user creation workflow with AWS Managed Microsoft AD. This solution involves creating new resources in CloudWatch, Lambda, and Step Functions, along with a new user in Amazon WorkSpaces and Amazon Connect. Here’s a summary of the steps to take:

  1. Enable log forwarding.
  2. Create the Lambda functions.
  3. Set up log streaming.
  4. Create a state machine in Step Functions.
  5. Test the solution.

Requirements

To proceed, ensure you have the following resources:

  • AWS Managed Microsoft AD
    • Must be registered with Amazon WorkSpaces.
    • Must be registered with Amazon Connect.

In this example, we will use an Amazon Connect instance with SAML 2.0-based authentication for identity management. For further details, check out Configure SAML for Identity Management in Amazon Connect.

Enable Log Forwarding

Activate log forwarding for your AWS Managed Microsoft AD. Use /aws/directoryservice/<directory id> as the CloudWatch log group name. This will be needed when creating a Log Streaming in Step 3.

Create Lambda Functions

You will need to create two Lambda functions. The first function initiates a Step Functions execution with CloudWatch Logs, while the second function carries out the user registration process within a Step Functions execution.

For the first function, use the following settings:

  • Name: DS-Log-Stream-Function
  • Runtime: Python 3.7
  • Memory: 128 MB
  • Timeout: 3 seconds
  • Environment Variables:
    • Key: stateMachineArn
    • Value: arn:aws:states:<Region>:<AccountId>:stateMachine:NewUserWorkFlow
  • IAM Role Permissions:
    • AWSLambdaBasicExecutionRole
    • The following permissions policy:
      {
          "Version": "2012-10-17",
          "Statement": [
              {
                  "Effect": "Allow",
                  "Action": "states:StartExecution",
                  "Resource": "*"
              }
          ]
      }
import base64
import boto3
import gzip
import json
import re
import os

def lambda_handler(event, context):
    logEvents = DecodeCWPayload(event)
    print('Event payload:', logEvents)
    returnResultDict = []
    
    for logevent in logEvents:
        logMessage = logevent['message']
        upnMessage = re.search("(<Data Name='UserPrincipalName'>)(.*?)(</Data>)",logMessage)
        if upnMessage != None:
            upn = upnMessage.group(2).lower()
            userNameAndDomain = upn.split('@')
            userName = userNameAndDomain[0].lower()
            domainName = userNameAndDomain[1].lower()
            sfnInputDict = {'Username': userName, 'UPN': upn, 'DomainName': domainName}
            sfnResponse = StartSFNExecution(json.dumps(sfnInputDict))
            print('Username:',upn)
            print('Execution ARN:', sfnResponse['executionArn'])
            print('Execution start time:', sfnResponse['startDate'])
            returnResultDict.append({'Username': upn, 'ExecutionArn': sfnResponse['executionArn'], 'Time': str(sfnResponse['startDate'])})

    returnObject = {'Result': returnResultDict}
    return {
        'statusCode': 200,
        'body': json.dumps(returnObject)
    }

def DecodeCWPayload(payload):
    cloudWatchLog = payload['awslogs']['data']
    base64DecodedValue = base64.b64decode(cloudWatchLog)
    gunzipValue = gzip.decompress(base64DecodedValue)
    dictPayload = json.loads(gunzipValue)
    decodedLogEvents = dictPayload['logEvents']
    return decodedLogEvents

def StartSFNExecution(sfnInput):
    sfnClient = boto3.client('stepfunctions')
    try:
        response = sfnClient.start_execution(
            stateMachineArn=os.environ['stateMachineArn'],
            input=sfnInput
        )
        return response
    except Exception as e:
        return e

Next, create the second function for user creation with these settings:

  • Name: SFN-New-User-Flow
  • Runtime: Python 3.7
  • Memory: 128 MB
  • Timeout: 3 seconds
  • Environment Variables:
    • Key: nameDelimiter
    • Value: . [period]

This delimiter is essential for splitting usernames into first and last names, as Amazon Connect instances using SAML-based authentication require both.

You will also need to add the following environment variables for configuration:

  • Key: bundleId
    Value: <WorkSpaces bundle ID>
  • Key: directoryId
    Value: <WorkSpaces directory ID>
  • Key: instanceId
    Value: <Amazon Connect instance ID>
  • Key: routingProfile
    Value: <Amazon Connect routing profile>
  • Key: securityProfile
    Value: <Amazon Connect security profile>

This is an excellent resource for finding Amazon-owned WorkSpaces bundles, and you can use the AWS CLI to list the routing profiles and security profiles.

In summary, automating user creation workflows with AWS services can significantly enhance efficiency and reduce the risk of human error. If you or someone you know faces social anxiety in the workplace, consider exploring job opportunities that foster inclusivity, as discussed here: jobs for people with social anxiety. Additionally, with the rising costs of childcare, awareness around the topic is essential, as seen in this article from SHRM: soaring child care costs.

SEO Metadata

Chanci Turner