Files
baiyue-firstleg/scripts/publish-nacos-config.ps1
2026-09-29 20:17:36 +08:00

33 lines
2.4 KiB
PowerShell

param(
[ValidateSet('test')][string]$Environment = 'test',
[Parameter(Mandatory)][string]$ServerAddr,
[string]$Group = 'BAIYUE',
[Parameter(Mandatory)][string]$Namespace,
[string]$Username = $env:NACOS_USERNAME,
[string]$Password = $env:NACOS_PASSWORD,
[switch]$DryRun
)
$ErrorActionPreference = 'Stop'
if ([string]::IsNullOrWhiteSpace($Namespace) -or $Namespace -eq 'public') { throw 'Supply the actual TEST Namespace ID, not public or a display name' }
$projectRoot = Split-Path -Parent (Split-Path -Parent $MyInvocation.MyCommand.Path)
$configRoot = Join-Path $projectRoot 'config/nacos/test'
$files = Get-ChildItem -LiteralPath $configRoot -File -Filter '*.yml' | Sort-Object @{Expression={if ($_.Name -eq 'baiyue-common.yml') {0} else {1}}}, Name
if ($files.Count -ne 14) { throw 'Expected common configuration and 13 retained services' }
if ($DryRun) { $files | ForEach-Object { Write-Host "Would publish $($_.Name) -> $Namespace / $Group" }; return }
if (-not $Username -or -not $Password) { throw 'NACOS_USERNAME and NACOS_PASSWORD are required' }
$base = "http://$ServerAddr/nacos"
$login = Invoke-RestMethod -Method Post -Uri "$base/v3/auth/user/login" -Body @{username=$Username; password=$Password} -TimeoutSec 10
if ([string]::IsNullOrWhiteSpace($login.accessToken)) { throw 'Nacos authentication failed' }
$namespaces = Invoke-RestMethod -Method Get -Uri "$base/v3/admin/core/namespace/list" -Body @{accessToken=$login.accessToken} -TimeoutSec 10
if ($null -eq $namespaces.code -or $namespaces.code -ne 0 -or
-not @($namespaces.data | Where-Object { $_.namespace -ceq $Namespace }).Count) {
throw 'Nacos TEST namespace ID was not found or namespace query failed'
}
foreach ($file in $files) {
$body = @{dataId=$file.Name; groupName=$Group; namespaceId=$Namespace; type='yaml'; content=(Get-Content -LiteralPath $file.FullName -Raw -Encoding UTF8); accessToken=$login.accessToken}
$pairs = foreach ($entry in $body.GetEnumerator()) { [uri]::EscapeDataString([string]$entry.Key) + '=' + [uri]::EscapeDataString([string]$entry.Value) }
$result = Invoke-RestMethod -Method Post -Uri "$base/v3/admin/cs/config" -ContentType 'application/x-www-form-urlencoded; charset=UTF-8' -Body ($pairs -join '&') -TimeoutSec 10
if ($null -eq $result.code -or $result.code -ne 0 -or $result.data -isnot [bool] -or $result.data -ne $true) { throw "Publish failed: $($file.Name)" }
Write-Host "Published $($file.Name) -> $Namespace / $Group"
}