1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
| function Invoke-TerraformMultiCloud { [CmdletBinding(SupportsShouldProcess=$true)] param( [Parameter(Mandatory=$true)] [ValidateSet('Azure','AWS','GCP')] [string[]]$CloudProviders, [string]$TfWorkingDir = '$PSScriptRoot/terraform' )
$stateReport = [PSCustomObject]@{ Timestamp = Get-Date -Format 'yyyy-MM-dd HH:mm:ss' DeploymentStatus = @{} ResourceCounts = @{} CrossCloudDependencies = @() }
try { $CloudProviders | ForEach-Object { if ($PSCmdlet.ShouldProcess("Initialize $_ provider")) { terraform -chdir=$TfWorkingDir init -backend-config="$_backend.hcl" } }
$planOutput = terraform -chdir=$TfWorkingDir plan -out=multicloud.tfplan $stateReport.DeploymentStatus['Plan'] = $planOutput -match 'No changes' ? 'Stable' : 'Pending'
if ($planOutput -match 'to add') { $applyOutput = terraform -chdir=$TfWorkingDir apply -auto-approve multicloud.tfplan $stateReport.DeploymentStatus['Apply'] = $applyOutput -match 'Apply complete' ? 'Success' : 'Failed' }
$tfState = terraform -chdir=$TfWorkingDir show -json | ConvertFrom-Json $stateReport.ResourceCounts = $tfState.resources | Group-Object provider_name | ForEach-Object {@{$_.Name = $_.Count}}
$stateReport.CrossCloudDependencies = $tfState.resources | Where-Object { $_.depends_on -match 'aws_|azurerm_' } | Select-Object type, provider } catch { Write-Error "多云部署失败: $_" terraform -chdir=$TfWorkingDir destroy -auto-approve }
$stateReport | Export-Csv -Path "$env:TEMP/MultiCloudReport_$(Get-Date -Format yyyyMMdd).csv" return $stateReport }
|