Files
SGU-CredentialProvider/scripts/Set-LabBrokerDns.ps1
T

82 lines
2.7 KiB
PowerShell

[CmdletBinding()]
param(
[string]$ZoneName = 'lci.lasalle.mx',
[string]$RecordName = 'sgu-auth',
[ipaddress]$IPv4Address = '192.168.50.10',
[ipaddress[]]$ExternalForwarders = @()
)
$ErrorActionPreference = 'Stop'
$dnsReady = $false
for ($attempt = 1; $attempt -le 30; $attempt++) {
try {
$soa = @(Resolve-DnsName $ZoneName -Type SOA -DnsOnly -Server localhost `
-ErrorAction Stop | Where-Object Type -eq SOA)
if ($soa.Count -gt 0) {
$dnsReady = $true
break
}
}
catch {
# An AD-integrated zone can take a few seconds to load after DNS starts.
}
Start-Sleep -Seconds 2
}
if (-not $dnsReady) {
throw "DNS did not load the $ZoneName zone before the readiness timeout."
}
$recordReady = $false
for ($attempt = 1; $attempt -le 5; $attempt++) {
$existing = @(Get-DnsServerResourceRecord -ZoneName $ZoneName -Name $RecordName `
-RRType A -ErrorAction SilentlyContinue)
$unwanted = @($existing | Where-Object {
$_.RecordData.IPv4Address.IPAddressToString -ne $IPv4Address.IPAddressToString
})
foreach ($record in $unwanted) {
Remove-DnsServerResourceRecord -ZoneName $ZoneName -InputObject $record -Force
}
$desired = @($existing | Where-Object {
$_.RecordData.IPv4Address.IPAddressToString -eq $IPv4Address.IPAddressToString
})
if ($desired.Count -eq 0) {
try {
Add-DnsServerResourceRecordA -ZoneName $ZoneName -Name $RecordName `
-IPv4Address $IPv4Address -ErrorAction Stop
}
catch {
# A record that becomes visible while an AD-integrated zone is
# finishing its load is harmless; the verified read below decides.
}
}
Start-Sleep -Milliseconds 250
$final = @(Get-DnsServerResourceRecord -ZoneName $ZoneName -Name $RecordName `
-RRType A -ErrorAction SilentlyContinue)
$finalAddresses = @($final | ForEach-Object {
$_.RecordData.IPv4Address.IPAddressToString
})
if ($finalAddresses.Count -eq 1 -and
$finalAddresses[0] -eq $IPv4Address.IPAddressToString) {
$recordReady = $true
break
}
Start-Sleep -Seconds 1
}
if (-not $recordReady) {
throw "The $RecordName.$ZoneName A record could not be set exclusively to $IPv4Address."
}
if ($ExternalForwarders.Count -gt 0) {
Set-DnsServerForwarder -IPAddress $ExternalForwarders -UseRootHint $false
Clear-DnsServerCache -Force
Clear-DnsClientCache
}
[pscustomobject]@{
BrokerRecord = Resolve-DnsName "$RecordName.$ZoneName" | Select-Object Name, Type, IPAddress
ExternalForwarders = @(Get-DnsServerForwarder | Select-Object -ExpandProperty IPAddress | ForEach-Object IPAddressToString)
}