Update vCenter-SSL.ps1

This commit is contained in:
2025-11-15 23:14:25 -06:00
parent db2c181fc3
commit 1805326b22

View File

@@ -1,14 +1,14 @@
#!/usr/bin/env pwsh #!/usr/bin/env pwsh
# ----------------------------------------------------------------------------------- # -----------------------------------------------------------------------------------
# vCenter SSL Automation (with Posh-ACME 4.30 and XDG path support) # vCenter SSL Automation (Posh-ACME 4.30, Linux/XDG compatible)
# Fully idempotent, rate-limit safe, uses existing cert if valid >30 days # Uses cert.cer / cert.key / fullchain.cer layout
# Auto-discovers cert files under ~/.config/Posh-ACME # Rate-limit safe, fingerprint-based update, 30-day renewal window
# ----------------------------------------------------------------------------------- # -----------------------------------------------------------------------------------
. /opt/idssys/nodemgmt/conf/powerwall/settings.ps1 . /opt/idssys/nodemgmt/conf/powerwall/settings.ps1
# ---------------------------- # ----------------------------
# LOGGING # Logging
# ---------------------------- # ----------------------------
$LogFile = "/opt/idssys/nodemgmt/logs/vc-ssl.log" $LogFile = "/opt/idssys/nodemgmt/logs/vc-ssl.log"
$logDir = Split-Path -Path $LogFile -Parent $logDir = Split-Path -Path $LogFile -Parent
@@ -25,32 +25,31 @@ function Write-Log {
function Show-Banner { function Show-Banner {
param([string]$Text,[string]$Type="INFO") param([string]$Text,[string]$Type="INFO")
switch ($Type.ToUpper()) { switch ($Type.ToUpper()) {
"SUCCESS" { $color="Green"; $level="SUCCESS" } "SUCCESS" { $C="Green"; $L="SUCCESS" }
"ERROR" { $color="Red"; $level="ERROR" } "ERROR" { $C="Red"; $L="ERROR" }
"WARN" { $color="Yellow"; $level="WARN" } "WARN" { $C="Yellow"; $L="WARN" }
default { $color="Cyan"; $level="INFO" } default { $C="Cyan"; $L="INFO" }
} }
$line = "=" * [math]::Max($Text.Length,40) $line = "=" * [math]::Max($Text.Length,40)
Write-Host $line -ForegroundColor $color Write-Host $line -ForegroundColor $C
Write-Host "${level}: $Text" -ForegroundColor $color Write-Host "${L}: $Text" -ForegroundColor $C
Write-Host $line -ForegroundColor $color Write-Host $line -ForegroundColor $C
Add-Content -Path $LogFile -Value ("[{0}] {1}: {2}" -f (Get-Date),$level,$Text) Add-Content -Path $LogFile -Value ("[{0}] {1}: {2}" -f (Get-Date),$L,$Text)
} }
# ---------------------------- # ----------------------------
# ERROR HANDLING # Error handling
# ---------------------------- # ----------------------------
$global:helpme = $null $global:helpme = $null
function Show-Failure { function Show-Failure {
param([System.Management.Automation.ErrorRecord]$ErrorRecord) param([System.Management.Automation.ErrorRecord]$ErrorRecord)
$global:helpme = $ErrorRecord.Exception.Message $global:helpme = $ErrorRecord.Exception.Message
Show-Banner -Text $ErrorRecord.Exception.Message -Type "ERROR" Show-Banner -Text $ErrorRecord.Exception.Message -Type "ERROR"
Write-Log -Level "ERROR" -Message $ErrorRecord | Out-Null
exit 1 exit 1
} }
# ---------------------------- # ----------------------------
# CERT FINGERPRINT # Cert fingerprint helper
# ---------------------------- # ----------------------------
function Get-CertFingerprintFromPem { function Get-CertFingerprintFromPem {
param([string]$PemString) param([string]$PemString)
@@ -63,42 +62,29 @@ function Get-CertFingerprintFromPem {
$hash = $sha256.ComputeHash($cert.RawData) $hash = $sha256.ComputeHash($cert.RawData)
return ($hash | ForEach-Object { $_.ToString("X2") }) -join "" return ($hash | ForEach-Object { $_.ToString("X2") }) -join ""
} }
catch { catch { return $null }
Write-Log WARN "Fingerprint calculation error: $($_.Exception.Message)" Yellow
return $null
}
} }
# ---------------------------- # ----------------------------
# Posh-ACME CERT FOLDER DISCOVERY (XDG FIX) # Discover Posh-ACME cert folder (Linux/XDG)
# ---------------------------- # ----------------------------
function Find-LocalPACertFolder { function Find-LocalPACertFolder {
param([string]$HostName) param([string]$HostName)
# Correct Linux path for Posh-ACME 4.x
$paRoot = Join-Path $HOME ".config/Posh-ACME" $paRoot = Join-Path $HOME ".config/Posh-ACME"
if (-not (Test-Path $paRoot)) { if (-not (Test-Path $paRoot)) { return $null }
Write-Log WARN "Posh-ACME config folder not found: $paRoot" Yellow
return $null
}
# Look for folders named exactly after the hostname
$folders = Get-ChildItem -Path $paRoot -Recurse -Directory -ErrorAction SilentlyContinue | $folders = Get-ChildItem -Path $paRoot -Recurse -Directory -ErrorAction SilentlyContinue |
Where-Object { $_.Name -eq $HostName } Where-Object { $_.Name -eq $HostName }
if (-not $folders) { if (-not $folders) { return $null }
Write-Log WARN "No hostname-matched folders found under $paRoot" Yellow
return $null
}
$folder = $folders | Select-Object -First 1 return ($folders | Select-Object -First 1).FullName
Write-Log INFO "Using Posh-ACME cert folder: $($folder.FullName)" Gray
return $folder.FullName
} }
# ---------------------------- # ----------------------------
# LOAD POWERCLI # Load VMware PowerCLI
# ---------------------------- # ----------------------------
if (-not (Get-Module -ListAvailable VMware.PowerCLI)) { if (-not (Get-Module -ListAvailable VMware.PowerCLI)) {
Install-Module VMware.PowerCLI -Force -Scope AllUsers Install-Module VMware.PowerCLI -Force -Scope AllUsers
@@ -107,7 +93,7 @@ Import-Module VMware.PowerCLI -ErrorAction Stop
Set-PowerCLIConfiguration -InvalidCertificateAction Ignore -Confirm:$false | Out-Null Set-PowerCLIConfiguration -InvalidCertificateAction Ignore -Confirm:$false | Out-Null
# ---------------------------- # ----------------------------
# CONNECT TO VCENTER # Connect to vCenter
# ---------------------------- # ----------------------------
try { try {
Write-Log INFO "Connecting to vCenter $VCENTERHOST..." Cyan Write-Log INFO "Connecting to vCenter $VCENTERHOST..." Cyan
@@ -116,7 +102,7 @@ try {
} catch { Show-Failure $_ } } catch { Show-Failure $_ }
# ---------------------------- # ----------------------------
# LOAD POSH-ACME # Load Posh-ACME
# ---------------------------- # ----------------------------
if (-not (Get-Module -ListAvailable Posh-ACME)) { if (-not (Get-Module -ListAvailable Posh-ACME)) {
Install-Module Posh-ACME -Force -Scope AllUsers Install-Module Posh-ACME -Force -Scope AllUsers
@@ -124,7 +110,7 @@ if (-not (Get-Module -ListAvailable Posh-ACME)) {
Import-Module Posh-ACME -ErrorAction Stop Import-Module Posh-ACME -ErrorAction Stop
# ---------------------------- # ----------------------------
# ACME CERTIFICATE LOGIC # ACME logic
# ---------------------------- # ----------------------------
$certSuccess = $false $certSuccess = $false
$certPath = $keyPath = $chainPath = $null $certPath = $keyPath = $chainPath = $null
@@ -137,7 +123,7 @@ if ($allPACerts) {
} }
} }
# Match certificate for vCenter # Select cert for vcenter.scity.us
$existingPACert = $allPACerts | $existingPACert = $allPACerts |
Where-Object { $_.MainDomain -eq $VCENTERHOST -or ($_.AllSANs -contains $VCENTERHOST) } | Where-Object { $_.MainDomain -eq $VCENTERHOST -or ($_.AllSANs -contains $VCENTERHOST) } |
Sort-Object NotAfter -Descending | Sort-Object NotAfter -Descending |
@@ -146,7 +132,7 @@ $existingPACert = $allPACerts |
$renewCert = $true $renewCert = $true
$skipReason = "" $skipReason = ""
# RULE: If existing cert valid >30 days skip ACME # If valid for >30 days, skip issuance
if ($existingPACert) { if ($existingPACert) {
$daysLeft = ($existingPACert.NotAfter - (Get-Date)).TotalDays $daysLeft = ($existingPACert.NotAfter - (Get-Date)).TotalDays
Write-Log INFO "Existing cert expires $($existingPACert.NotAfter) (~$([math]::Round($daysLeft)) days)" Gray Write-Log INFO "Existing cert expires $($existingPACert.NotAfter) (~$([math]::Round($daysLeft)) days)" Gray
@@ -156,7 +142,7 @@ if ($existingPACert) {
} }
} }
# RULE: Rate-limit safety # Rate-limit safety: don't issue if created <168 hours (LE window)
if ($renewCert -and $existingPACert) { if ($renewCert -and $existingPACert) {
$hoursSince = ((Get-Date) - $existingPACert.Created).TotalHours $hoursSince = ((Get-Date) - $existingPACert.Created).TotalHours
if ($hoursSince -lt 168) { if ($hoursSince -lt 168) {
@@ -166,7 +152,7 @@ if ($renewCert -and $existingPACert) {
} }
# ------------------------------------------------------- # -------------------------------------------------------
# USE EXISTING CERT FILES (XDG-FIXED) # USE EXISTING CERT (no ACME issuance)
# ------------------------------------------------------- # -------------------------------------------------------
if (-not $renewCert -and $existingPACert) { if (-not $renewCert -and $existingPACert) {
Write-Log INFO "Skipping ACME issuance: $skipReason" Yellow Write-Log INFO "Skipping ACME issuance: $skipReason" Yellow
@@ -177,15 +163,23 @@ if (-not $renewCert -and $existingPACert) {
exit 1 exit 1
} }
$certPath = Join-Path $certFolder "cert.pem" # Posh-ACME Linux filenames:
$keyPath = Join-Path $certFolder "privkey.pem" $certPath = Join-Path $certFolder "cert.cer"
$chainPath = Join-Path $certFolder "chain.pem" $keyPath = Join-Path $certFolder "cert.key"
$chainPath = Join-Path $certFolder "fullchain.cer"
foreach ($f in @($certPath,$keyPath,$chainPath)) {
if (-not (Test-Path $f)) {
Write-Log ERROR "Missing certificate file: $f" Red
exit 1
}
}
$certSuccess = $true $certSuccess = $true
} }
# ------------------------------------------------------- # -------------------------------------------------------
# REQUEST NEW ACME CERT IF NEEDED # NEW ACME CERTIFICATE
# ------------------------------------------------------- # -------------------------------------------------------
if ($renewCert) { if ($renewCert) {
Write-Log INFO "Requesting new ACME certificate..." Cyan Write-Log INFO "Requesting new ACME certificate..." Cyan
@@ -199,11 +193,12 @@ if ($renewCert) {
PowerDNSApiKey = $securePDNSAPI PowerDNSApiKey = $securePDNSAPI
PowerDNSUseTLS = $true PowerDNSUseTLS = $true
PowerDNSPort = 443 PowerDNSPort = 443
PowerDNSServerName = 'localhost' PowerDNSServerName = "localhost"
} }
try { try {
New-PACertificate -Domain $VCENTERHOST ` New-PACertificate `
-Domain $VCENTERHOST `
-DnsPlugin PowerDNS ` -DnsPlugin PowerDNS `
-PluginArgs $pArgs ` -PluginArgs $pArgs `
-Contact $ACMEEMAIL ` -Contact $ACMEEMAIL `
@@ -212,13 +207,13 @@ if ($renewCert) {
-Force ` -Force `
-Verbose -Verbose
# Find new cert folder via XDG
$certFolder = Find-LocalPACertFolder -HostName $VCENTERHOST $certFolder = Find-LocalPACertFolder -HostName $VCENTERHOST
if (-not $certFolder) { Show-Banner "ACME succeeded but no files found." ERROR; exit 1 } if (-not $certFolder) { Show-Banner "ACME OK but no files found!" ERROR; exit 1 }
$certPath = Join-Path $certFolder "cert.cer"
$keyPath = Join-Path $certFolder "cert.key"
$chainPath = Join-Path $certFolder "fullchain.cer"
$certPath = Join-Path $certFolder "cert.pem"
$keyPath = Join-Path $certFolder "privkey.pem"
$chainPath = Join-Path $certFolder "chain.pem"
$certSuccess = $true $certSuccess = $true
Show-Banner "New ACME certificate created." SUCCESS Show-Banner "New ACME certificate created." SUCCESS
} }
@@ -228,28 +223,18 @@ if ($renewCert) {
$global:helpme = $msg $global:helpme = $msg
if ($msg -like "*too many certificates*") { if ($msg -like "*too many certificates*") {
Show-Banner "Rate-limit hit! Falling back to existing cert." WARN Show-Banner "Rate limit hit! Using existing cert." WARN
if (-not $existingPACert) {
if ($existingPACert) { Show-Banner "No fallback cert exists! Aborting." ERROR
$certFolder = Find-LocalPACertFolder -HostName $VCENTERHOST
if ($certFolder) {
$certPath = Join-Path $certFolder "cert.pem"
$keyPath = Join-Path $certFolder "privkey.pem"
$chainPath = Join-Path $certFolder "chain.pem"
$certSuccess = $true
} else {
Show-Banner "Cannot locate fallback cert files. Aborting." ERROR
exit 1 exit 1
} }
} }
else { Show-Banner "No fallback cert exists." ERROR; exit 1 }
}
else { exit 1 } else { exit 1 }
} }
} }
# ------------------------------------------------------- # -------------------------------------------------------
# VERIFY CERT FILES EXIST # CERT SANITY CHECK
# ------------------------------------------------------- # -------------------------------------------------------
foreach ($f in @($certPath,$keyPath,$chainPath)) { foreach ($f in @($certPath,$keyPath,$chainPath)) {
if (-not (Test-Path $f)) { if (-not (Test-Path $f)) {
@@ -259,7 +244,7 @@ foreach ($f in @($certPath,$keyPath,$chainPath)) {
} }
# ------------------------------------------------------- # -------------------------------------------------------
# CHECK VCENTER CURRENT CERT & COMPARE FINGERPRINTS # COMPARE CURRENT VCENTER CERT
# ------------------------------------------------------- # -------------------------------------------------------
$sessionHeaders = @{ $sessionHeaders = @{
'vmware-api-session-id' = $vCenterConn.ExtensionData.Content.SessionManager.SessionId 'vmware-api-session-id' = $vCenterConn.ExtensionData.Content.SessionManager.SessionId
@@ -269,17 +254,14 @@ $vcenterCertUri = "https://$VCENTERHOST/rest/vcenter/certificate-management/vcen
$updateNeeded = $true $updateNeeded = $true
try { try {
$vcResp = Invoke-RestMethod -Uri $vcenterCertUri -Method Get -Headers $sessionHeaders -SkipCertificateCheck $vcCert = Invoke-RestMethod -Uri $vcenterCertUri -Method Get -Headers $sessionHeaders -SkipCertificateCheck
$currentPem = $vcResp.value.cert $currentPem = $vcCert.value.cert
$currentFp = Get-CertFingerprintFromPem $currentPem $currentFp = Get-CertFingerprintFromPem $currentPem
$newFp = Get-CertFingerprintFromPem (Get-Content -Raw $certPath) $newFp = Get-CertFingerprintFromPem (Get-Content -Raw $certPath)
if ($currentFp -and $newFp -and ($currentFp -eq $newFp)) { if ($currentFp -and $newFp -and ($currentFp -eq $newFp)) {
Show-Banner "vCenter certificate already up-to-date." SUCCESS Show-Banner "vCenter certificate already up-to-date." SUCCESS
$updateNeeded = $false $updateNeeded = $false
} else {
Write-Log INFO "Fingerprint mismatch → update required." Yellow
} }
} }
catch { catch {
@@ -287,10 +269,8 @@ catch {
} }
# ------------------------------------------------------- # -------------------------------------------------------
# UPLOAD / APPLY NEW CERT # UPLOAD + APPLY CERTIFICATE
# ------------------------------------------------------- # -------------------------------------------------------
$restartNeeded = $false
if ($updateNeeded) { if ($updateNeeded) {
try { try {
$body = @{ $body = @{
@@ -299,13 +279,13 @@ if ($updateNeeded) {
chain = Get-Content -Raw $chainPath chain = Get-Content -Raw $chainPath
} }
Write-Log INFO "Uploading new cert..." Cyan Write-Log INFO "Uploading certificate..." Cyan
Invoke-RestMethod -Uri $vcenterCertUri -Method Post -Headers $sessionHeaders ` Invoke-RestMethod -Uri $vcenterCertUri -Method Post -Headers $sessionHeaders `
-ContentType "application/json" -Body ($body | ConvertTo-Json -Compress) -SkipCertificateCheck -ContentType "application/json" -Body ($body | ConvertTo-Json -Compress) -SkipCertificateCheck
Write-Log INFO "Applying certificate..." Cyan Write-Log INFO "Applying certificate..." Cyan
Invoke-RestMethod -Uri "$vcenterCertUri?action=apply" -Method Post ` Invoke-RestMethod -Uri "$vcenterCertUri?action=apply" `
-Headers $sessionHeaders -SkipCertificateCheck -Method Post -Headers $sessionHeaders -SkipCertificateCheck
Show-Banner "Certificate applied to vCenter." SUCCESS Show-Banner "Certificate applied to vCenter." SUCCESS
$restartNeeded = $true $restartNeeded = $true
@@ -320,10 +300,11 @@ else {
} }
# ------------------------------------------------------- # -------------------------------------------------------
# RESTART VPXD (IF NEEDED) # Restart vpxd (optional, REST)
# ------------------------------------------------------- # -------------------------------------------------------
if ($restartNeeded) { if ($restartNeeded) {
$maxRetries = 20 $maxRetries = 20
for ($i=1; $i -le $maxRetries; $i++) { for ($i=1; $i -le $maxRetries; $i++) {
try { try {
Invoke-RestMethod -Uri "https://$VCENTERHOST/rest/appliance/health/system" ` Invoke-RestMethod -Uri "https://$VCENTERHOST/rest/appliance/health/system" `