#!/usr/bin/env pwsh . /opt/idssys/nodemgmt/conf/powerwall/settings.ps1 # ---------------------------- # Safe Failure Handler (cross-platform) # ---------------------------- function Show-Failure { param([System.Management.Automation.ErrorRecord]$ErrorRecord) $global:helpme = "" try { $ex = $ErrorRecord.Exception # HttpResponseMessage path (PowerShell Core) if ($ex.Response -is [System.Net.Http.HttpResponseMessage]) { $resp = $ex.Response if ($resp -and $resp.Content) { try { # Defensive read; won't deadlock and will catch disposed stream $global:helpme = $resp.Content.ReadAsStringAsync().GetAwaiter().GetResult() if ([string]::IsNullOrWhiteSpace($global:helpme)) { $global:helpme = "" } } catch { $global:helpme = "" } } else { $global:helpme = "" } } # Legacy WebResponse path elseif ($ex.Response -is [System.Net.WebResponse]) { try { $stream = $ex.Response.GetResponseStream() if ($stream) { $reader = [System.IO.StreamReader]::new($stream) $global:helpme = $reader.ReadToEnd() if ([string]::IsNullOrWhiteSpace($global:helpme)) { $global:helpme = "" } } else { $global:helpme = "" } } catch { $global:helpme = "" } } # Fallback to exception message else { $global:helpme = $ex.Message } } catch { # In case the extraction itself fails $global:helpme = "" } Write-Host -ForegroundColor Red "Status: A system exception was caught." Write-Host -ForegroundColor Red $global:helpme Write-Host -ForegroundColor Red "The request body has been saved to `$global:helpme" exit 1 } # ---------------------------- # Unified REST wrapper (TLS 1.2 + disable gzip + skip cert check) # ---------------------------- function Invoke-SafeRestMethod { param( [Parameter(Mandatory=$true)][string]$Uri, [string]$Method = 'Get', [hashtable]$Headers, $Body, [switch]$AsJson, [int]$TimeoutSeconds = 60 ) try { # Ensure headers object if (-not $Headers) { $Headers = @{} } # Avoid gzip → prevents GZipDecompressedContent disposal bugs if (-not $Headers.ContainsKey("Accept-Encoding")) { $Headers["Accept-Encoding"] = "identity" } # Ensure TLS1.2 (covers Windows & Pwsh where ServicePointManager is relevant) try { [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 } catch { # If not applicable on this platform, ignore } $params = @{ Uri = $Uri Method = $Method Headers = $Headers SkipCertificateCheck = $true ErrorAction = 'Stop' TimeoutSec = $TimeoutSeconds } if ($PSBoundParameters.ContainsKey('Body') -and $Body) { if ($AsJson) { # ConvertTo-Json can produce arrays/objects -- use moderate depth $params.Body = $Body | ConvertTo-Json -Depth 12 -Compress $params.ContentType = 'application/json' } else { $params.Body = $Body } } return Invoke-RestMethod @params } catch { Show-Failure -ErrorRecord $_ # Show-Failure calls exit 1, so code here shouldn't run, but keep for safety throw } } # ---------------------------- # Variables (from settings.ps1) # ---------------------------- $vCenterURL = $VCENTERHOST $CommonName = $VCENTERHOST $EmailContact = $ACMEEMAIL [PSCredential]$Credential = New-Object System.Management.Automation.PSCredential -ArgumentList $VCENTERUSER, (ConvertTo-SecureString $VCENTERPASS -AsPlainText -Force) # Posh-ACME / PowerDNS plugin args (PowerDNSApiKey as plain string) $pArgs = @{ PowerDNSApiHost = $WDNSHOST PowerDNSApiKey = $PDNSAPI PowerDNSUseTLS = $true PowerDNSPort = 443 PowerDNSServerName = 'localhost' } # ---------------------------- # Ensure Posh-ACME Module # ---------------------------- Write-Host "Checking for Required Module Posh-ACME" -ForegroundColor Green if (Get-Module -ListAvailable -Name Posh-ACME) { Write-Host "Posh-ACME Module Already Installed" -ForegroundColor Green } else { Write-Host "Posh-ACME Module Not Found, Installing..." -ForegroundColor Yellow Install-Module -Name Posh-ACME -Force -Confirm:$false Write-Host "Please restart this script after module install." -ForegroundColor Yellow exit 0 } # Try to import the module (force) and wait until available Import-Module -Name Posh-ACME -Force -ErrorAction Stop $maxWaitSec = 30 $waited = 0 Do { $PoshACME = Get-Module -Name Posh-ACME -ListAvailable if (-not $PoshACME) { Write-Host "Waiting for Posh-ACME Module to load..." -ForegroundColor Cyan Start-Sleep -Seconds 2 $waited += 2 } else { break } } While ($waited -lt $maxWaitSec) if (-not $PoshACME) { Write-Host "Posh-ACME failed to load within $maxWaitSec seconds." -ForegroundColor Red exit 1 } # ---------------------------- # vCenter API Session (Option A: POST with NO body) # ---------------------------- $loginUri = "https://$vCenterURL/rest/com/vmware/cis/session" try { $session = Invoke-SafeRestMethod -Uri $loginUri -Method Post -Headers @{ } # <-- no body (Option A) } catch { # Invoke-SafeRestMethod will call Show-Failure and exit on error exit 1 } # Extract session token $sessionToken = $null if ($session -and $session.value) { $sessionToken = $session.value } if (-not $sessionToken) { Write-Error "Unable to get Session Token, Terminating Script" exit 1 } Write-Host "Connected to vCenter API. Session established." -ForegroundColor Green # ---------------------------- # Example: Retrieve VMs # ---------------------------- $headers = @{ 'vmware-api-session-id' = $sessionToken } $vmList = Invoke-SafeRestMethod -Uri "https://$vCenterURL/rest/vcenter/vm" -Method Get -Headers $headers Write-Host "Retrieved VM list from vCenter:" -ForegroundColor Cyan if ($vmList -and $vmList.value) { $vmList.value | ForEach-Object { Write-Host " - $($_.name)" } } else { Write-Host "No VMs returned (empty result)" -ForegroundColor Yellow } # ---------------------------- # PowerDNS Integration (via Posh-ACME plugin args) # ---------------------------- Write-Host "Configuring PowerDNS with Posh-ACME" -ForegroundColor Green # Ensure plugin args are plain strings where required $pArgs = @{ PowerDNSApiHost = $WDNSHOST PowerDNSApiKey = $PDNSAPI PowerDNSUseTLS = $true PowerDNSPort = 443 PowerDNSServerName = 'localhost' } # ---------------------------- # Example ACME order with DNS plugin # ---------------------------- $certName = "vcenter-cert" try { Write-Host "Requesting certificate for $CommonName via Posh-ACME (PowerDNS plugin)" -ForegroundColor Cyan # This will create the order, perform DNS challenge via plugin args, and fetch certs New-PACertificate -Domain $CommonName -DnsPlugin PowerDNS -PluginArgs $pArgs -Contact $EmailContact -AcceptTOS -Verbose } catch { Show-Failure -ErrorRecord $_ exit 1 } # ---------------------------- # Push certificate back to vCenter # ---------------------------- try { $paAccount = Get-PAAccount -ErrorAction Stop $certFolder = $paAccount.CertFolder $certPath = Join-Path -Path $certFolder -ChildPath "$certName\cert.pem" $keyPath = Join-Path -Path $certFolder -ChildPath "$certName\privkey.pem" $chainPath = Join-Path -Path $certFolder -ChildPath "$certName\chain.pem" foreach ($p in @($certPath, $keyPath, $chainPath)) { if (-not (Test-Path -Path $p)) { Write-Host "Expected certificate file not found: $p" -ForegroundColor Red throw "Certificate file missing: $p" } } $body = @{ cert = (Get-Content -Path $certPath -Raw) key = (Get-Content -Path $keyPath -Raw) chain = (Get-Content -Path $chainPath -Raw) } $uploadUri = "https://$vCenterURL/rest/vcenter/certificate-management/vcenter/tls" $headers = @{ 'vmware-api-session-id' = $sessionToken } Invoke-SafeRestMethod -Uri $uploadUri -Method Post -Headers $headers -Body $body -AsJson Write-Host "New TLS certificate uploaded to vCenter" -ForegroundColor Green } catch { Show-Failure -ErrorRecord $_ exit 1 } # ---------------------------- # Apply certificate to vCenter # ---------------------------- try { $applyUri = "https://$vCenterURL/rest/vcenter/certificate-management/vcenter/tls?action=apply" $headers = @{ 'vmware-api-session-id' = $sessionToken } Invoke-SafeRestMethod -Uri $applyUri -Method Post -Headers $headers Write-Host "New TLS certificate applied to vCenter" -ForegroundColor Green } catch { Show-Failure -ErrorRecord $_ exit 1 } # ---------------------------- # Restart vCenter Services (optional) # ---------------------------- try { $restartUri = "https://$vCenterURL/rest/appliance/system/services/vpxd?action=restart" $headers = @{ 'vmware-api-session-id' = $sessionToken } Invoke-SafeRestMethod -Uri $restartUri -Method Post -Headers $headers Write-Host "vCenter service restart initiated (vpxd)" -ForegroundColor Yellow Write-Host "Note: UI/API may briefly be unavailable while services restart." -ForegroundColor Yellow } catch { Show-Failure -ErrorRecord $_ exit 1 } Write-Host "Script completed." -ForegroundColor Green