270 lines
9.6 KiB
PowerShell
270 lines
9.6 KiB
PowerShell
#!/usr/bin/env pwsh
|
|
# -----------------------------------------------------------------------------------
|
|
# Linux-safe vCenter + Posh-ACME Script
|
|
# - Uses HttpClient with AutomaticDecompression disabled (Fix1)
|
|
# - Handles Posh-ACME + PowerDNS plugin
|
|
# - Uploads & applies certificates to vCenter
|
|
# -----------------------------------------------------------------------------------
|
|
|
|
. /opt/idssys/nodemgmt/conf/powerwall/settings.ps1
|
|
|
|
# ----------------------------
|
|
# Global variables for troubleshooting
|
|
# ----------------------------
|
|
$global:helpme = $null
|
|
$global:responseBody = $null
|
|
|
|
# ----------------------------
|
|
# Error handler (robust across platforms)
|
|
# ----------------------------
|
|
function Show-Failure {
|
|
param([System.Management.Automation.ErrorRecord]$ErrorRecord)
|
|
|
|
$global:responseBody = "<No response body available>"
|
|
|
|
try {
|
|
$ex = $ErrorRecord.Exception
|
|
|
|
if ($ex.Response -is [System.Net.Http.HttpResponseMessage]) {
|
|
$resp = $ex.Response
|
|
try {
|
|
$global:responseBody = $resp.Content.ReadAsStringAsync().GetAwaiter().GetResult()
|
|
}
|
|
catch {
|
|
$global:responseBody = "<Failed to read HTTP content: $($_.Exception.Message)>"
|
|
}
|
|
}
|
|
elseif ($ex.Response -is [System.Net.WebResponse]) {
|
|
try {
|
|
$stream = $ex.Response.GetResponseStream()
|
|
if ($stream) {
|
|
$reader = [System.IO.StreamReader]::new($stream)
|
|
$global:responseBody = $reader.ReadToEnd()
|
|
}
|
|
else {
|
|
$global:responseBody = "<WebResponse had no stream>"
|
|
}
|
|
}
|
|
catch {
|
|
$global:responseBody = "<Failed to read WebResponse: $($_.Exception.Message)>"
|
|
}
|
|
}
|
|
else {
|
|
$global:responseBody = $ex.Message
|
|
}
|
|
}
|
|
catch {
|
|
$global:responseBody = "<Error extracting failure detail: $($_.Exception.Message)>"
|
|
}
|
|
|
|
$global:helpme = $global:responseBody
|
|
|
|
Write-Host "----------------------------------------" -ForegroundColor Red
|
|
Write-Host "Status: A system exception was caught." -ForegroundColor Red
|
|
Write-Host $global:responseBody -ForegroundColor Red
|
|
Write-Host "The request/response body has been saved to `$global:helpme" -ForegroundColor Red
|
|
Write-Host "----------------------------------------" -ForegroundColor Red
|
|
|
|
exit 1
|
|
}
|
|
|
|
# ----------------------------
|
|
# HttpClient wrapper (TLS1.2, skip cert check, no decompression)
|
|
# ----------------------------
|
|
function Invoke-SafeRestMethod {
|
|
param(
|
|
[Parameter(Mandatory=$true)][string]$Uri,
|
|
[string]$Method = 'GET',
|
|
[hashtable]$Headers = @{},
|
|
$Body = $null,
|
|
[switch]$AsJson,
|
|
[int]$TimeoutSec = 60
|
|
)
|
|
|
|
try {
|
|
# Handler: disable automatic decompression
|
|
$handler = [System.Net.Http.HttpClientHandler]::new()
|
|
$handler.AutomaticDecompression = [System.Net.DecompressionMethods]::None
|
|
$handler.ServerCertificateCustomValidationCallback = { $true } # Skip cert check
|
|
|
|
$client = [System.Net.Http.HttpClient]::new($handler)
|
|
$client.Timeout = [System.TimeSpan]::FromSeconds($TimeoutSec)
|
|
|
|
# Add headers
|
|
foreach ($k in $Headers.Keys) {
|
|
$client.DefaultRequestHeaders.Remove($k) | Out-Null
|
|
$client.DefaultRequestHeaders.Add($k, $Headers[$k])
|
|
}
|
|
|
|
# Prepare content
|
|
if ($Body -ne $null) {
|
|
if ($AsJson) {
|
|
$jsonBody = $Body | ConvertTo-Json -Depth 12 -Compress
|
|
$content = [System.Net.Http.StringContent]::new($jsonBody, [System.Text.Encoding]::UTF8, 'application/json')
|
|
}
|
|
else {
|
|
$content = [System.Net.Http.StringContent]::new($Body)
|
|
}
|
|
}
|
|
else {
|
|
$content = $null
|
|
}
|
|
|
|
# Send request
|
|
$method = [System.Net.Http.HttpMethod]::$Method
|
|
$request = [System.Net.Http.HttpRequestMessage]::new($method, $Uri)
|
|
if ($content) { $request.Content = $content }
|
|
|
|
$response = $client.SendAsync($request).GetAwaiter().GetResult()
|
|
|
|
$respBody = $null
|
|
if ($response.Content -ne $null) {
|
|
$respBody = $response.Content.ReadAsStringAsync().GetAwaiter().GetResult()
|
|
}
|
|
|
|
if ($response.IsSuccessStatusCode) {
|
|
# Try to convert JSON if response body exists
|
|
if ($respBody -and $respBody.Trim().Length -gt 0) {
|
|
try { return $respBody | ConvertFrom-Json }
|
|
catch { return $respBody }
|
|
}
|
|
else {
|
|
return $respBody
|
|
}
|
|
}
|
|
else {
|
|
throw [System.Net.Http.HttpRequestException]::new("HTTP $($response.StatusCode): $($response.ReasonPhrase)", $null, $response)
|
|
}
|
|
}
|
|
catch {
|
|
Show-Failure -ErrorRecord $_
|
|
}
|
|
finally {
|
|
$client.Dispose()
|
|
$handler.Dispose()
|
|
}
|
|
}
|
|
|
|
# ----------------------------
|
|
# Variables
|
|
# ----------------------------
|
|
$vCenterURL = $VCENTERHOST
|
|
$CommonName = $VCENTERHOST
|
|
$EmailContact = $ACMEEMAIL
|
|
|
|
[PSCredential]$Credential = New-Object System.Management.Automation.PSCredential -ArgumentList $VCENTERUSER, (ConvertTo-SecureString $VCENTERPASS -AsPlainText -Force)
|
|
|
|
$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 (-not (Get-Module -ListAvailable -Name Posh-ACME)) {
|
|
Write-Host "Posh-ACME Module Not Found, Installing..." -ForegroundColor Yellow
|
|
Install-Module -Name Posh-ACME -Force -Confirm:$false -Scope AllUsers
|
|
}
|
|
Import-Module Posh-ACME -ErrorAction Stop
|
|
Write-Host "Posh-ACME module loaded." -ForegroundColor Green
|
|
|
|
# ----------------------------
|
|
# vCenter API Session (Option A)
|
|
# ----------------------------
|
|
$loginUri = "https://$vCenterURL/rest/com/vmware/cis/session"
|
|
Write-Host "Connecting to vCenter at $vCenterURL ..." -ForegroundColor Cyan
|
|
|
|
$sessionResponse = Invoke-SafeRestMethod -Uri $loginUri -Method Post -Headers @{}
|
|
if ($sessionResponse -is [string] -or -not $sessionResponse) {
|
|
# Session might be in header
|
|
$sessionToken = $null
|
|
try {
|
|
$httpclient = [System.Net.Http.HttpClient]::new()
|
|
$req = [System.Net.Http.HttpRequestMessage]::new([System.Net.Http.HttpMethod]::Post, $loginUri)
|
|
$resp = $httpclient.SendAsync($req).GetAwaiter().GetResult()
|
|
if ($resp.Headers.Contains("vmware-api-session-id")) {
|
|
$sessionToken = $resp.Headers.GetValues("vmware-api-session-id") | Select-Object -First 1
|
|
}
|
|
$httpclient.Dispose()
|
|
}
|
|
catch {
|
|
Show-Failure -ErrorRecord $_
|
|
}
|
|
}
|
|
else {
|
|
$sessionToken = $sessionResponse.value
|
|
}
|
|
|
|
if (-not $sessionToken) {
|
|
Show-Failure -ErrorRecord ([pscustomobject]@{ Exception = [System.Exception] "Unable to get vCenter session token" })
|
|
}
|
|
|
|
Write-Host "Connected to vCenter API. Session established." -ForegroundColor Green
|
|
|
|
# ----------------------------
|
|
# Retrieve VM list
|
|
# ----------------------------
|
|
$headers = @{ 'vmware-api-session-id' = $sessionToken }
|
|
$vmList = Invoke-SafeRestMethod -Uri "https://$vCenterURL/rest/vcenter/vm" -Headers $headers
|
|
if ($vmList.value) {
|
|
Write-Host "Retrieved VM list from vCenter:" -ForegroundColor Cyan
|
|
$vmList.value | ForEach-Object { Write-Host " - $($_.name)" }
|
|
}
|
|
|
|
# ----------------------------
|
|
# PowerDNS / Posh-ACME certificate
|
|
# ----------------------------
|
|
$certName = "vcenter-cert"
|
|
try {
|
|
New-PACertificate -Domain $CommonName -DnsPlugin PowerDNS -PluginArgs $pArgs -Contact $EmailContact -AcceptTOS -Verbose -Force
|
|
Write-Host "ACME certificate request completed." -ForegroundColor Green
|
|
}
|
|
catch {
|
|
Show-Failure -ErrorRecord $_
|
|
}
|
|
|
|
# ----------------------------
|
|
# Collect certificate paths
|
|
# ----------------------------
|
|
$paAccount = Get-PAAccount
|
|
$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 ($f in @($certPath, $keyPath, $chainPath)) {
|
|
if (-not (Test-Path $f)) { Show-Failure -ErrorRecord ([pscustomobject]@{ Exception = [System.Exception] "Certificate file missing: $f" }) }
|
|
}
|
|
|
|
# ----------------------------
|
|
# Upload certificate to vCenter
|
|
# ----------------------------
|
|
$uploadUri = "https://$vCenterURL/rest/vcenter/certificate-management/vcenter/tls"
|
|
$body = @{
|
|
cert = Get-Content -Path $certPath -Raw
|
|
key = Get-Content -Path $keyPath -Raw
|
|
chain = Get-Content -Path $chainPath -Raw
|
|
}
|
|
Invoke-SafeRestMethod -Uri $uploadUri -Method Post -Headers $headers -Body $body -AsJson
|
|
Write-Host "Certificate uploaded to vCenter." -ForegroundColor Green
|
|
|
|
# ----------------------------
|
|
# Apply certificate
|
|
# ----------------------------
|
|
$applyUri = "https://$vCenterURL/rest/vcenter/certificate-management/vcenter/tls?action=apply"
|
|
Invoke-SafeRestMethod -Uri $applyUri -Method Post -Headers $headers
|
|
Write-Host "TLS certificate applied." -ForegroundColor Green
|
|
|
|
# ----------------------------
|
|
# Restart vCenter vpxd service
|
|
# ----------------------------
|
|
$restartUri = "https://$vCenterURL/rest/appliance/system/services/vpxd?action=restart"
|
|
Invoke-SafeRestMethod -Uri $restartUri -Method Post -Headers $headers
|
|
Write-Host "vCenter vpxd service restart requested." -ForegroundColor Yellow
|
|
|
|
Write-Host "Script completed successfully." -ForegroundColor Green
|