feat(stagging): number workflow and add DNS reservations in 0.3.0

This commit is contained in:
Madzone
2026-09-09 09:49:53 +02:00
parent 5f4a214fae
commit 0681874bb2
17 changed files with 548 additions and 95 deletions
+151
View File
@@ -0,0 +1,151 @@
Set-StrictMode -Version Latest
$ErrorActionPreference='Stop'
Import-Module (Join-Path $PSScriptRoot 'WindowsPreparation.psm1') -DisableNameChecking
function IPv4([string]$Address) {
if ($Address -notmatch '^(0|[1-9][0-9]{0,2})(\.(0|[1-9][0-9]{0,2})){3}$') { throw "Ungueltige IPv4-Adresse: $Address" }
[uint64]$v=0
foreach ($part in $Address.Split('.')) { if ([int]$part -gt 255) { throw "Ungueltige IPv4-Adresse: $Address" }; $v=256*$v+[int]$part }
return $v
}
function ClientKey([string]$ClientId) { return $ClientId.Replace('-','').Replace(':','').ToLowerInvariant() }
function Get-NetworkServicesPlan($Config) {
$base=Get-WindowsPreparationPlan $Config.Settings
$zone=$base.DnsZone
if ($zone -notmatch '^(?=.{1,180}$)(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z][a-z0-9-]*$' -or $zone.EndsWith('.arpa')) { throw 'DNS-Zone fehlt oder ist ungueltig, z.B. lab.example.' }
$getac=([string]$Config.Settings['GETAC-Name']).Trim().ToLowerInvariant()
if ($getac -notmatch '^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$') { throw 'GETAC-Name: kurzer DNS-Name ohne Domain, z.B. getac.' }
$records=@([pscustomobject]@{ Name=$getac; IP=$base.IP })
$reservations=@(); $names=@{ $getac=$true }; $macs=@{}; $ips=@{}
$low=IPv4 $base.ScopeId; $high=$low+[Math]::Pow(2,32-$base.Prefix)-1
$from=IPv4 $base.DHCPStart; $to=IPv4 $base.DHCPEnd
foreach ($h in $Config.Servers) {
$fqdn=([string]$h.Servername).ToLowerInvariant(); $suffix=".$zone"
if (-not $fqdn.EndsWith($suffix)) { throw "Servername muss in DNS-Zone $zone liegen: $fqdn" }
$name=$fqdn.Substring(0,$fqdn.Length-$suffix.Length)
if ($name -notmatch '^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$' -or $names.ContainsKey($name)) { throw "Ungueltiger oder doppelter DNS-Name: $fqdn" }
$names[$name]=$true
$mac=[string]$h['PXE-MAC-Adresse']
if ($mac -notmatch '^(?:[a-fA-F0-9]{2}:){5}[a-fA-F0-9]{2}$' -or ([Convert]::ToInt32($mac.Substring(0,2),16) -band 1) -or (ClientKey $mac) -eq '000000000000') { throw "Ungueltige PXE-MAC fuer $fqdn" }
$key=ClientKey $mac
if ($macs.ContainsKey($key)) { throw 'Doppelte PXE-MAC.' }; $macs[$key]=$true
$pxe=[string]$h['PXE-IP']; $target=[string]$h['Ziel-IP']; $p=IPv4 $pxe; $t=IPv4 $target
if ($p -lt $from -or $p -gt $to) { throw "PXE-IP muss im DHCP-Bereich liegen: $fqdn" }
if ($t -le $low -or $t -ge $high -or $target -eq $base.IP -or ($t -ge $from -and $t -le $to) -or [string]$h['Präfix'] -ne [string]$base.Prefix) { throw "Ziel-IP/Praefix muss zum festen GETAC-Netz ausserhalb DHCP passen: $fqdn" }
foreach ($ip in @($pxe,$target)) { if ($ips.ContainsKey($ip)) { throw 'Doppelte Server-IP.' }; $ips[$ip]=$true }
$reservations += [pscustomobject]@{ Name=$fqdn; IP=$pxe; ClientId=$mac.Replace(':','-').ToLowerInvariant() }
$records += [pscustomobject]@{ Name=$name; IP=$target }
}
return [pscustomobject]@{ Base=$base; Zone=$zone; ZoneFile="Stagging-KIS-$zone.dns"; Records=$records; Reservations=$reservations }
}
function Get-NetworkServicesState($Plan) {
$base=Get-PreparationState $Plan.Base
Assert-PreparationState $Plan.Base $base
if (-not $base.DhcpInstalled -or @($base.Scopes).Count -ne 1) { throw 'Zuerst 01-Setup-StagingServer.ps1 -Apply ausfuehren.' }
$scope=$Plan.Base.ScopeId
$reservations=@(Get-DhcpServerv4Reservation -ScopeId $scope)
$leases=@(Get-DhcpServerv4Lease -ScopeId $scope -AllLeases)
$exclusions=@(Get-DhcpServerv4ExclusionRange -ScopeId $scope)
$policies=@(Get-DhcpServerv4Policy)+@(Get-DhcpServerv4Policy -ScopeId $scope)
$feature=Get-WindowsFeature -Name DNS
$zones=@(); $records=@(); $dnsSettings=$null
if ($feature.Installed) {
Import-Module DnsServer
$dnsSettings=Get-DnsServerSetting -All
$rawZones=@(Get-DnsServerZone | Where-Object { -not $_.IsAutoCreated })
# Read primary-specific properties from their documented CIM class;
# the generic zone enumeration need not expose ZoneFile/DynamicUpdate.
$primary=@(Get-CimInstance -Namespace 'root/Microsoft/Windows/DNS' -ClassName DnsServerPrimaryZone)
$zones=@(foreach ($zone in $rawZones) {
$detail=@($primary | Where-Object ZoneName -eq $zone.ZoneName)
$file=''; $update=''
if ($detail.Count -eq 1) { $file=$detail[0].ZoneFile; $update=$detail[0].DynamicUpdate }
[pscustomobject]@{ ZoneName=$zone.ZoneName; ZoneType=$zone.ZoneType; IsDsIntegrated=$zone.IsDsIntegrated; ZoneFile=$file; DynamicUpdate=$update }
})
if (@($zones | Where-Object ZoneName -eq $Plan.Zone).Count -gt 0) { $records=@(Get-DnsServerResourceRecord -ZoneName $Plan.Zone) }
}
return [pscustomobject]@{ Base=$base; Reservations=$reservations; Leases=$leases; Exclusions=$exclusions; Policies=$policies; DnsInstalled=[bool]$feature.Installed; Zones=$zones; Records=$records; DnsSettings=$dnsSettings }
}
function Assert-NetworkServicesState($Plan,$State) {
Assert-PreparationState $Plan.Base $State.Base
if (-not $State.Base.DhcpInstalled -or @($State.Base.Scopes).Count -ne 1) { throw 'Schritt 01 fehlt.' }
$ip=@($State.Base.Addresses | Where-Object { $_.IPAddress -eq $Plan.Base.IP -and $_.PrefixOrigin -eq 'Manual' -and $_.AddressState -eq 'Preferred' })
$bindings=@($State.Base.Bindings | Where-Object BindingState)
if ($ip.Count -ne 1 -or $bindings.Count -ne 1 -or $bindings[0].InterfaceAlias -ne $Plan.Base.Adapter) { throw 'Feste GETAC-IP oder DHCP-Bindung fehlt. Schritt 01 pruefen.' }
if (@($State.Exclusions).Count -or @($State.Policies).Count) { throw 'Vorhandene DHCP-Ausschluesse/Policies manuell pruefen.' }
foreach ($r in $State.Reservations) {
$match=@($Plan.Reservations | Where-Object { $_.IP -eq [string]$r.IPAddress -and (ClientKey $_.ClientId) -eq (ClientKey $r.ClientId) -and $_.Name -eq $r.Name })
if ($match.Count -ne 1 -or $r.Description -ne 'Stagging-KIS' -or [string]$r.Type -ne 'Both') { throw 'Bestehende Reservierung weicht von Auswahl/Excel ab. Manuell bereinigen; kein automatisches Loeschen.' }
}
foreach ($r in $Plan.Reservations) {
foreach ($lease in $State.Leases) {
if ([string]$lease.IPAddress -eq $r.IP -and (ClientKey $lease.ClientId) -ne (ClientKey $r.ClientId)) { throw "PXE-IP $($r.IP) ist bereits anders vergeben. Lease vor Ort klaeren." }
}
}
foreach ($zone in $State.Zones) {
if ($zone.ZoneName -ne $Plan.Zone -or $zone.ZoneFile -ne $Plan.ZoneFile -or [string]$zone.ZoneType -ne 'Primary' -or $zone.IsDsIntegrated -or [string]$zone.DynamicUpdate -ne 'None') { throw 'Fremde oder abweichende DNS-Zone: keine automatische Uebernahme des DNS-Servers.' }
}
foreach ($record in $State.Records) {
if ($record.HostName -eq '@' -and [string]$record.RecordType -in @('SOA','NS')) { continue }
if ([string]$record.RecordType -ne 'A') { throw 'Unerwarteter DNS-Eintrag in der Staging-Zone.' }
$match=@($Plan.Records | Where-Object { $_.Name -eq $record.HostName -and $_.IP -eq [string]$record.RecordData.IPv4Address })
if ($match.Count -ne 1) { throw 'DNS-Eintrag weicht von Auswahl/Excel ab. Manuell pruefen.' }
}
}
function Invoke-NetworkServices($Plan,$State,[switch]$ActivateDhcp) {
Assert-NetworkServicesState $Plan $State
$scope=$Plan.Base.ScopeId
Set-DhcpServerv4Scope -ScopeId $scope -State InActive
try {
if (-not $State.DnsInstalled) {
$installed=Install-WindowsFeature -Name DNS -IncludeManagementTools
if (-not $installed.Success -or [string]$installed.RestartNeeded -eq 'Yes') { throw 'DNS-Rolle nicht einsatzbereit. Installation/Neustart lokal pruefen und Schritt 02 wiederholen.' }
}
Import-Module DnsServer
Start-Service DNS
$settings=Get-DnsServerSetting -All
$settings.ListeningIPAddress=@($Plan.Base.IP)
Set-DnsServerSetting -InputObject $settings
Set-DnsServerRecursion -Enable $false
Restart-Service DNS
if (@($State.Zones).Count -eq 0) { Add-DnsServerPrimaryZone -Name $Plan.Zone -ZoneFile $Plan.ZoneFile -DynamicUpdate None }
foreach ($r in $Plan.Records) {
if (@($State.Records | Where-Object HostName -eq $r.Name).Count -eq 0) { Add-DnsServerResourceRecordA -ZoneName $Plan.Zone -Name $r.Name -IPv4Address $r.IP }
}
foreach ($r in $Plan.Reservations) {
if (@($State.Reservations | Where-Object { [string]$_.IPAddress -eq $r.IP }).Count -eq 0) {
Add-DhcpServerv4Reservation -ScopeId $scope -IPAddress $r.IP -ClientId $r.ClientId -Name $r.Name -Description 'Stagging-KIS' -Type Both
}
}
Set-DhcpServerv4OptionValue -ScopeId $scope -DnsServer $Plan.Base.IP -DnsDomain $Plan.Zone
foreach ($protocol in @('TCP','UDP')) {
$name="Stagging-KIS-DNS-$protocol"
if (Get-NetFirewallRule -Name $name -ErrorAction SilentlyContinue) { Remove-NetFirewallRule -Name $name }
New-NetFirewallRule -Name $name -DisplayName $name -Direction Inbound -Action Allow -Protocol $protocol -LocalPort 53 -LocalAddress $Plan.Base.IP -RemoteAddress "$scope/$($Plan.Base.Prefix)" -InterfaceAlias $Plan.Base.Adapter -Profile Any -Service DNS | Out-Null
}
Set-Service DNS -StartupType Automatic
# Read back actual server state before DHCP activation.
$after=Get-NetworkServicesState $Plan
Assert-NetworkServicesState $Plan $after
if (@($after.Reservations).Count -ne @($Plan.Reservations).Count -or @($after.Records | Where-Object RecordType -eq 'A').Count -ne @($Plan.Records).Count -or @($after.Zones).Count -ne 1) { throw 'DNS/Reservierungen sind unvollstaendig.' }
foreach ($id in @(6,15)) { if (@($after.Base.Options | Where-Object OptionId -eq $id).Count -ne 1) { throw 'DNS-Optionen im DHCP-Bereich fehlen.' } }
$listen=@($after.DnsSettings.ListeningIPAddress | ForEach-Object { [string]$_ })
if ($listen.Count -ne 1 -or $listen[0] -ne $Plan.Base.IP) { throw 'DNS lauscht nicht ausschliesslich auf der GETAC-IP.' }
foreach ($r in $Plan.Records) {
$answers=@(Resolve-DnsName -Name "$($r.Name).$($Plan.Zone)" -Server $Plan.Base.IP -Type A -DnsOnly | Where-Object Type -eq 'A')
if ($answers.Count -ne 1 -or $answers[0].IPAddress -ne $r.IP) { throw "DNS-Abfrage fehlgeschlagen: $($r.Name)" }
}
if ($ActivateDhcp) { Set-DhcpServerv4Scope -ScopeId $scope -State Active }
$expected=if ($ActivateDhcp) { 'Active' } else { 'InActive' }
if ([string](Get-DhcpServerv4Scope -ScopeId $scope).State -ne $expected) { throw 'DHCP-Zustand konnte nicht bestaetigt werden.' }
return [pscustomobject]@{ Zone=$Plan.Zone; DNS=$Plan.Base.IP; Reservations=@($Plan.Reservations).Count; ARecords=@($Plan.Records).Count; DHCP=$expected }
} catch {
Set-DhcpServerv4Scope -ScopeId $scope -State InActive -ErrorAction SilentlyContinue
Stop-Service DNS -ErrorAction SilentlyContinue
throw
}
}
Export-ModuleMember -Function Get-NetworkServicesPlan,Get-NetworkServicesState,Assert-NetworkServicesState,Invoke-NetworkServices
+5 -1
View File
@@ -54,7 +54,7 @@ function Read-KisWorkbook([string]$Path) {
foreach ($key in $sheets.Staging.Cells.Keys) {
if ($key -notmatch '^A(\d+)$') { continue }
$row = $Matches[1]; $name = $sheets.Staging.Cells[$key]
if ($name -notin @('Projektname','Windows-Server-Version','Netzwerkkarte','GETAC-IP','Netzpräfix','DHCP von','DHCP bis','Medienordner','Proxmox-Medium','ESXi-Medium','Admin-E-Mail')) { continue }
if ($name -notin @('Projektname','Windows-Server-Version','Netzwerkkarte','GETAC-IP','Netzpräfix','DHCP von','DHCP bis','Medienordner','Proxmox-Medium','ESXi-Medium','Admin-E-Mail','DNS-Zone','GETAC-Name')) { continue }
if ($sheets.Staging.Formulas.ContainsKey("B$row")) { throw "Staging!B${row}: Eingabeformeln sind nicht erlaubt." }
if ($settings.ContainsKey($name)) { throw "Doppelte Staging-Einstellung: $name" }
$settings[$name] = [string]$sheets.Staging.Cells["B$row"]
@@ -75,6 +75,10 @@ function Read-KisWorkbook([string]$Path) {
if ($sheets.Server.Formulas.ContainsKey($cell)) { throw "Server!${cell}: Eingabeformeln sind nicht erlaubt." }
$values[$expected[$i]] = ([string]$sheets.Server.Cells[$cell]).Trim()
}
if ($sheets.Server.Cells['N6'] -eq 'PXE-IP') {
if ($sheets.Server.Formulas.ContainsKey("N$r")) { throw "Server!N${r}: Eingabeformeln sind nicht erlaubt." }
$values['PXE-IP']=([string]$sheets.Server.Cells["N$r"]).Trim()
}
if ($values.Installieren -notin @('','JA','NEIN')) { throw "Server Zeile ${r}: Installieren muss JA oder NEIN sein." }
if ($values.Installieren -eq 'JA') { $values.Row = $r; $servers += $values }
}
+8 -3
View File
@@ -31,7 +31,7 @@ function Get-WindowsPreparationPlan($Settings) {
if ($media -notmatch '^[a-zA-Z]:\\[^<>:"|?*\x00-\x1f]+$' -or $media -match '(?:^|\\)\.{1,2}(?:\\|$)' -or $media -match '[. ](?:\\|$)') { throw 'Medienordner: lokalen absoluten Unterordner verwenden, z.B. C:\Staging\Medien.' }
# Kept separate from media: never put secret answer files in a future webroot.
$drive=$media.Substring(0,2)
return [pscustomobject]@{ WindowsYear=$year; Adapter=$adapter; IP=[string]$Settings['GETAC-IP']; Prefix=$prefix; ScopeId=(ConvertFrom-IPv4Value $network); SubnetMask=(Get-Netmask $prefix); DHCPStart=[string]$Settings['DHCP von']; DHCPEnd=[string]$Settings['DHCP bis']; MediaDirectory=$media; BootDirectory="$drive\Staging-PXE\Boot"; ScopeName='Stagging-KIS'; ScopeDescription='Managed by Stagging Setup-StagingServer v1' }
return [pscustomobject]@{ DnsZone=([string]$Settings['DNS-Zone']).Trim().ToLowerInvariant(); WindowsYear=$year; Adapter=$adapter; IP=[string]$Settings['GETAC-IP']; Prefix=$prefix; ScopeId=(ConvertFrom-IPv4Value $network); SubnetMask=(Get-Netmask $prefix); DHCPStart=[string]$Settings['DHCP von']; DHCPEnd=[string]$Settings['DHCP bis']; MediaDirectory=$media; BootDirectory="$drive\Staging-PXE\Boot"; ScopeName='Stagging-KIS'; ScopeDescription='Managed by Stagging Setup-StagingServer v1' }
}
function Assert-PreparationState($Plan,$State) {
@@ -57,7 +57,12 @@ function Assert-PreparationState($Plan,$State) {
if ([string]$scope.StartRange -ne $Plan.DHCPStart -or [string]$scope.EndRange -ne $Plan.DHCPEnd -or [string]$scope.SubnetMask -ne $Plan.SubnetMask) { throw 'Vorhandener Staging-Bereich weicht von Excel ab. Kein automatisches Ersetzen bestehender Leases.' }
}
if (@($State.Scopes6).Count -gt 0) { throw 'Vorhandene DHCPv6-Bereiche: kein dedizierter leerer Staging-DHCP-Server.' }
if (@($State.Options).Count -gt 0) { throw 'Vorhandene DHCP-Optionen: vor automatischer Einrichtung manuell pruefen (keine impliziten Router-/PXE-Optionen).' }
foreach ($option in $State.Options) {
if (-not ($option.PSObject.Properties.Name -contains 'ScopeId') -or [string]$option.ScopeId -ne $Plan.ScopeId) { throw 'Vorhandene globale DHCP-Optionen: manuell pruefen.' }
$value=@($option.Value) -join ','
if (($option.OptionId -eq 6 -and $value -eq $Plan.IP) -or ($option.OptionId -eq 15 -and $Plan.DnsZone -and $value -eq $Plan.DnsZone)) { continue }
throw 'DHCP-Option weicht vom KIS-Profil ab. Keine automatische Uebernahme.'
}
}
function Get-PreparationState($Plan) {
@@ -78,7 +83,7 @@ function Get-PreparationState($Plan) {
Import-Module DhcpServer
$scopes=@(Get-DhcpServerv4Scope); $scopes6=@(Get-DhcpServerv6Scope); $bindings=@(Get-DhcpServerv4Binding)
$options=@(Get-DhcpServerv4OptionValue)
foreach ($scope in $scopes) { $options+=@(Get-DhcpServerv4OptionValue -ScopeId $scope.ScopeId) }
foreach ($scope in $scopes) { $options+=@(Get-DhcpServerv4OptionValue -ScopeId $scope.ScopeId | ForEach-Object { [pscustomobject]@{ ScopeId=[string]$scope.ScopeId; OptionId=$_.OptionId; Value=$_.Value } }) }
}
return [pscustomobject]@{ Caption=$os.Caption; ProductType=$os.ProductType; PartOfDomain=$computer.PartOfDomain; Adapters=$adapters; Addresses=$addresses; IPInterface=$ipInterface; DnsClient=$dnsClient; OtherAddresses=$others; DefaultRoutes=$routes; Scopes=$scopes; Scopes6=$scopes6; Options=$options; Bindings=$bindings; DhcpInstalled=[bool]$feature.Installed }
}