Skip to content

Instantly share code, notes, and snippets.

@abjoseph
Last active February 18, 2022 15:13
Show Gist options
  • Save abjoseph/d5d9dba1d6089169aa2174d7fa490981 to your computer and use it in GitHub Desktop.
Save abjoseph/d5d9dba1d6089169aa2174d7fa490981 to your computer and use it in GitHub Desktop.
<powershell>
## Execution Identifier: EXZ-TZ-003
Start-Transcript -Path "C:\ADJoin-Script-Execution.log" -Append -Force
# Script parameters
[string]$ADJoinCred = "${AD_Creds_Secret_Name}"
[string]$DnsIPs = "${AD_DNS_IPs}"
class Logger {
#----------------------------------------------
[string] hidden $cwlGroup
[string] hidden $cwlStream
[string] hidden $sequenceToken
#----------------------------------------------
# Log Initialization
#----------------------------------------------
Logger([string] $Action) {
$this.cwlGroup = "/ps/boot/configuration/"
$this.cwlStream = "{0}/{1}/{2}" -f $env:COMPUTERNAME, $Action,
(Get-Date -UFormat "%Y-%m-%d_%H.%M.%S")
$this.sequenceToken = ""
#------------------------------------------
if ( !(Get-CWLLogGroup -LogGroupNamePrefix $this.cwlGroup) ) {
New-CWLLogGroup -LogGroupName $this.cwlGroup
Write-CWLRetentionPolicy -LogGroupName $this.cwlGroup -RetentionInDays 3
}
if ( !(Get-CWLLogStream -LogGroupName $this.cwlGroup -LogStreamNamePrefix $this.cwlStream) ) {
New-CWLLogStream -LogGroupName $this.cwlGroup -LogStreamName $this.cwlStream
}
}
#----------------------------------------
[void] WriteLine([string] $msg) {
$logEntry = New-Object -TypeName "Amazon.CloudWatchLogs.Model.InputLogEvent"
#-----------------------------------------------------------
$logEntry.Message = $msg
$logEntry.Timestamp = (Get-Date).ToUniversalTime()
if ("" -eq $this.sequenceToken) {
# First write into empty log...
$this.sequenceToken = Write-CWLLogEvent -LogGroupName $this.cwlGroup `
-LogStreamName $this.cwlStream `
-LogEvent $logEntry
}
else {
# Subsequent write into the log...
$this.sequenceToken = Write-CWLLogEvent -LogGroupName $this.cwlGroup `
-LogStreamName $this.cwlStream `
-SequenceToken $this.sequenceToken `
-LogEvent $logEntry
}
}
}
[Logger]$log = [Logger]::new("UserData")
$log.WriteLine("------------------------------")
$log.WriteLine("Log Started - V4.0")
$RunUser = $env:username
$log.WriteLine("PowerShell session user: $RunUser")
$log.WriteLine("Loading Secret <" + $ADJoinCred + ">")
Import-Module AWSPowerShell
try { $SecretObj = (Get-SECSecretValue -SecretId $ADJoinCred) }
catch {
$log.WriteLine("Could not load secret <" + $ADJoinCred + "> - terminating execution")
return
}
[PSCustomObject]$Secret = ($SecretObj.SecretString | ConvertFrom-Json)
$log.WriteLine("Domain (from Secret): <" + $Secret.Domain + ">")
#Configure Hostname
$log.WriteLine("Retrieving new Hostname via Instance Metadata Service (IMDSv2)")
$token = Invoke-RestMethod -Headers @{"X-aws-ec2-metadata-token-ttl-seconds" = "21600" } -Method PUT –Uri http://169.254.169.254/latest/api/token
$instanceId = ((Invoke-WebRequest -Headers @{"X-aws-ec2-metadata-token" = $token } -Uri http://169.254.169.254/latest/meta-data/instance-id -UseBasicParsing).Content)
$newhostname = ((Get-EC2Instance -InstanceID $instanceId).Instances | Select-Object -First 1 | Select-Object -ExpandProperty tags | Where-Object -Property Key -eq Hostname).value
#Configure Network Interface to use Domain DNS Server IPs
$log.WriteLine("Setting Domain DNS Servers: `"$DnsIPs`"")
$primaryNICName = Get-NetAdapter -Name * -Physical | Where-Object InterfaceDescription -like "Amazon Elastic*" | Select-Object -ExpandProperty Name
Set-DnsClientServerAddress $primaryNICName -ServerAddresses $DnsIPs
# 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 ($null -eq $RSAT) {
$log.WriteLine("<RSAT-AD-PowerShell> feature not found - terminating script")
return
}
$log.WriteLine("Terminating script - ")
return
}
# Performing Domain Join
$log.WriteLine("Domain Join required")
$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 -NewName $newhostname -Restart -Force
$log.WriteLine("Requesting restart...")
#------------------------------------------------------------------------------
</powershell>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment