This post is written by Alex Zarenin, Senior AWS Solution Architect, Microsoft Tech.

1.   Introduction

For most companies, a move of Microsoft workloads to AWS starts with “lift and shift” where existing workloads are moved from the on-premises data centers to the cloud. These workloads may include WEB and API farms, and a fleet of processing nodes, which typically depend on AD Domain membership for access to shared resources, such as file shares and SQL Server databases.

When the farms and set of processing nodes are static, which is typical for on-premises deployments, managing domain membership is simple – new instances join the AD Domain and stay there. When some machines are periodically recycled, respective AD computer accounts are disabled or deleted, and new accounts are added when new machines are added to the domain. However, these changes are slow and can be easily managed.

When these workloads are moved to the cloud, it is natural to set up WEB and API farms as scalability groups to allow for scaling up and scaling down membership to optimize cost while meeting the performance requirements. Similarly, processing nodes could be combined into scalability groups or created on-demand as a set of Spot Instances.

In either case, the fleet becomes very dynamic, and can expand and shrink multiple times to match the load or in response to some events, which makes manual management of AD Domain membership impractical. This scenario requires automated solution for managing domain membership.

2.   Challenges

This automated solution to manage domain membership of dynamic fleet of Amazon EC2 instances should provide for:

  • Seamless AD Domain joining when the new instances join the fleet and it should work both for Managed and native ADs;
  • Automatic unjoining from the AD Domain and removal from AD the respective computer account when the instance is stopped or terminated;
  • Following the best practices for protecting sensitive information – the identity of the account that is used for joining domain or removing computer account from the domain.
  • Extensive logging to facilitate troubleshooting if something does not work as expected.

3.   Solution overview

Joining an AD domain, whether native or managed, could be achieved by placing a PowerShell script that performs domain joining into the User Data section of the EC2 instance launch configuration.

It is much more difficult to implement domain unjoining and deleting computer account from AD upon instance termination as Windows does not support On-Shutdown trigger in the Task Scheduler. However, it is possible to define On-Shutdown script using the local Group Policy.

If defined, the On-Shutdown script runs on EVERY shutdown. However, joining a domain REQUIRES reboot of the machine, so On-Shutdown policy cannot be enabled on the first invocation of the User Data script as it will be removed from the domain by the On-Shutdown script right when it joins the domain. Thus, the User Data script must have some logic to define whether it is the first invocation upon instance launch, or the subsequent one following the domain join reboot. The On-Shutdown policy should be enabled only on the second start-up. This also necessitates to define the User Data script as “persistent” by specifying <persist>true</persist> in the User Data section of the launch configuration.

Both domain join and domain unjoin scripts require security context that allows to perform these operations on the domain, which is usually achieved by providing credentials for a user account with corresponding rights. In the proposed implementation, both scripts obtain account credentials from the AWS Secrets Manager under protection of security policies and roles – no credentials are stored in the scripts.

Both scripts generate detailed log of their operation stored locally on the machine.

In this post, I demonstrate a solution based upon PowerShell script that is scheduled to perform Active Directory domain joining on the instance start-up through the EC2 launch User Data script. I also show removal from the domain with the deletion of respective computer accounts from the domain upon instance shutdown using the script installed in the On-Shutdown policy.

User Data script overall logic:

  1. Initialize Logging
  2. Initialize On-Shutdown Policy
  3. Read fields UserID, Password, and Domain from prod/AD secret
  4. Verify machine’s domain membership
  5. If machine is already a member of the domain, then
    1. Enable On-Shutdown Policy
    2. Install RSAT for AD PowerShell
  6. Otherwise
    1. Create credentials from the secret
    2. Initiate domain join
    3. Request machine restart

On-Shutdown script overall logic:

  1. Initialize Logging
  2. Check cntrl variable; If cntrl variable is not set to value “run”, exit script
  3. Check whether machine is a member of the domain; if not, exit script
  4. Check if the RSAT for AD PowerShell installed; if not installed, exit the script
  5. Read fields UserID, Password, and Domain from prod/AD secret
  6. Create credentials from the secret
  7. Identify domain controller
  8. Remove machine from the domain
  9. Delete machine account from domain controller

Simplified Flow chart of User Data and On-Shutdown Scripts

Now that we have reviewed the overall logic of the scripts, we may examine components of each script in more details.

4.   Routines common to both User Data and On-Shutdown scripts

4.1. Processing configuration variables and parameters

User Data script does not accept parameters and is being executed exactly as being provided in the User Data section of the launch configuration. However, at the beginning of the script two variables are specified that could be easily changed:

[string]$SecretAD  = "prod/AD"

[string]$LogPath   = "C:\ProgramData\Amazon\CustomLaunch"

The first one defines the name of the secret in the Secrets Manager that contains UserID, Password, and Domain. The second variable defines the name of the folder where the log file will be stored.

The On-Shutdown Group Policy invokes corresponding script with a parameter, which is stored in the registry as part of the policy setup. Thus, the first line of the On-Shutdown script defines the variable for this parameter:

param([string]$cntrl = "NotSet")

The following two lines in the On-Shutdown script are the same as in the User Data script; actually, they are generated from the corresponding variables in the User Data script.

4.2. The Logger class

Both scripts use the same Logger class to manage logging:

class Logger

    {

    [string] hidden  $logFileName

    Logger([string] $Path, [string] $LogName)

        {

        if(!(Test-Path -Path $Path -pathType container))

            { $dummy = New-Item -ItemType directory -Path $Path }

        $this.logFileName = [System.IO.Path]::Combine($Path, ($LogName + ".log"))

        }

    [void] WriteLine([string] $msg)

        {

        [string] $logLine = (Get-Date -Format 'hh:mm:ss')

         if ($msg) { Out-File -LiteralPath $this.logFileName -Append -InputObject ($logLine + " " + $msg) }

        # Msg is null - creating new file

        else { Out-File -LiteralPath $this.logFileName -InputObject ($logLine + " Log created")     }

        }

    }

Constructor of the class verifies/creates required folder structure and generates log file name to be used by subsequent calls to WriteLine([string] $msg) method. This method outputs provided message as a separate line in the log, prefixed with the timestamp. The following code example creates a Logger instance and writes a message to the log:

[Logger]$log = [Logger]::new($LogPath, "ADMgmt")

$log.WriteLine("Log Started")

5.   The User Data script

The following are the major components of the User Data script.

5.1. Initializing the On-Shutdown policy

The SDManager class wraps functionality necessary to create On-Shutdown policy. The policy requires certain registry entries as well as a script that will be executed when policy is invoked. This script must be placed in a well-defined folder on the file system.

The SDManager constructor performs the following task:

  • Verifies that the folder C:\Windows\System32\GroupPolicy\Machine\Scripts\Shutdown exists and, if necessary, creates it;
  • Updates On-Shutdown script stored as an array in SDManager with the parameters provided to the constructor, and then saves adjusted script in the proper location;
  • Creates all registry entries required for On-Shutdown policy;
  • Sets the parameter that will be passed to the On-Shutdown script by the policy to a value that would preclude On-Shutdown script from removing machine from the domain.

SDManager exposes two member functions, EnableUnJoin() and DisableUnJoin(), which update parameter passed to On-Shutdown script to enable or disable removing machine from the domain, respectively.

5.2. Reading the “secret”

Using the value of configuration variable $SecretAD, the following code example retrieves the secret value from AWS Secrets Manager and creates PowerShell credential to be used for the operations on the domain. The Domain value from the secret is also used to verify that machine is a member of required domain.

Import-Module AWSPowerShell

try { $SecretObj = (Get-SECSecretValue -SecretId $SecretAD) }

catch

    {

    $log.WriteLine("Could not load secret <" + $SecretAD + "> - terminating execution")

    return

    }

[PSCustomObject]$Secret = ($SecretObj.SecretString  | ConvertFrom-Json)

$log.WriteLine("Domain (from Secret): <" + $Secret.Domain + ">")

To get the secret from AWS Secrets Manager, you must use an AWS-specific cmdlet. To make it available, you must import the AWSPowerShell module.

5.3. Checking for domain membership and enabling On-Shutdown policy

To check for domain membership, we use WMI Win32_ComputerObject. While performing check for domain membership, we also validate that if the machine is a member of the domain, it is the domain specified in the secret.

If machine is already a member of the correct domain, the script proceeds with installing RSAT for AD PowerShell, which is required for the On-Shutdown script. It also enables the On-Shutdown script. The following code example achieves this:

$compSys = Get-WmiObject -Class Win32_ComputerSystem

if ( ($compSys.PartOfDomain) -and ($compSys.Domain -eq $Secret.Domain))

    {

    $log.WriteLine("Already member of: <" + $compSys.Domain + "> - Verifying RSAT Status")

    $RSAT = (Get-WindowsFeature RSAT-AD-PowerShell)

    if ($RSAT -eq $null)

        {

        $log.WriteLine("<RSAT-AD-PowerShell> feature not found - terminating script")

        return

        }

    $log.WriteLine("Enable OnShutdown task to un-join Domain")

    $sdm.EnableUnJoin()

    if ( (-Not $RSAT.Installed) -and ($RSAT.InstallState -eq "Available") )

        {

        $log.WriteLine("Installing <RSAT-AD-PowerShell> feature")

        Install-WindowsFeature RSAT-AD-PowerShell

        }

    $log.WriteLine("Terminating script - ")

    return

    }

5.4. Joining Domain

If a machine is not member of the domain or member of the wrong domain, the script creates credentials from the Secret and requests domain joining with subsequent restart of the machine. The following code example performs all these tasks:

$log.WriteLine("Domain Join required")

$log.WriteLine("Disable OnShutdown task to avoid reboot loop")

$sdm.DisableUnJoin()

$password   = $Secret.Password | ConvertTo-SecureString -asPlainText -Force

$username   = $Secret.UserID + "@" + $Secret.Domain

$credential = New-Object System.Management.Automation.PSCredential($username,$password)

$log.WriteLine("Attempting to join domain <" + $Secret.Domain + ">")

Add-Computer -DomainName $Secret.Domain -Credential $credential -Restart -Force

$log.WriteLine("Requesting restart...")

 

6.   The On-Shutdown script

Many components of the On-Shutdown script, such as logging, working with the AWS Secrets Manager, and validating domain membership are either the same or very similar to respective components of the User Data script.

One interesting difference is that the On-Shutdown script accepts parameter from the respective policy; the value of this parameter is set by EnableUnJoin() and DisableUnJoin() functions in the User Data script to control whether domain un-join will happen on a particular reboot – something that we have discussed earlier. Thus, you have the following code example at the beginning of On-Shutdown script:

if ($cntrl -ne "run")

      {

      $log.WriteLine("Script param <" + $cntrl + "> not set to <run> - script terminated")

      return

      }

So, by setting the On-Shutdown policy parameter (a value in registry) to something other than “run” we can stop On-Shutdown script from executing – this is exactly what function DisableUnJoin() does. Similarly, the function EnableUnJoin() sets the value of this parameter to “run” thus allowing the On-Shutdown script to continue execution when invoked.

Another interesting problem with this script is how to implement removing a machine from the domain and deleting respective computer account from the Active Directory. If the script first removes machine from the domain, then it cannot find domain controller to delete computer account.

Alternatively, if the script first deletes computer account, and then tries to remove computer account by changing domain to a workgroup, this change would fail. The following code example represents how this issue was resolved in the script:

import-module ActiveDirectory

$DCHostName = (Get-ADDomainController -Discover).HostName

$log.WriteLine("Using Account <" + $username + ">")

$log.WriteLine("Using Domain Controller <" + $DCHostName + ">")

Remove-Computer -WorkgroupName "WORKGROUP" -UnjoinDomainCredential $credential -Force -Confirm:$false

Remove-ADComputer -Identity $MachineName -Credential $credential -Server "$DCHostName" -Confirm:$false

Before removing machine from the domain, the script obtains and stores in a local variable the name of one of the domain controllers. Then computer is switched from domain to the workgroup. As the last step, the respective computer account is being deleted from the AD using the host name of the domain controller obtained earlier.

7.   Managing Script Credentials

Both User Data and On-Shutdown scripts obtain the domain name and user credentials to add or remove computers from the domain from AWS Secrets Manager secret with the predefined name  prod/AD. This predefined name can be changed in the script.

Details on how to create a secret are available in AWS documentation. This secret should be defined as Other type of secrets and contain at least the following fields:

  • UserID
  • Password
  • Domain

Fill in the fields and choose Next. As illustrated on the following screenshot:

Screenshot Store a new secret. UserID, Password, Domain

Give the new secret the name prod/AD (this name is referred to in the script) and capture the secret’s ARN. The latter is required for creating a policy that allows access to this secret.

Screenshot of Secret Details and Secret Name

8.   Creating AWS Policy and Role to access the Credential Secret

8.1. Creating IAM Policy

The next step is to use IAM to create a policy that would allow access to the secret; the policy  statement will appear as following:

{

    "Version": "2012-10-17",

    "Statement": [

        {

            "Sid": "VisualEditor0",

            "Effect": "Allow",

            "Action": "secretsmanager:GetSecretValue",

            "Resource": "arn:aws:secretsmanager:us-east-1:NNNNNNNN7225:secret:prod/AD-??????"

        }

    ]

}

Below is the AWS console screenshot with the policy statement filled in:

Screenshot with policy statement filled in

The resource in the policy is identified with the “wildcard” characters for the 6 random characters at the end of the ARN, which may change when the Secret is updated. Configuring policy with the wildcard allows to extend rights to ALL versions of the secret, which would allow for changing credential information without changing respective policy.

Screenshot of review policy. Name AdminReadDomainCreds

Let’s name this policy AdminReadDomainCreds so that we may refer to it when creating an IAM Role.

 

8.2. Creating IAM Role

Now that we have defined AdminReadDomainCreds policy, we may create a role AdminDomainJoiner that would refer to this policy. On the Permission tab of the role creation dialog we should attach standard SSM policy for EC2, AmazonEC2RoleforSSM, together with the just created custom policy AdminReadDomainCreds.

The Permission tab of the role creation dialog with the respective roles attached is shown in the following screenshot:

Screenshot of permission tab with roles

This role should include our new policy, AdminReadDomainCreds, in addition to standard SSM policy for EC2.

9.   Launching the Instance

Now, you’re ready to launch the instance or create the launch configuration. When configuring the instance for launch, it’s important to assign the instance to the role AdminDomainJoiner, which you just created:

Screenshot of Configure Instance Details. IAM role as AdminDomainJoiner

In the Advanced Details section of the configuration screen, paste the script into the User Data field:

If you named your secret differently than the name prod/AD that I used, modify the script parameters SecretAD to use the name of your secret.

10.   Conclusion

That’s it! When you launch this instance, it will automatically join the domain. Upon Stop or Termination, the instance will remove itself from the domain.

 

For your convenience we provide the full text of the User Data script:

<powershell>
#------------------------------------------------------------------------------
# Script parameters
#------------------------------------------------------------------------------
[string]$SecretAD = "prod/AD"
[string]$LogPath = "C:\ProgramData\Amazon\CustomLaunch"
#------------------------------------------------------------------------------
#region Logger class
#----------------------------------------------
class Logger
{
[string] hidden $logFileName
#----------------------------------------
Logger([string] $Path, [string] $LogName)
{
if(!(Test-Path -Path $Path -pathType container))
{ $dummy = New-Item -ItemType directory -Path $Path }
$this.logFileName = [System.IO.Path]::Combine($Path, ($LogName + ".log"))
}
#----------------------------------------
[void] WriteLine([string] $msg)
{
[string] $logLine = (Get-Date -Format 'hh:mm:ss')
if ($msg) { Out-File -LiteralPath $this.logFileName -Append -InputObject ($logLine + " " + $msg) }
# Msg is null - creating new file
else { Out-File -LiteralPath $this.logFileName -InputObject ($logLine + " Log created") }
}
}
#----------------------------------------------
#endregion
#------------------------------------------------------------------------------
# Create Logger
#------------------------------------------------------------------------------
[Logger]$log = [Logger]::new($LogPath, "ADMgmt")
$log.WriteLine("--------------------------------------------------------------------")
$log.WriteLine("Log Started")
#------------------------------------------------------------------------------

#------------------------------------------------------------------------------
#region SDManager class
#----------------------------------------------
class SDManager
{
#-------------------------------------------------------------------
[string] hidden $ScriptName = "Shutdown-UnJoin.ps1"
[string] hidden $GPScrShd_0_0 = "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Group Policy\Scripts\Shutdown\0\0"
[string] hidden $GPMScrShd_0_0 = "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Group Policy\State\Machine\Scripts\Shutdown\0\0"
#-------------------------------------------------------------------
SDManager([string]$LogDirPath, [string]$SecretName)
{
[string] $GPRootPath = "C:\Windows\System32\GroupPolicy"
[string] $GPMcnPath = "C:\Windows\System32\GroupPolicy\Machine"
[string] $GPScrPath = "C:\Windows\System32\GroupPolicy\Machine\Scripts"
[string] $GPSShdPath = "C:\Windows\System32\GroupPolicy\Machine\Scripts\Shutdown"
[string] $ScriptFile = [System.IO.Path]::Combine($GPSShdPath, $this.ScriptName)
[string] $SecretLine = '[string]$SecretAD = "' + $SecretName + '"'
[string] $PathLine = '[string]$LogPath = "' + $LogDirPath + '"'
#----------------------------------------------------------------
#region Shutdown script (scheduled through Local Policy)
$ScriptBody =
@(
'param([string]$cntrl = "NotSet")',
$SecretLine,
$PathLine,
'[string]$MachineName = $env:COMPUTERNAME',
'class Logger ',
' {',
' [string] hidden $logFileName',
' Logger([string] $Path, [string] $LogName)',
' {',
' if(!(Test-Path -Path $Path -pathType container))',
' { $dummy = New-Item -ItemType directory -Path $Path }',
' $this.logFileName = [System.IO.Path]::Combine($Path, ($LogName + ".log"))',
' }',
' [void] WriteLine([string] $msg)',
' {',
' [string] $logLine = (Get-Date -Format "hh:mm:ss")',
' if ($msg) { Out-File -LiteralPath $this.logFileName -Append -InputObject ($logLine + " " + $msg) }',
' else { Out-File -LiteralPath $this.logFileName -InputObject ($logLine + " Log created") }',
' }',
' }',
'[Logger]$log = [Logger]::new($LogPath, "ADMgmt")',
'$log.WriteLine("-----------------------------------------")',
'$log.WriteLine("Log Started")',
'if ($cntrl -ne "run") ',
' { ',
' $log.WriteLine("Script param <" + $cntrl + "> not set to <run> - script terminated") ',
' return',
' }',
'$compSys = Get-WmiObject -Class Win32_ComputerSystem',
'if ( -Not ($compSys.PartOfDomain))',
' {',
' $log.WriteLine("Not member of a domain - terminating script")',
' return',
' }',
'$RSAT = (Get-WindowsFeature RSAT-AD-PowerShell)',
'if ( $RSAT -eq $null -or (-Not $RSAT.Installed) )',
' {',
' $log.WriteLine("<RSAT-AD-PowerShell> feature not found - terminating script")',
' return',
' }',
'$log.WriteLine("Removing machine <" +$MachineName + "> from Domain <" + $compSys.Domain + ">")',
'$log.WriteLine("Reading Secret <" + $SecretAD + ">")',
'Import-Module AWSPowerShell',
'try { $SecretObj = (Get-SECSecretValue -SecretId $SecretAD) }',
'catch ',
' { ',
' $log.WriteLine("Could not load secret <" + $SecretAD + "> - terminating execution")',
' return ',
' }',
'[PSCustomObject]$Secret = ($SecretObj.SecretString | ConvertFrom-Json)',
'$password = $Secret.Password | ConvertTo-SecureString -asPlainText -Force',
'$username = $Secret.UserID + "@" + $Secret.Domain',
'$credential = New-Object System.Management.Automation.PSCredential($username,$password)',
'import-module ActiveDirectory',
'$DCHostName = (Get-ADDomainController -Discover).HostName',
'$log.WriteLine("Using Account <" + $username + ">")',
'$log.WriteLine("Using Domain Controller <" + $DCHostName + ">")',
'Remove-Computer -WorkgroupName "WORKGROUP" -UnjoinDomainCredential $credential -Force -Confirm:$false ',
'Remove-ADComputer -Identity $MachineName -Credential $credential -Server "$DCHostName" -Confirm:$false ',
'$log.WriteLine("Machine <" +$MachineName + "> removed from Domain <" + $compSys.Domain + ">")'
)
#endregion
#----------------------------------------------------------------
if(!(Test-Path -Path $GPRootPath -pathType container))
{ New-Item -ItemType directory -Path $GPRootPath }
if(!(Test-Path -Path $GPMcnPath -pathType container))
{ New-Item -ItemType directory -Path $GPMcnPath }
if(!(Test-Path -Path $GPScrPath -pathType container))
{ New-Item -ItemType directory -Path $GPScrPath }
if(!(Test-Path -Path $GPSShdPath -pathType container))
{ New-Item -ItemType directory -Path $GPSShdPath }
#----------------------------------------
Set-Content $ScriptFile -Value $ScriptBody
#----------------------------------------
$RegistryScript =
@(
'Windows Registry Editor Version 5.00',
'[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Group Policy\Scripts]',
'[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Group Policy\Scripts\Shutdown]',
'[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Group Policy\Scripts\Shutdown\0]',
'"GPO-ID"="LocalGPO"',
'"SOM-ID"="Local"',
'"FileSysPath"="C:\\Windows\\System32\\GroupPolicy\\Machine"',
'"DisplayName"="Local Group Policy"',
'"GPOName"="Local Group Policy"',
'"PSScriptOrder"=dword:00000001',
'[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Group Policy\Scripts\Shutdown\0\0]',
'"Script"="Shutdown-UnJoin.ps1"',
'"Parameters"=""',
'"IsPowershell"=dword:00000001',
'"ExecTime"=hex(b):00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00',
'[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Group Policy\Scripts\Startup]',
'[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Group Policy\State\Machine\Scripts]',
'[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Group Policy\State\Machine\Scripts\Shutdown]',
'[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Group Policy\State\Machine\Scripts\Shutdown\0]',
'"GPO-ID"="LocalGPO"',
'"SOM-ID"="Local"',
'"FileSysPath"="C:\\Windows\\System32\\GroupPolicy\\Machine"',
'"DisplayName"="Local Group Policy"',
'"GPOName"="Local Group Policy"',
'"PSScriptOrder"=dword:00000001',
'[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Group Policy\State\Machine\Scripts\Shutdown\0\0]',
'"Script"="Shutdown-UnJoin.ps1"',
'"Parameters"=""',
'"ExecTime"=hex(b):00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00',
'[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Group Policy\State\Machine\Scripts\Startup]'
)
[string] $RegistryFile = [System.IO.Path]::Combine($LogDirPath, "OnShutdown.reg")
Set-Content $RegistryFile -Value $RegistryScript
&regedit.exe /S "$RegistryFile"
}
#----------------------------------------
[void] DisableUnJoin()
{
Set-ItemProperty -Path $this.GPScrShd_0_0 -Name "Parameters" -Value "ignore"
Set-ItemProperty -Path $this.GPMScrShd_0_0 -Name "Parameters" -Value "ignore"
&gpupdate /Target:computer /Wait:0
}
#----------------------------------------
[void] EnableUnJoin()
{
Set-ItemProperty -Path $this.GPScrShd_0_0 -Name "Parameters" -Value "run"
Set-ItemProperty -Path $this.GPMScrShd_0_0 -Name "Parameters" -Value "run"
&gpupdate /Target:computer /Wait:0
}
}
#----------------------------------------------
#endregion
#------------------------------------------------------------------------------
# Create ShutDown Manager
#------------------------------------------------------------------------------
[SDManager]$sdm = [SDManager]::new($LogPath, $SecretAD, $LogPath)
#------------------------------------------------------------------------------
$log.WriteLine("Loading Secret <" + $SecretAD + ">")
#------------------------------------------------------------------------------
Import-Module AWSPowerShell
try { $SecretObj = (Get-SECSecretValue -SecretId $SecretAD) }
catch
{
$log.WriteLine("Could not load secret <" + $SecretAD + "> - terminating execution")
return
}
[PSCustomObject]$Secret = ($SecretObj.SecretString | ConvertFrom-Json)
$log.WriteLine("Domain (from Secret): <" + $Secret.Domain + ">")
#------------------------------------------------------------------------------
# Verify domain membership
#------------------------------------------------------------------------------
$compSys = Get-WmiObject -Class Win32_ComputerSystem
#------------------------------------------------------------------------------
if ( ($compSys.PartOfDomain) -and ($compSys.Domain -eq $Secret.Domain))
{
$log.WriteLine("Already member of: <" + $compSys.Domain + "> - Verifying RSAT Status")
#------------------------------------------------------------------------------
$RSAT = (Get-WindowsFeature RSAT-AD-PowerShell)
if ($RSAT -eq $null)
{
$log.WriteLine("<RSAT-AD-PowerShell> feature not found - terminating script")
return
}
#--------------------------------------------------------------------------
$log.WriteLine("Enable OnShutdown task to un-join Domain")
$sdm.EnableUnJoin()
#------------------------------------------------------------------------------
if ( (-Not $RSAT.Installed) -and ($RSAT.InstallState -eq "Available") )
{
$log.WriteLine("Installing <RSAT-AD-PowerShell> feature")
Install-WindowsFeature RSAT-AD-PowerShell
}
#--------------------------------------------------------------------------
$log.WriteLine("Terminating script - ")
return
}
#------------------------------------------------------------------------------
# Performing Domain Join
#------------------------------------------------------------------------------
$log.WriteLine("Domain Join required")
#------------------------------------------------------------------------------
$log.WriteLine("Disable OnShutdown task to avoid reboot loop")
$sdm.DisableUnJoin()
$password = $Secret.Password | ConvertTo-SecureString -asPlainText -Force
$username = $Secret.UserID + "@" + $Secret.Domain
$credential = New-Object System.Management.Automation.PSCredential($username,$password)
#------------------------------------------------------------------------------
$log.WriteLine("Attempting to join domain <" + $Secret.Domain + ">")
#------------------------------------------------------------------------------
Add-Computer -DomainName $Secret.Domain -Credential $credential -Restart -Force
#------------------------------------------------------------------------------
$log.WriteLine("Requesting restart...")
#------------------------------------------------------------------------------
</powershell>
<persist>true</persist>

 

from AWS Compute Blog