Files
baiyue-firstleg/scripts/use-nacos-environment.ps1
2026-08-26 19:46:14 +08:00

75 lines
2.8 KiB
PowerShell

param(
[ValidateSet('local', 'dev', 'development', 'test')]
[string]$Environment,
[ValidateSet('cn', 'overseas')]
[string]$Region = 'cn',
[string]$NacosServerAddr,
[string]$NacosNamespace,
[string]$NacosUsername,
[string]$NacosPassword
)
$ErrorActionPreference = 'Stop'
$target = if ($Environment -eq 'development') { 'dev' } else { $Environment }
$defaults = @{
local = @{ Server = '127.0.0.1:8848'; CnNamespace = 'public' }
dev = @{ Server = '8.163.49.32:8848'; CnNamespace = $env:DEV_NACOS_NAMESPACE }
test = @{ Server = '8.163.30.128:8848'; CnNamespace = 'd99d7998-5bb0-4ffe-a2a0-1a564ce14463' }
}
$selected = $defaults[$target]
$serverAddr = if ($NacosServerAddr) { $NacosServerAddr } else { $selected.Server }
$namespace = if ($NacosNamespace) {
$NacosNamespace
} elseif ($target -eq 'local') {
'public'
} elseif ($Region -eq 'overseas') {
$regionNamespace = [Environment]::GetEnvironmentVariable("$($target.ToUpperInvariant())_OVERSEAS_NACOS_NAMESPACE")
if ($regionNamespace) {
$regionNamespace
} else {
[Environment]::GetEnvironmentVariable("$($target.ToUpperInvariant())_NACOS_NAMESPACE")
}
} else {
$selected.CnNamespace
}
$username = if ($NacosUsername) {
$NacosUsername
} elseif ([Environment]::GetEnvironmentVariable("$($target.ToUpperInvariant())_NACOS_USERNAME")) {
[Environment]::GetEnvironmentVariable("$($target.ToUpperInvariant())_NACOS_USERNAME")
} else {
'nacos'
}
$password = if ($NacosPassword) {
$NacosPassword
} elseif ([Environment]::GetEnvironmentVariable("$($target.ToUpperInvariant())_NACOS_PASSWORD")) {
[Environment]::GetEnvironmentVariable("$($target.ToUpperInvariant())_NACOS_PASSWORD")
} elseif ($target -eq 'local') {
'nacos'
} else {
$null
}
if (-not $namespace) {
throw "$target/$Region 必须通过 -NacosNamespace 或对应的 *_NACOS_NAMESPACE 环境变量指定 namespace"
}
if (-not $password) {
throw "$target 必须通过 -NacosPassword 或 $($target.ToUpperInvariant())_NACOS_PASSWORD 提供 Nacos 密码"
}
$env:NACOS_SERVER_ADDR = $serverAddr
$env:NACOS_NAMESPACE = $namespace
$env:NACOS_GROUP = 'BAIYUE'
$env:NACOS_USERNAME = $username
$env:NACOS_PASSWORD = $password
$env:SPRING_CLOUD_NACOS_CONFIG_NAMESPACE = $namespace
$env:SPRING_CLOUD_NACOS_DISCOVERY_NAMESPACE = $namespace
$env:SPRING_PROFILES_ACTIVE = if ($Region -eq 'overseas') { 'overseas' } elseif ($target -eq 'local') { 'dev' } else { 'cn' }
$env:BAIYUE_RUNTIME_ENVIRONMENT = $target
$env:BAIYUE_RUNTIME_REGION = $Region
Write-Host "Runtime environment: $target / $Region"
Write-Host "Nacos: $serverAddr; namespace: $namespace; group: BAIYUE"
Write-Host "Spring profiles: $env:SPRING_PROFILES_ACTIVE"
Write-Host 'Nacos password is loaded into the current process and is not printed.'