Update vCenter-SSL.ps1
This commit is contained in:
@@ -1,13 +1,14 @@
|
|||||||
#!/usr/bin/env pwsh
|
#!/usr/bin/env pwsh
|
||||||
# -----------------------------------------------------------------------------------
|
# -----------------------------------------------------------------------------------
|
||||||
# vCenter + Posh-ACME Script
|
# vCenter + Posh-ACME SSL Automation Script
|
||||||
# Fully automated, idempotent, with logging and fingerprint comparison
|
# Fully idempotent, rate-limit safe, fingerprint matching, full logging
|
||||||
|
# Compatible with: Posh-ACME 4.30.0
|
||||||
# -----------------------------------------------------------------------------------
|
# -----------------------------------------------------------------------------------
|
||||||
|
|
||||||
. /opt/idssys/nodemgmt/conf/powerwall/settings.ps1
|
. /opt/idssys/nodemgmt/conf/powerwall/settings.ps1
|
||||||
|
|
||||||
# ----------------------------
|
# ----------------------------
|
||||||
# Logging setup
|
# 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
|
||||||
@@ -16,188 +17,148 @@ if (-not (Test-Path $logDir)) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function Write-Log {
|
function Write-Log {
|
||||||
param(
|
param([string]$Level,[string]$Message,[string]$Color="White")
|
||||||
[string]$Level,
|
$ts = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
|
||||||
[string]$Message,
|
$line = "[{0}] {1}: {2}" -f $ts,$Level.ToUpper(),$Message
|
||||||
[string]$Color = "White"
|
|
||||||
)
|
|
||||||
$ts = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
|
|
||||||
$line = "[{0}] {1}: {2}" -f $ts, $Level.ToUpper(), $Message
|
|
||||||
Write-Host $line -ForegroundColor $Color
|
Write-Host $line -ForegroundColor $Color
|
||||||
Add-Content -Path $LogFile -Value $line
|
Add-Content -Path $LogFile -Value $line
|
||||||
}
|
}
|
||||||
|
|
||||||
function Show-Banner {
|
function Show-Banner {
|
||||||
param(
|
param([string]$Text,[string]$Type="INFO")
|
||||||
[string]$Text,
|
|
||||||
[string]$Type = "INFO"
|
|
||||||
)
|
|
||||||
switch ($Type.ToUpper()) {
|
switch ($Type.ToUpper()) {
|
||||||
"SUCCESS" { $color = "Green"; $level = "SUCCESS" }
|
"SUCCESS" { $color="Green"; $level="SUCCESS" }
|
||||||
"ERROR" { $color = "Red"; $level = "ERROR" }
|
"ERROR" { $color="Red"; $level="ERROR" }
|
||||||
"WARN" { $color = "Yellow"; $level = "WARN" }
|
"WARN" { $color="Yellow"; $level="WARN" }
|
||||||
default { $color = "Cyan"; $level = "INFO" }
|
default { $color="Cyan"; $level="INFO" }
|
||||||
}
|
}
|
||||||
|
$line = "=" * [math]::Max($Text.Length,40)
|
||||||
$line = ("=" * [Math]::Max($Text.Length, 40))
|
|
||||||
|
|
||||||
Write-Host $line -ForegroundColor $color
|
Write-Host $line -ForegroundColor $color
|
||||||
Write-Host "${level}: $Text" -ForegroundColor $color
|
Write-Host "${level}: $Text" -ForegroundColor $color
|
||||||
Write-Host $line -ForegroundColor $color
|
Write-Host $line -ForegroundColor $color
|
||||||
|
Add-Content -Path $LogFile -Value ("[{0}] {1}: {2}" -f (Get-Date),$level,$Text)
|
||||||
$ts = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
|
|
||||||
$log = "[{0}] {1}: {2}" -f $ts, $level, $Text
|
|
||||||
Add-Content -Path $LogFile -Value $log
|
|
||||||
}
|
}
|
||||||
|
|
||||||
# ----------------------------
|
# ----------------------------
|
||||||
# Global variables for troubleshooting
|
# ERROR HANDLING
|
||||||
# ----------------------------
|
# ----------------------------
|
||||||
$global:helpme = $null
|
$global:helpme = $null
|
||||||
$global:responseBody = $null
|
|
||||||
|
|
||||||
# ----------------------------
|
|
||||||
# Error handler
|
|
||||||
# ----------------------------
|
|
||||||
function Show-Failure {
|
function Show-Failure {
|
||||||
param([System.Management.Automation.ErrorRecord]$ErrorRecord)
|
param([System.Management.Automation.ErrorRecord]$ErrorRecord)
|
||||||
|
$global:helpme = $ErrorRecord.Exception.Message
|
||||||
$global:responseBody = $ErrorRecord.Exception.Message
|
|
||||||
$global:helpme = $global:responseBody
|
|
||||||
|
|
||||||
Show-Banner -Text $ErrorRecord.Exception.Message -Type "ERROR"
|
Show-Banner -Text $ErrorRecord.Exception.Message -Type "ERROR"
|
||||||
Write-Log -Level "ERROR" -Message "Exception: $($ErrorRecord | Out-String)" -Color "Red"
|
Write-Log -Level "ERROR" -Message $ErrorRecord | Out-Null
|
||||||
|
|
||||||
exit 1
|
exit 1
|
||||||
}
|
}
|
||||||
|
|
||||||
# ----------------------------
|
# ----------------------------
|
||||||
# Certificate fingerprint helper (SHA-256)
|
# SHA-256 CERT FINGERPRINT
|
||||||
# ----------------------------
|
# ----------------------------
|
||||||
function Get-CertFingerprintFromPem {
|
function Get-CertFingerprintFromPem {
|
||||||
param(
|
param([string]$PemString)
|
||||||
[Parameter(Mandatory = $true)]
|
|
||||||
[string]$PemString
|
|
||||||
)
|
|
||||||
|
|
||||||
try {
|
try {
|
||||||
# Strip the BEGIN/END lines and blank lines
|
$pemBody = $PemString -replace "`r","" -split "`n" |
|
||||||
$pemBody = $PemString -replace "`r","" -split "`n" | Where-Object {
|
Where-Object {$_ -notmatch "^-----"} |
|
||||||
($_ -notlike "-----BEGIN*") -and
|
Where-Object {$_ -ne ""}
|
||||||
($_ -notlike "-----END*") -and
|
$pemBody = ($pemBody -join "")
|
||||||
($_ -ne "")
|
|
||||||
}
|
|
||||||
$pemBody = ($pemBody -join "") # single base64 string
|
|
||||||
|
|
||||||
$bytes = [Convert]::FromBase64String($pemBody)
|
$bytes = [Convert]::FromBase64String($pemBody)
|
||||||
$cert = [System.Security.Cryptography.X509Certificates.X509Certificate2]::new($bytes)
|
$cert = [System.Security.Cryptography.X509Certificates.X509Certificate2]::new($bytes)
|
||||||
|
|
||||||
$sha256 = [System.Security.Cryptography.SHA256]::Create()
|
$sha256 = [System.Security.Cryptography.SHA256]::Create()
|
||||||
$hash = $sha256.ComputeHash($cert.RawData)
|
$hash = $sha256.ComputeHash($cert.RawData)
|
||||||
($hash | ForEach-Object { $_.ToString("X2") }) -join ""
|
return ($hash | ForEach-Object { $_.ToString("X2") }) -join ""
|
||||||
}
|
} catch {
|
||||||
catch {
|
Write-Log -Level "WARN" -Message "Fingerprint calc error: $($_.Exception.Message)" -Color Yellow
|
||||||
Write-Log -Level "WARN" -Message "Failed to compute fingerprint: $($_.Exception.Message)" -Color "Yellow"
|
|
||||||
return $null
|
return $null
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
# ----------------------------
|
# ----------------------------
|
||||||
# Ensure PowerCLI module
|
# LOAD POWERCLI
|
||||||
# ----------------------------
|
# ----------------------------
|
||||||
if (-not (Get-Module -ListAvailable -Name VMware.PowerCLI)) {
|
if (-not (Get-Module -ListAvailable VMware.PowerCLI)) {
|
||||||
Write-Log -Level "INFO" -Message "VMware.PowerCLI not found. Installing..." -Color "Yellow"
|
Install-Module VMware.PowerCLI -Force -Scope AllUsers
|
||||||
Install-Module -Name VMware.PowerCLI -Force -Scope AllUsers
|
|
||||||
}
|
}
|
||||||
Import-Module VMware.PowerCLI -ErrorAction Stop
|
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 -Level "INFO" -Message "Connecting to vCenter at $VCENTERHOST ..." -Color "Cyan"
|
Write-Log -Level "INFO" -Message "Connecting to vCenter $VCENTERHOST..." -Color Cyan
|
||||||
$vCenterConn = Connect-VIServer -Server $VCENTERHOST -User $VCENTERUSER -Password $VCENTERPASS -Force
|
$vCenterConn = Connect-VIServer -Server $VCENTERHOST -User $VCENTERUSER -Password $VCENTERPASS -Force
|
||||||
Show-Banner -Text "Connected to vCenter API. Session established." -Type "SUCCESS"
|
Show-Banner -Text "Connected to vCenter." -Type SUCCESS
|
||||||
} catch {
|
} catch { Show-Failure $_ }
|
||||||
Show-Failure -ErrorRecord $_
|
|
||||||
}
|
|
||||||
|
|
||||||
# ----------------------------
|
# ----------------------------
|
||||||
# Retrieve VM list (optional)
|
# LOAD POSH-ACME
|
||||||
# ----------------------------
|
# ----------------------------
|
||||||
try {
|
if (-not (Get-Module -ListAvailable Posh-ACME)) {
|
||||||
$vms = Get-VM
|
Install-Module Posh-ACME -Force -Scope AllUsers
|
||||||
Write-Log -Level "INFO" -Message "Retrieved VM list ($($vms.Count) VMs)." -Color "Cyan"
|
|
||||||
$vms | ForEach-Object { Write-Log -Level "INFO" -Message "VM: $($_.Name)" -Color "Gray" }
|
|
||||||
} catch {
|
|
||||||
Write-Log -Level "WARN" -Message "Unable to retrieve VM list, continuing..." -Color "Yellow"
|
|
||||||
}
|
|
||||||
|
|
||||||
# ----------------------------
|
|
||||||
# Ensure Posh-ACME module
|
|
||||||
# ----------------------------
|
|
||||||
if (-not (Get-Module -ListAvailable -Name Posh-ACME)) {
|
|
||||||
Write-Log -Level "INFO" -Message "Posh-ACME not found. Installing..." -Color "Yellow"
|
|
||||||
Install-Module -Name Posh-ACME -Force -Scope AllUsers
|
|
||||||
}
|
}
|
||||||
Import-Module Posh-ACME -ErrorAction Stop
|
Import-Module Posh-ACME -ErrorAction Stop
|
||||||
|
|
||||||
# ----------------------------
|
# ----------------------------
|
||||||
# ACME / Posh-ACME certificate logic (v4.30-compatible)
|
# ACME CERTIFICATE LOGIC (Posh-ACME 4.30)
|
||||||
# ----------------------------
|
# ----------------------------
|
||||||
$certSuccess = $false
|
$certSuccess = $false
|
||||||
$certPath = $null
|
$certPath = $keyPath = $chainPath = $null
|
||||||
$keyPath = $null
|
|
||||||
$chainPath = $null
|
|
||||||
|
|
||||||
# Get most recent Posh-ACME certificate for this domain
|
# Log all certs first
|
||||||
$existingPACert = Get-PACertificate |
|
$allPACerts = Get-PACertificate -ErrorAction SilentlyContinue
|
||||||
Where-Object { $_.MainDomain -eq $VCENTERHOST } |
|
if ($allPACerts) {
|
||||||
|
Write-Log INFO "Found $($allPACerts.Count) Posh-ACME certs." Gray
|
||||||
|
foreach ($c in $allPACerts) {
|
||||||
|
Write-Log INFO (" Cert: MainDomain={0} SANs={1} Exp={2}" -f $c.MainDomain, ($c.AllSANs -join ","), $c.NotAfter) Gray
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
Write-Log INFO "No Posh-ACME certs found." Yellow
|
||||||
|
}
|
||||||
|
|
||||||
|
# Find cert matching VCENTERHOST
|
||||||
|
$existingPACert = $allPACerts |
|
||||||
|
Where-Object {$_.MainDomain -eq $VCENTERHOST -or ($_.AllSANs -contains $VCENTERHOST)} |
|
||||||
Sort-Object NotAfter -Descending |
|
Sort-Object NotAfter -Descending |
|
||||||
Select-Object -First 1
|
Select-Object -First 1
|
||||||
|
|
||||||
$renewCert = $true
|
$renewCert = $true
|
||||||
$skipReason = ""
|
$skipReason = ""
|
||||||
|
|
||||||
# Rule 1: Skip if cert valid >30 days
|
# RULE 1: Existing cert valid >30 days → skip
|
||||||
if ($existingPACert) {
|
if ($existingPACert) {
|
||||||
$daysLeft = ($existingPACert.NotAfter - (Get-Date)).TotalDays
|
$daysLeft = ($existingPACert.NotAfter - (Get-Date)).TotalDays
|
||||||
Write-Log -Level "INFO" -Message "Existing cert expires $($existingPACert.NotAfter) (~$([math]::Round($daysLeft)) days left)." -Color "Gray"
|
Write-Log INFO "Existing cert expires $($existingPACert.NotAfter) (~$([math]::Round($daysLeft)) days)." Gray
|
||||||
|
|
||||||
if ($daysLeft -gt 30) {
|
if ($daysLeft -gt 30) {
|
||||||
$renewCert = $false
|
$renewCert = $false
|
||||||
$skipReason = "Existing certificate is valid for more than 30 days."
|
$skipReason = "Existing certificate still valid >30 days."
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
# Rule 2: LE rate-limit safety (don't request if last issuance < 168h)
|
# RULE 2: LE rate-limit safety (168h)
|
||||||
if ($renewCert -and $existingPACert) {
|
if ($renewCert -and $existingPACert) {
|
||||||
$hoursSinceIssued = ((Get-Date) - $existingPACert.Created).TotalHours
|
$hoursSinceIssued = ((Get-Date) - $existingPACert.Created).TotalHours
|
||||||
if ($hoursSinceIssued -lt 168) {
|
if ($hoursSinceIssued -lt 168) {
|
||||||
$renewCert = $false
|
$renewCert = $false
|
||||||
$skipReason = "LE rate-limit safety: last cert issued $([math]::Round($hoursSinceIssued)) hours ago (must wait 168h)."
|
$skipReason = "LE rate-limit safety: last cert was $([math]::Round($hoursSinceIssued)) hours ago."
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
# If skipping ACME issuance
|
||||||
if (-not $renewCert -and $existingPACert) {
|
if (-not $renewCert -and $existingPACert) {
|
||||||
Write-Log -Level "INFO" -Message "Skipping ACME issuance: $skipReason" -Color "Yellow"
|
Write-Log INFO "Skipping new ACME issuance: $skipReason" Yellow
|
||||||
|
|
||||||
$certPath = $existingPACert.CertificatePath
|
$certPath = $existingPACert.CertificatePath
|
||||||
$keyPath = $existingPACert.PrivateKeyPath
|
$keyPath = $existingPACert.PrivateKeyPath
|
||||||
$chainPath = $existingPACert.ChainPath
|
$chainPath = $existingPACert.ChainPath
|
||||||
$certSuccess = $true
|
$certSuccess = $true
|
||||||
}
|
}
|
||||||
else {
|
else {
|
||||||
# We either have no existing cert, it's near expiry, or outside LE safety window
|
# NEED NEW CERTIFICATE
|
||||||
|
Write-Log INFO "Requesting new ACME certificate..." Cyan
|
||||||
|
|
||||||
Write-Log -Level "INFO" -Message "Requesting new ACME certificate via Posh-ACME..." -Color "Cyan"
|
$securePDNSAPI = if ($PDNSAPI -is [string]) {
|
||||||
|
ConvertTo-SecureString $PDNSAPI -AsPlainText -Force
|
||||||
if ($PDNSAPI -is [string]) {
|
} else { $PDNSAPI }
|
||||||
$securePDNSAPI = ConvertTo-SecureString $PDNSAPI -AsPlainText -Force
|
|
||||||
} else {
|
|
||||||
$securePDNSAPI = $PDNSAPI
|
|
||||||
}
|
|
||||||
|
|
||||||
$pArgs = @{
|
$pArgs = @{
|
||||||
PowerDNSApiHost = $WDNSHOST
|
PowerDNSApiHost = $WDNSHOST
|
||||||
@@ -208,17 +169,11 @@ else {
|
|||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
New-PACertificate -Domain $VCENTERHOST `
|
New-PACertificate -Domain $VCENTERHOST -DnsPlugin PowerDNS -PluginArgs $pArgs `
|
||||||
-DnsPlugin PowerDNS `
|
-Contact $ACMEEMAIL -AcceptTOS -DnsSleep 15 -Force -Verbose
|
||||||
-PluginArgs $pArgs `
|
|
||||||
-Contact $ACMEEMAIL `
|
|
||||||
-AcceptTOS `
|
|
||||||
-DnsSleep 15 `
|
|
||||||
-Force `
|
|
||||||
-Verbose
|
|
||||||
|
|
||||||
$newCert = Get-PACertificate |
|
$newCert = Get-PACertificate |
|
||||||
Where-Object { $_.MainDomain -eq $VCENTERHOST } |
|
Where-Object {$_.MainDomain -eq $VCENTERHOST -or ($_.AllSANs -contains $VCENTERHOST)} |
|
||||||
Sort-Object NotAfter -Descending |
|
Sort-Object NotAfter -Descending |
|
||||||
Select-Object -First 1
|
Select-Object -First 1
|
||||||
|
|
||||||
@@ -227,166 +182,128 @@ else {
|
|||||||
$keyPath = $newCert.PrivateKeyPath
|
$keyPath = $newCert.PrivateKeyPath
|
||||||
$chainPath = $newCert.ChainPath
|
$chainPath = $newCert.ChainPath
|
||||||
$certSuccess = $true
|
$certSuccess = $true
|
||||||
Show-Banner -Text "New ACME certificate successfully created." -Type "SUCCESS"
|
Show-Banner "New ACME certificate created." SUCCESS
|
||||||
} else {
|
} else {
|
||||||
Write-Log -Level "ERROR" -Message "ACME issuance succeeded but no certificate object found from Get-PACertificate." -Color "Red"
|
Write-Log ERROR "ACME succeeded but no certificate found." Red
|
||||||
$certSuccess = $false
|
$certSuccess = $false
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
catch {
|
catch {
|
||||||
$errorMessage = $_.Exception.Message
|
$msg = $_.Exception.Message
|
||||||
Write-Log -Level "ERROR" -Message "ACME request failed: $errorMessage" -Color "Red"
|
Write-Log ERROR "ACME request failed: $msg" Red
|
||||||
$global:helpme = $errorMessage
|
$global:helpme = $msg
|
||||||
|
|
||||||
# If LE rate-limit hit, try to fall back to existing cert
|
if ($msg -like "*too many certificates*") {
|
||||||
if ($errorMessage -like "*too many certificates*") {
|
Show-Banner "Rate-limit hit. Trying fallback..." WARN
|
||||||
Show-Banner -Text "Let’s Encrypt rate-limit reached. Using existing certificate if available." -Type "WARN"
|
|
||||||
|
|
||||||
if ($existingPACert) {
|
if ($existingPACert) {
|
||||||
$certPath = $existingPACert.CertificatePath
|
$certPath = $existingPACert.CertificatePath
|
||||||
$keyPath = $existingPACert.PrivateKeyPath
|
$keyPath = $existingPACert.PrivateKeyPath
|
||||||
$chainPath = $existingPACert.ChainPath
|
$chainPath = $existingPACert.ChainPath
|
||||||
$certSuccess = $true
|
$certSuccess = $true
|
||||||
} else {
|
|
||||||
Show-Banner -Text "No existing certificate available to fall back to!" -Type "ERROR"
|
|
||||||
$certSuccess = $false
|
|
||||||
}
|
}
|
||||||
} else {
|
else {
|
||||||
$certSuccess = $false
|
Show-Banner "No fallback cert exists. Aborting." ERROR
|
||||||
|
exit 1
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
else { exit 1 }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
# Verify cert files exist
|
# Validate final cert files
|
||||||
if ($certSuccess) {
|
foreach ($f in @($certPath,$keyPath,$chainPath)) {
|
||||||
foreach ($f in @($certPath, $keyPath, $chainPath)) {
|
if (-not (Test-Path $f)) {
|
||||||
if (-not (Test-Path $f)) {
|
Write-Log ERROR "Missing certificate file: $f" Red
|
||||||
Write-Log -Level "ERROR" -Message "Certificate file missing: $f" -Color "Red"
|
exit 1
|
||||||
$certSuccess = $false
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (-not $certSuccess) {
|
|
||||||
Show-Banner -Text "No usable certificate available. Aborting before vCenter update." -Type "ERROR"
|
|
||||||
exit 1
|
|
||||||
}
|
|
||||||
|
|
||||||
# ----------------------------
|
# ----------------------------
|
||||||
# vCenter REST: Compare fingerprints and update if needed
|
# CHECK VCENTER CERT & FINGERPRINT MATCH
|
||||||
# ----------------------------
|
# ----------------------------
|
||||||
$sessionHeaders = @{
|
$sessionHeaders = @{
|
||||||
'vmware-api-session-id' = $vCenterConn.ExtensionData.Content.SessionManager.SessionId
|
'vmware-api-session-id' = $vCenterConn.ExtensionData.Content.SessionManager.SessionId
|
||||||
}
|
}
|
||||||
$vcenterCertUri = "https://$VCENTERHOST/rest/vcenter/certificate-management/vcenter/tls"
|
|
||||||
|
|
||||||
|
$vcenterCertUri = "https://$VCENTERHOST/rest/vcenter/certificate-management/vcenter/tls"
|
||||||
$updateNeeded = $true
|
$updateNeeded = $true
|
||||||
|
|
||||||
try {
|
try {
|
||||||
Write-Log -Level "INFO" -Message "Querying current vCenter TLS certificate..." -Color "Cyan"
|
$vcResp = Invoke-RestMethod -Uri $vcenterCertUri -Method Get -Headers $sessionHeaders -SkipCertificateCheck
|
||||||
$vcResp = Invoke-RestMethod -Uri $vcenterCertUri -Method Get -Headers $sessionHeaders -SkipCertificateCheck -ErrorAction Stop
|
$currentPem = $vcResp.value.cert
|
||||||
|
|
||||||
$currentPem = $null
|
$currentFp = Get-CertFingerprintFromPem -PemString $currentPem
|
||||||
if ($vcResp.value -and $vcResp.value.cert) {
|
$newPem = Get-Content -Raw $certPath
|
||||||
$currentPem = $vcResp.value.cert
|
$newFp = Get-CertFingerprintFromPem -PemString $newPem
|
||||||
} elseif ($vcResp.certificate) {
|
|
||||||
$currentPem = $vcResp.certificate
|
|
||||||
}
|
|
||||||
|
|
||||||
if ($currentPem) {
|
if ($currentFp -and $newFp -and ($currentFp -eq $newFp)) {
|
||||||
$currentFp = Get-CertFingerprintFromPem -PemString $currentPem
|
Show-Banner "vCenter certificate already up-to-date." SUCCESS
|
||||||
$newPem = Get-Content -Path $certPath -Raw
|
$updateNeeded = $false
|
||||||
$newFp = Get-CertFingerprintFromPem -PemString $newPem
|
|
||||||
|
|
||||||
if ($currentFp -and $newFp -and ($currentFp -eq $newFp)) {
|
|
||||||
Write-Log -Level "INFO" -Message "vCenter already has the same certificate (fingerprint match)." -Color "Green"
|
|
||||||
$updateNeeded = $false
|
|
||||||
} else {
|
|
||||||
Write-Log -Level "INFO" -Message "vCenter certificate differs from Posh-ACME cert. Update is required." -Color "Yellow"
|
|
||||||
$updateNeeded = $true
|
|
||||||
}
|
|
||||||
} else {
|
} else {
|
||||||
Write-Log -Level "WARN" -Message "Could not parse existing vCenter certificate from REST response. Assuming update required." -Color "Yellow"
|
Write-Log INFO "Certificate fingerprints differ. Update required." Yellow
|
||||||
$updateNeeded = $true
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
catch {
|
catch {
|
||||||
Write-Log -Level "WARN" -Message "Failed to query current vCenter certificate: $($_.Exception.Message). Proceeding with update." -Color "Yellow"
|
Write-Log WARN "Cannot read vCenter cert, assuming update needed." Yellow
|
||||||
$updateNeeded = $true
|
$updateNeeded = $true
|
||||||
}
|
}
|
||||||
|
|
||||||
# ----------------------------
|
# ----------------------------
|
||||||
# Upload/apply cert if needed
|
# UPLOAD + APPLY NEW CERT
|
||||||
# ----------------------------
|
# ----------------------------
|
||||||
$restartNeeded = $false
|
$restartNeeded = $false
|
||||||
|
|
||||||
if ($updateNeeded) {
|
if ($updateNeeded) {
|
||||||
try {
|
try {
|
||||||
$body = @{
|
$body = @{
|
||||||
cert = Get-Content -Path $certPath -Raw
|
cert = Get-Content -Raw $certPath
|
||||||
key = Get-Content -Path $keyPath -Raw
|
key = Get-Content -Raw $keyPath
|
||||||
chain = Get-Content -Path $chainPath -Raw
|
chain = Get-Content -Raw $chainPath
|
||||||
}
|
}
|
||||||
|
|
||||||
Write-Log -Level "INFO" -Message "Uploading TLS certificate to vCenter..." -Color "Cyan"
|
Write-Log INFO "Uploading new TLS cert to vCenter..." Cyan
|
||||||
Invoke-RestMethod -Uri $vcenterCertUri -Method Post -Body ($body | ConvertTo-Json -Compress) `
|
Invoke-RestMethod -Uri $vcenterCertUri -Method Post `
|
||||||
-ContentType 'application/json' -Headers $sessionHeaders -SkipCertificateCheck
|
-Headers $sessionHeaders -ContentType "application/json" `
|
||||||
Show-Banner -Text "Certificate uploaded to vCenter." -Type "SUCCESS"
|
-Body ($body | ConvertTo-Json -Compress) -SkipCertificateCheck
|
||||||
|
|
||||||
$uriApply = "https://$VCENTERHOST/rest/vcenter/certificate-management/vcenter/tls?action=apply"
|
Write-Log INFO "Applying new TLS cert..." Cyan
|
||||||
Write-Log -Level "INFO" -Message "Applying TLS certificate to vCenter..." -Color "Cyan"
|
Invoke-RestMethod -Uri "$vcenterCertUri?action=apply" `
|
||||||
Invoke-RestMethod -Uri $uriApply -Method Post -Headers $sessionHeaders -SkipCertificateCheck
|
-Method Post -Headers $sessionHeaders -SkipCertificateCheck
|
||||||
Show-Banner -Text "Certificate applied to vCenter." -Type "SUCCESS"
|
|
||||||
|
|
||||||
|
Show-Banner "Certificate applied to vCenter." SUCCESS
|
||||||
$restartNeeded = $true
|
$restartNeeded = $true
|
||||||
}
|
}
|
||||||
catch {
|
catch {
|
||||||
Write-Log -Level "ERROR" -Message "Certificate upload/apply failed: $($_.Exception.Message)" -Color "Red"
|
Show-Banner "Failed to upload/apply certificate: $($_.Exception.Message)" ERROR
|
||||||
$global:helpme = $_.Exception.Message
|
exit 1
|
||||||
Show-Banner -Text "Failed to upload/apply certificate to vCenter." -Type "ERROR"
|
|
||||||
$restartNeeded = $false
|
|
||||||
}
|
}
|
||||||
} else {
|
}
|
||||||
Show-Banner -Text "vCenter certificate is already up to date. No upload/apply needed." -Type "SUCCESS"
|
else {
|
||||||
$restartNeeded = $false
|
Write-Log INFO "Skipping cert upload/apply." Green
|
||||||
}
|
}
|
||||||
|
|
||||||
# ----------------------------
|
# ----------------------------
|
||||||
# vpxd restart via REST (only if cert changed)
|
# RESTART VPXD IF NEEDED
|
||||||
# ----------------------------
|
# ----------------------------
|
||||||
if ($restartNeeded) {
|
if ($restartNeeded) {
|
||||||
$maxRetries = 20
|
$maxRetries = 20
|
||||||
$retryCount = 0
|
for ($i=1; $i -le $maxRetries; $i++) {
|
||||||
$restartSucceeded = $false
|
|
||||||
|
|
||||||
while ($retryCount -lt $maxRetries -and -not $restartSucceeded) {
|
|
||||||
try {
|
try {
|
||||||
$healthUri = "https://$VCENTERHOST/rest/appliance/health/system"
|
Invoke-RestMethod -Uri "https://$VCENTERHOST/rest/appliance/health/system" `
|
||||||
Write-Log -Level "INFO" -Message "Checking vCenter REST health endpoint..." -Color "Cyan"
|
-Method Get -SkipCertificateCheck -ErrorAction Stop
|
||||||
Invoke-RestMethod -Uri $healthUri -Method Get -SkipCertificateCheck -ErrorAction Stop
|
|
||||||
|
|
||||||
$restartUri = "https://$VCENTERHOST/rest/appliance/system/services/vpxd?action=restart"
|
Invoke-RestMethod -Uri "https://$VCENTERHOST/rest/appliance/system/services/vpxd?action=restart" `
|
||||||
Write-Log -Level "INFO" -Message "Requesting vpxd service restart via REST..." -Color "Cyan"
|
-Method Post -SkipCertificateCheck -ErrorAction Stop
|
||||||
Invoke-RestMethod -Uri $restartUri -Method Post -SkipCertificateCheck -ErrorAction Stop
|
|
||||||
Show-Banner -Text "vpxd service restart requested successfully." -Type "SUCCESS"
|
Show-Banner "vpxd restarted successfully." SUCCESS
|
||||||
$restartSucceeded = $true
|
break
|
||||||
}
|
}
|
||||||
catch {
|
catch {
|
||||||
Write-Log -Level "WARN" -Message "vpxd REST endpoint not ready, retrying in 15 seconds... (Attempt $($retryCount+1)/$maxRetries)" -Color "Yellow"
|
Write-Log WARN "vpxd REST not ready, retry $i/$maxRetries..." Yellow
|
||||||
Start-Sleep -Seconds 15
|
Start-Sleep -Seconds 15
|
||||||
$retryCount++
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (-not $restartSucceeded) {
|
|
||||||
Show-Banner -Text "Automatic vpxd restart failed after $maxRetries attempts. Please restart manually via SSH." -Type "ERROR"
|
|
||||||
Write-Log -Level "ERROR" -Message "Manual restart: ssh root@$VCENTERHOST 'service-control --stop vpxd; service-control --start vpxd'" -Color "Red"
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
Write-Log -Level "INFO" -Message "Skipping vpxd restart because no certificate changes were applied." -Color "Green"
|
|
||||||
}
|
}
|
||||||
|
|
||||||
# ----------------------------
|
Show-Banner "Script complete. Log: $LogFile" INFO
|
||||||
# Completion message
|
|
||||||
# ----------------------------
|
|
||||||
Show-Banner -Text "Script completed. Check $LogFile and `$global:helpme for details if needed." -Type "INFO"
|
|
||||||
|
|||||||
Reference in New Issue
Block a user