PowerShell 技能连载 - 配置即代码实践

适用于 PowerShell 7.0 及以上版本

在现代 DevOps 实践中,配置即代码(Configuration as Code, CaC)已经从一种理想化的口号变成了可落地的工程实践。无论是微服务应用的 appsettings.json,还是基础设施的 Terraform 状态文件,配置都以代码的形式被版本化管理、评审和自动化部署。PowerShell 作为 Windows 和跨平台自动化的利器,在配置即代码领域扮演着不可或缺的角色——它能解析、生成、验证和分发各种格式的配置文件。

企业环境中的配置管理面临着独特的挑战:开发、测试、预发布、生产四个环境各有一套参数,机密信息不能明文存储在仓库里,多台服务器的配置必须保持同步且可审计。手动维护这些配置极易出错,一次遗漏就可能导致生产事故。将配置纳入代码管理流程,通过 PowerShell 脚本实现配置的解析、合并、验证和漂移检测,可以有效降低人为失误的风险,让配置变更像代码变更一样可追溯、可回滚。

本文将从三个实战场景出发,演示如何用 PowerShell 构建一套完整的配置即代码工作流:第一,使用 YAML/JSON 作为配置源并通过 Schema 验证保证数据质量;第二,实现配置分层与深度合并,解决多环境配置管理的复杂性;第三,构建配置漂移检测与自动修正机制,确保系统始终处于期望状态。

YAML/JSON 配置模式与 Schema 验证

YAML 以其可读性优势成为配置文件的首选格式。PowerShell 7 原生支持 JSON,而对 YAML 的支持可以通过 powershell-yaml 模块实现。下面的代码演示了如何定义一套配置 Schema 并对配置文件进行自动化验证,确保开发人员提交的配置文件符合规范。

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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
# 定义配置 Schema(JSON Schema 格式)
$schema = @{
'$schema' = 'http://json-schema.org/draft-07/schema#'
title = 'Application Configuration Schema'
type = 'object'
required = @('application', 'server', 'database')
properties = @{
application = @{
type = 'object'
required = @('name', 'version')
properties = @{
name = @{ type = 'string'; minLength = 1 }
version = @{
type = 'string'
pattern = '^\d+\.\d+\.\d+(-[a-zA-Z0-9.]+)?$'
}
debug = @{ type = 'boolean'; default = $false }
}
}
server = @{
type = 'object'
required = @('port', 'host')
properties = @{
host = @{ type = 'string' }
port = @{ type = 'integer'; minimum = 1; maximum = 65535 }
enableSsl = @{ type = 'boolean'; default = $true }
maxConnection = @{ type = 'integer'; default = 100; minimum = 1 }
}
}
database = @{
type = 'object'
required = @('host', 'name')
properties = @{
host = @{ type = 'string' }
port = @{ type = 'integer'; default = 5432 }
name = @{ type = 'string' }
user = @{ type = 'string' }
password = @{ type = 'string' }
}
}
logging = @{
type = 'object'
properties = @{
level = @{ type = 'string'; enum = @('DEBUG', 'INFO', 'WARN', 'ERROR') }
path = @{ type = 'string' }
rotate = @{ type = 'boolean'; default = $true }
}
}
}
}

# 将 Schema 保存为 JSON 文件
$schemaPath = Join-Path $PSScriptRoot 'config-schema.json'
$schema | ConvertTo-Json -Depth 10 | Set-Content -Path $schemaPath -Encoding UTF8

# 创建示例 YAML 配置文件
$yamlContent = @"
application:
name: OrderService
version: 2.4.1
debug: false
server:
host: 0.0.0.0
port: 8080
enableSsl: true
maxConnection: 200
database:
host: db.internal.local
port: 5432
name: orders_db
user: app_user
password: `${VAULT:database/password}
logging:
level: INFO
path: /var/log/orderservice
rotate: true
"@

$configPath = Join-Path $PSScriptRoot 'config-base.yaml'
$yamlContent | Set-Content -Path $configPath -Encoding UTF8

# Schema 验证函数
function Test-ConfigSchema {
param(
[Parameter(Mandatory)]
[hashtable]$Config,

[Parameter(Mandatory)]
[hashtable]$Schema,

[string]$Path = 'root'
)

$errors = [System.Collections.Generic.List[string]]::new()

# 检查必填字段
if ($Schema.required) {
foreach ($field in $Schema.required) {
if (-not $Config.ContainsKey($field)) {
$errors.Add("[$Path] 缺少必填字段: $field")
}
}
}

# 检查属性类型和约束
if ($Schema.properties) {
foreach ($key in $Config.Keys) {
$propSchema = $Schema.properties[$key]
if (-not $propSchema) {
continue
}
$value = $Config[$key]
$currentPath = "$Path.$key"

if ($propSchema.type -eq 'object' -and $value -is [hashtable]) {
$childErrors = Test-ConfigSchema -Config $value -Schema $propSchema -Path $currentPath
$errors.AddRange($childErrors)
}
elseif ($propSchema.type -eq 'integer') {
if ($value -isnot [int] -and $value -isnot [long]) {
$errors.Add("[$currentPath] 类型错误: 期望 integer,实际为 $($value.GetType().Name)")
}
elseif ($propSchema.minimum -and $value -lt $propSchema.minimum) {
$errors.Add("[$currentPath] 值 $value 小于最小值 $($propSchema.minimum)")
}
elseif ($propSchema.maximum -and $value -gt $propSchema.maximum) {
$errors.Add("[$currentPath] 值 $value 大于最大值 $($propSchema.maximum)")
}
}
elseif ($propSchema.type -eq 'string') {
if ($propSchema.pattern -and $value -notmatch $propSchema.pattern) {
$errors.Add("[$currentPath] 值 '$value' 不匹配模式 '$($propSchema.pattern)'")
}
if ($propSchema.enum -and $value -notin $propSchema.enum) {
$errors.Add("[$currentPath] 值 '$value' 不在允许列表中: $($propSchema.enum -join ', ')")
}
}
elseif ($propSchema.type -eq 'boolean' -and $value -isnot [bool]) {
$errors.Add("[$currentPath] 类型错误: 期望 boolean,实际为 $($value.GetType().Name)")
}
}
}

return $errors
}

# 安装并导入 YAML 模块(如未安装)
if (-not (Get-Module -ListAvailable -Name 'powershell-yaml')) {
Install-Module -Name 'powershell-yaml' -Force -Scope CurrentUser
}
Import-Module 'powershell-yaml'

# 读取配置并验证
$configYaml = Get-Content -Path $configPath -Raw
$parsedConfig = ConvertFrom-Yaml -Yaml $configYaml
$validationErrors = Test-ConfigSchema -Config $parsedConfig -Schema $schema

if ($validationErrors.Count -eq 0) {
Write-Host "配置验证通过" -ForegroundColor Green
} else {
Write-Host "配置验证失败,发现 $($validationErrors.Count) 个错误:" -ForegroundColor Red
$validationErrors | ForEach-Object { Write-Host " - $_" -ForegroundColor Yellow }
}

执行结果示例:

1
配置验证通过

如果配置中存在错误(例如端口超出范围或版本号格式不对),输出如下:

1
2
3
配置验证失败,发现 2 个错误:
- [root.server.port] 值 99999 大于最大值 65535
- [root.application.version] 值 'v2.x' 不匹配模式 '^\d+\.\d+\.\d+(-[a-zA-Z0-9.]+)?$'

配置分层与深度合并

企业应用通常需要在基础配置之上叠加环境专属配置和机密注入。例如,开发环境使用本地数据库,生产环境使用集群数据库,而数据库密码则从 HashiCorp Vault 或 Azure Key Vault 动态获取。这就要求我们实现配置的分层加载和深度合并(Deep Merge)——当子层级的配置与基础配置有相同键时,子层级应覆盖基础配置的值,而非简单地替换整个节点。

下面的代码实现了一个完整的配置分层合并系统,支持基础配置、环境覆盖和机密注入三个层级。

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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
# 深度合并函数:递归合并两个 hashtable
function Merge-ConfigDeep {
param(
[Parameter(Mandatory)]
[hashtable]$Base,

[Parameter(Mandatory)]
[hashtable]$Override
)

$result = @{}
# 复制基础配置的所有键
foreach ($key in $Base.Keys) {
$result[$key] = $Base[$key]
}

# 用覆盖配置进行深度合并
foreach ($key in $Override.Keys) {
if ($result.ContainsKey($key) -and
$result[$key] -is [hashtable] -and
$Override[$key] -is [hashtable]) {
# 两个值都是 hashtable,递归合并
$result[$key] = Merge-ConfigDeep -Base $result[$key] -Override $Override[$key]
}
else {
# 否则直接覆盖
$result[$key] = $Override[$key]
}
}

return $result
}

# 从环境变量或 Vault 注入机密
function Resolve-ConfigSecrets {
param(
[Parameter(Mandatory)]
[hashtable]$Config
)

$secretPattern = '^\$\{VAULT:(.+)\}$'

function Invoke-RecursiveResolve {
param($Node)

if ($Node -is [hashtable]) {
$resolved = @{}
foreach ($key in $Node.Keys) {
$resolved[$key] = Invoke-RecursiveResolve -Node $Node[$key]
}
return $resolved
}
elseif ($Node -is [string] -and $Node -match $secretPattern) {
$secretPath = $Matches[1]
# 优先从环境变量读取
$envKey = $secretPath -replace '[/\\:.]', '_'
$envValue = [System.Environment]::GetEnvironmentVariable($envKey)
if ($envValue) {
Write-Verbose "从环境变量解析机密: $secretPath"
return $envValue
}
# 回退到模拟 Vault(实际环境中对接真实 Vault API)
Write-Verbose "从 Vault 解析机密: $secretPath"
return "[VAULT-RESOLVED:$secretPath]"
}
elseif ($Node -is [array]) {
return @($Node | ForEach-Object { Invoke-RecursiveResolve -Node $_ })
}
return $Node
}

return Invoke-RecursiveResolve -Node $Config
}

# 基础配置(所有环境共享)
$baseConfig = @{
application = @{
name = 'OrderService'
version = '2.4.1'
debug = $false
}
server = @{
host = '0.0.0.0'
port = 8080
enableSsl = $true
maxConnection = 100
}
database = @{
host = 'db.internal.local'
port = 5432
name = 'orders_db'
user = 'app_user'
password = '${VAULT:database/password}'
}
logging = @{
level = 'INFO'
path = '/var/log/orderservice'
rotate = $true
}
}

# 生产环境覆盖配置
$productionOverride = @{
server = @{
host = '10.0.1.50'
port = 443
enableSsl = $true
maxConnection = 500
}
database = @{
host = 'prod-db-cluster.internal.local'
user = 'prod_app_user'
}
logging = @{
level = 'WARN'
path = '/var/log/orderservice/prod'
}
}

# 开发环境覆盖配置
$devOverride = @{
application = @{
debug = $true
}
server = @{
host = 'localhost'
port = 3000
enableSsl = $false
maxConnection = 10
}
database = @{
host = 'localhost'
name = 'orders_db_dev'
}
logging = @{
level = 'DEBUG'
path = './logs'
}
}

# 构建不同环境的最终配置
$environments = @{
production = Merge-ConfigDeep -Base $baseConfig -Override $productionOverride
development = Merge-ConfigDeep -Base $baseConfig -Override $devOverride
}

foreach ($env in $environments.Keys) {
Write-Host "`n=== $env 环境 ===" -ForegroundColor Cyan
$resolvedConfig = Resolve-ConfigSecrets -Config $environments[$env]
$resolvedConfig | ConvertTo-Json -Depth 5
}

执行结果示例:

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
=== production 环境 ===
{
"application": {
"name": "OrderService",
"version": "2.4.1",
"debug": false
},
"server": {
"host": "10.0.1.50",
"port": 443,
"enableSsl": true,
"maxConnection": 500
},
"database": {
"host": "prod-db-cluster.internal.local",
"port": 5432,
"name": "orders_db",
"user": "prod_app_user",
"password": "[VAULT-RESOLVED:database/password]"
},
"logging": {
"level": "WARN",
"path": "/var/log/orderservice/prod",
"rotate": true
}
}

=== development 环境 ===
{
"application": {
"name": "OrderService",
"version": "2.4.1",
"debug": true
},
"server": {
"host": "localhost",
"port": 3000,
"enableSsl": false,
"maxConnection": 10
},
"database": {
"host": "localhost",
"port": 5432,
"name": "orders_db_dev",
"user": "app_user",
"password": "[VAULT-RESOLVED:database/password]"
},
"logging": {
"level": "DEBUG",
"path": "./logs",
"rotate": true
}
}

配置漂移检测与自动修正

配置漂移(Configuration Drift)是指系统实际运行状态逐渐偏离期望配置的现象。它可能由手动修改、补丁更新、临时调试等多种原因引起,是导致”在我机器上能跑”问题的根源之一。对于成熟的运维体系来说,检测和修正配置漂移是保障环境一致性的关键能力。

下面的代码实现了一个配置漂移检测框架,它会将期望配置与系统实际状态进行逐项对比,生成漂移报告,并支持自动修正和审计日志记录。

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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
# 配置漂移检测与修正引擎
class ConfigDriftDetector {
[string]$ConfigName
[hashtable]$DesiredState
[System.Collections.Generic.List[hashtable]]$Drifts
[System.Collections.Generic.List[hashtable]]$AuditLog

ConfigDriftDetector([string]$Name, [hashtable]$Desired) {
$this.ConfigName = $Name
$this.DesiredState = $Desired
$this.Drifts = [System.Collections.Generic.List[hashtable]]::new()
$this.AuditLog = [System.Collections.Generic.List[hashtable]]::new()
}

# 递归对比期望状态与实际状态
[void] CompareState(
[hashtable]$Desired,
[hashtable]$Actual,
[string]$Path
) {
foreach ($key in $Desired.Keys) {
$currentPath = if ($Path) { "$Path.$key" } else { $key }

if (-not $Actual.ContainsKey($key)) {
$this.Drifts.Add(@{
Path = $currentPath
Type = 'Missing'
Desired = $Desired[$key]
Actual = $null
Severity = 'High'
})
continue
}

$desiredVal = $Desired[$key]
$actualVal = $Actual[$key]

if ($desiredVal -is [hashtable] -and $actualVal -is [hashtable]) {
$this.CompareState($desiredVal, $actualVal, $currentPath)
}
elseif ($desiredVal -is [array] -and $actualVal -is [array]) {
$diff = Compare-Object $desiredVal $actualVal
if ($diff) {
$this.Drifts.Add(@{
Path = $currentPath
Type = 'ArrayDiff'
Desired = ($desiredVal -join ', ')
Actual = ($actualVal -join ', ')
Severity = 'Medium'
})
}
}
elseif ("$desiredVal" -ne "$actualVal") {
$severity = if ($currentPath -match 'password|secret|key') {
'Critical'
} elseif ($currentPath -match 'debug|log') {
'Low'
} else {
'Medium'
}
$this.Drifts.Add(@{
Path = $currentPath
Type = 'ValueMismatch'
Desired = "$desiredVal"
Actual = "$actualVal"
Severity = $severity
})
}
}
}

# 生成漂移报告
[string] GenerateReport() {
$sb = [System.Text.StringBuilder]::new()
[void]$sb.AppendLine("配置漂移报告 - $($this.ConfigName)")
[void]$sb.AppendLine("生成时间: $(Get-Date -Format 'yyyy-MM-dd HH:mm:ss')")
[void]$sb.AppendLine("漂移项数: $($this.Drifts.Count)")
[void]$sb.AppendLine('---')

if ($this.Drifts.Count -eq 0) {
[void]$sb.AppendLine('未检测到配置漂移,系统状态正常。')
}
else {
$severityOrder = @{ Critical = 0; High = 1; Medium = 2; Low = 3 }
$sorted = $this.Drifts | Sort-Object { $severityOrder[$_.Severity] }

foreach ($drift in $sorted) {
[void]$sb.AppendLine(
"[$($drift.Severity)] $($drift.Path)"
)
[void]$sb.AppendLine(
" 期望: $($drift.Desired) | 实际: $($drift.Actual)"
)
[void]$sb.AppendLine(" 类型: $($drift.Type)")
[void]$sb.AppendLine()
}
}
return $sb.ToString()
}

# 自动修正漂移并记录审计日志
[void] Remediate([hashtable]$ActualRef) {
foreach ($drift in $this.Drifts) {
$pathParts = $drift.Path.Split('.')
$current = $ActualRef

# 导航到父级节点
for ($i = 0; $i -lt $pathParts.Count - 1; $i++) {
$current = $current[$pathParts[$i]]
}

$leafKey = $pathParts[-1]
$oldValue = $current[$leafKey]
$current[$leafKey] = $drift.Desired

$this.AuditLog.Add(@{
Timestamp = Get-Date -Format 'yyyy-MM-dd HH:mm:ss'
Path = $drift.Path
OldValue = "$oldValue"
NewValue = "$($drift.Desired)"
Severity = $drift.Severity
Action = 'AutoRemediate'
})
}
}
}

# 定义期望配置
$desiredConfig = @{
application = @{
name = 'OrderService'
version = '2.4.1'
debug = $false
}
server = @{
host = '10.0.1.50'
port = 443
enableSsl = $true
maxConnection = 500
}
database = @{
host = 'prod-db-cluster.internal.local'
port = 5432
}
}

# 模拟当前实际配置(存在漂移)
$actualConfig = @{
application = @{
name = 'OrderService'
version = '2.3.0' # 版本落后
debug = $true # 调试模式未关闭
}
server = @{
host = '10.0.1.50'
port = 8080 # 端口错误
enableSsl = $false # SSL 被关闭
maxConnection = 500
}
database = @{
host = 'prod-db-cluster.internal.local'
port = 5432
}
}

# 执行漂移检测
$detector = [ConfigDriftDetector]::new('Production-OrderService', $desiredConfig)
$detector.CompareState($desiredConfig, $actualConfig, '')
Write-Host $detector.GenerateReport()

# 执行自动修正
Write-Host "`n正在执行自动修正..." -ForegroundColor Yellow
$detector.Remediate($actualConfig)

# 输出审计日志
Write-Host "`n审计日志:" -ForegroundColor Cyan
$detector.AuditLog | Format-Table -AutoSize

执行结果示例:

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
配置漂移报告 - Production-OrderService
生成时间: 2026-04-28 10:30:00
漂移项数: 4
---
[Critical] server.enableSsl
期望: True | 实际: False
类型: ValueMismatch

[High] application.version
期望: 2.4.1 | 实际: 2.3.0
类型: ValueMismatch

[Medium] server.port
期望: 443 | 实际: 8080
类型: ValueMismatch

[Low] application.debug
期望: False | 实际: True
类型: ValueMismatch


正在执行自动修正...

审计日志:

Timestamp Path OldValue NewValue Severity Action
--------- ---- -------- -------- -------- ------
2026-04-28 10:30:00 application.version 2.3.0 2.4.1 High AutoRemediate
2026-04-28 10:30:00 application.debug True False Low AutoRemediate
2026-04-28 10:30:00 server.port 8080 443 Medium AutoRemediate
2026-04-28 10:30:00 server.enableSsl False True Critical AutoRemediate

注意事项

  1. Schema 验证应在 CI 流水线中强制执行。将配置文件的 Schema 验证作为 Pull Request 的必经检查项,可以在配置进入主分支之前就拦截格式错误和遗漏字段,避免无效配置扩散到下游环境。

  2. 深度合并时注意数组合并策略。本文实现的深度合并对数组采用直接覆盖策略。如果业务要求数组进行并集合并(如白名单列表),需要在 Merge-ConfigDeep 函数中为数组类型添加专门的合并逻辑。

  3. 机密注入应与配置文件分离存储。示例中的 ${VAULT:path} 占位符机制确保机密不会出现在代码仓库中。生产环境中应对接 HashiCorp Vault、Azure Key Vault 或 AWS Secrets Manager 等专业机密管理工具,而非依赖环境变量。

  4. 漂移检测的频率需要根据业务场景调整。关键生产系统建议每小时检测一次,并配合告警通知(如 PagerDuty、企业微信)。非关键系统可以每天检测一次,配合每日巡检报告。

  5. 自动修正需设置白名单和审批机制。并非所有漂移都应该被自动修正——某些漂移可能是有意的应急措施。建议对修正操作设置严重级别白名单,High 和 Critical 级别自动修正,其他级别仅生成告警,由运维人员确认后再修正。

  6. 审计日志应持久化到不可篡改的存储。配置变更的审计日志是故障排查和安全合规的重要依据。建议将日志写入数据库(如 Elasticsearch)或对象存储(如 S3),并启用版本控制和防篡改保护。

PowerShell 技能连载 - YAML 与 TOML 配置处理

适用于 PowerShell 7.0 及以上版本

YAML 和 TOML 是现代配置文件的两大主流格式。YAML 以其可读性和丰富的数据类型支持,被 Kubernetes、Docker Compose、GitHub Actions 等广泛采用;TOML 则以简洁明了著称,是 Rust、Python 项目的首选配置格式。PowerShell 原生支持 JSON 和 XML,但处理 YAML 和 TOML 需要借助第三方模块。本文将讲解如何在 PowerShell 中高效处理这两种配置格式。

YAML 处理

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
# 安装 YamlDotNet 模块
Install-Module -Name powershell-yaml -Scope CurrentUser -Force

# 解析 YAML 字符串
$yaml = @"
server:
host: 0.0.0.0
port: 8080
ssl:
enabled: true
cert: /etc/ssl/cert.pem
key: /etc/ssl/key.pem

database:
host: db.internal
port: 5432
name: myapp
pool:
min: 5
max: 20
timeout: 30

logging:
level: info
file: /var/log/myapp.log
rotation:
max_size: 100MB
max_files: 10
"@

$config = $yaml | ConvertFrom-Yaml

# 访问配置值
Write-Host "服务器端口:$($config.server.port)"
Write-Host "SSL 启用:$($config.server.ssl.enabled)"
Write-Host "数据库连接池最大值:$($config.database.pool.max)"

# 读取 YAML 文件
$k8sDeployment = Get-Content "k8s/deployment.yaml" -Raw | ConvertFrom-Yaml
$k8sDeployment.metadata.name
$k8sDeployment.spec.replicas

# 修改 YAML 配置
$config.server.port = 9090
$config.logging.level = "debug"
$config.database.pool.max = 50

# 导出为 YAML
$updatedYaml = $config | ConvertTo-Yaml
Write-Host "更新后的配置:" -ForegroundColor Cyan
Write-Host $updatedYaml

执行结果示例:

1
2
3
4
5
6
7
8
9
10
服务器端口:8080
SSL 启用:True
数据库连接池最大值:20
更新后的配置:
server:
host: 0.0.0.0
port: 9090
ssl:
enabled: true
cert: /etc/ssl/cert.pem

YAML 配置文件管理

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
56
57
58
function Get-YamlConfig {
<#
.SYNOPSIS
读取 YAML 配置文件并支持环境变量替换
#>
param(
[Parameter(Mandatory)]
[string]$Path,

[string]$Environment
)

$content = Get-Content $Path -Raw
$config = $content | ConvertFrom-Yaml

# 环境变量替换 ${VAR_NAME} 格式
$config | ConvertTo-Yaml | ForEach-Object {
$pattern = '\$\{(\w+)\}'
while ($_ -match $pattern) {
$varName = $Matches[1]
$varValue = [System.Environment]::GetEnvironmentVariable($varName) ?? ''
$_ = $_ -replace "\`\{$varName\}", $varValue
}
}

return $config
}

# 合并多层配置
function Merge-YamlConfig {
param(
[string[]]$ConfigPaths
)

$merged = @{}

foreach ($path in $ConfigPaths) {
if (Test-Path $path) {
$config = Get-Content $path -Raw | ConvertFrom-Yaml
foreach ($key in $config.Keys) {
if ($merged[$key] -is [hashtable] -and $config[$key] -is [hashtable]) {
$merged[$key] = Merge-Hashtables $merged[$key] $config[$key]
} else {
$merged[$key] = $config[$key]
}
}
}
}

return $merged
}

# 按优先级合并配置:默认 < 环境 < 本地覆盖
$config = Merge-YamlConfig -ConfigPaths @(
"config/default.yaml"
"config/production.yaml"
"config/local.yaml"
)

执行结果示例:

1
# 配置合并按路径优先级覆盖

TOML 处理

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
# 安装 TOML 模块
Install-Module -Name PSToml -Scope CurrentUser -Force

# 解析 TOML 字符串
$toml = @"
[server]
host = "0.0.0.0"
port = 8080

[server.ssl]
enabled = true
cert = "/etc/ssl/cert.pem"

[database]
host = "db.internal"
port = 5432
name = "myapp"

[database.pool]
min = 5
max = 20

[logging]
level = "info"
file = "/var/log/myapp.log"

[[logging.rotation]]
max_size = "100MB"
max_files = 10
"@

$config = $toml | ConvertFrom-Toml

# 访问配置值
Write-Host "服务器端口:$($config.server.port)"
Write-Host "SSL 启用:$($config.server.ssl.enabled)"

# 读取 TOML 文件(如 Cargo.toml, pyproject.toml)
$cargoConfig = Get-Content "Cargo.toml" -Raw | ConvertFrom-Toml
Write-Host "项目名称:$($cargoConfig.package.name)"
Write-Host "版本:$($cargoConfig.package.version)"

# 修改并保存
$config.server.port = 9090
$updatedToml = $config | ConvertTo-Toml
Set-Content -Path "config_updated.toml" -Value $updatedToml

执行结果示例:

1
2
3
4
服务器端口:8080
SSL 启用:True
项目名称:my-rust-project
版本:0.1.0

格式转换工具

在配置管理中经常需要在不同格式间转换:

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
function Convert-ConfigFormat {
<#
.SYNOPSIS
在 JSON、YAML、TOML 之间转换配置格式
#>
param(
[Parameter(Mandatory)]
[string]$InputPath,

[ValidateSet('json', 'yaml', 'toml')]
[string]$From,

[ValidateSet('json', 'yaml', 'toml')]
[string]$To,

[string]$OutputPath
)

# 读取源文件
$content = Get-Content $InputPath -Raw
$data = switch ($From) {
'json' { $content | ConvertFrom-Json -AsHashtable }
'yaml' { $content | ConvertFrom-Yaml }
'toml' { $content | ConvertFrom-Toml }
}

# 转换为目标格式
$output = switch ($To) {
'json' { $data | ConvertTo-Json -Depth 10 }
'yaml' { $data | ConvertTo-Yaml }
'toml' { $data | ConvertTo-Toml }
}

# 输出
if ($OutputPath) {
Set-Content -Path $OutputPath -Value $output -Encoding UTF8
Write-Host "已转换:$InputPath ($From) => $OutputPath ($To)" -ForegroundColor Green
} else {
Write-Output $output
}
}

# YAML 转 JSON
Convert-ConfigFormat -InputPath "docker-compose.yaml" -From yaml -To json -OutputPath "docker-compose.json"

# TOML 转 YAML
Convert-ConfigFormat -InputPath "Cargo.toml" -From toml -To yaml -OutputPath "Cargo.yaml"

执行结果示例:

1
2
已转换:docker-compose.yaml (yaml) => docker-compose.json (json)
已转换:Cargo.toml (toml) => Cargo.yaml (yaml)

注意事项

  1. YAML 缩进:YAML 对缩进非常敏感,使用空格而非 Tab。生成 YAML 时注意保持一致的缩进风格
  2. TOML 类型限制:TOML 不支持 null 值,所有键必须有值
  3. 模块兼容性powershell-yamlPSToml 是社区模块,注意版本兼容性
  4. 大文件性能:YAML 解析比 JSON 慢,大型配置文件考虑使用 JSON 格式
  5. 安全风险:YAML 的锚点(anchor)和合并(merge)特性可能被利用,解析不受信任的 YAML 时需注意
  6. 配置验证:使用 JSON Schema 或自定义脚本验证配置文件的完整性和合法性

PowerShell 技能连载 - JSON 与 YAML 配置管理

适用于 PowerShell 7.0 及以上版本

在 DevOps 和基础设施即代码的实践中,配置文件管理是核心能力。无论是应用部署、容器编排还是 CI/CD 流水线,JSON 和 YAML 格式的配置文件无处不在。PowerShell 原生支持 JSON 的读写与转换,配合 powershell-yaml 模块也能轻松处理 YAML,包括 Kubernetes 风格的多文档格式。

本文将从实际场景出发,逐步介绍如何用 PowerShell 完成 JSON 配置读取与修改、YAML 解析、Schema 验证、模板渲染以及环境配置切换。

读取 JSON 配置

日常运维中,我们经常需要从 JSON 文件中提取特定的配置项。PowerShell 的 ConvertFrom-Json 可以将 JSON 文本转换为对象,然后用属性访问语法直接取值。下面封装了一个通用函数,支持按层级路径读取指定区段。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# 读取 JSON 配置文件,支持按层级路径提取指定区段
function Get-JsonConfig {
param(
[Parameter(Mandatory)]
[string]$Path,

[string[]]$Sections
)

# 读取原始内容并转换为 PowerShell 对象
$json = Get-Content $Path -Raw | ConvertFrom-Json

# 如果指定了区段路径,逐层深入取值
if ($Sections) {
$result = $json
foreach ($section in $Sections) {
$result = $result.$section
}
return $result
}

return $json
}

假设我们有一个应用配置文件 appsettings.json,内容如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
{
"server": {
"host": "0.0.0.0",
"port": 8080
},
"database": {
"host": "db.internal",
"port": 5432,
"name": "app_prod"
},
"logging": {
"level": "INFO",
"path": "/var/log/app.log"
}
}

读取整个配置或某个区段:

1
2
3
4
5
6
7
# 读取完整配置
$config = Get-JsonConfig -Path ".\appsettings.json"
$config.database.host

# 只读取数据库区段
$dbConfig = Get-JsonConfig -Path ".\appsettings.json" -Sections "database"
$dbConfig

执行结果示例:

1
2
3
4
5
db.internal

host port name
---- ---- ----
db.internal 5432 app_prod

修改 JSON 配置

读取只是第一步,更多时候我们需要修改配置项并写回文件。下面的函数支持用点号分隔的路径(如 database.host)来定位嵌套属性,并可选地在修改前备份原文件。

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
# 修改 JSON 配置,支持点号路径定位嵌套属性
function Set-JsonConfig {
param(
[Parameter(Mandatory)]
[string]$Path,

[Parameter(Mandatory)]
[hashtable]$Properties,

[switch]$Backup
)

# 可选:修改前备份原文件
if ($Backup) {
Copy-Item $Path "$Path.bak.$(Get-Date -Format 'yyyyMMddHHmmss')"
}

$json = Get-Content $Path -Raw | ConvertFrom-Json

# 遍历每个要修改的属性
foreach ($key in $Properties.Keys) {
$parts = $key -split '\.'
$obj = $json
# 逐层导航到父对象
for ($i = 0; $i -lt $parts.Count - 1; $i++) {
$obj = $obj.$($parts[$i])
}
# 设置最终属性值
$obj.$($parts[-1]) = $Properties[$key]
}

# 写回文件,深度设为 10 层以覆盖大多数嵌套结构
$json | ConvertTo-Json -Depth 10 | Set-Content $Path -Encoding UTF8
}

将数据库主机和日志级别修改为新值:

1
2
3
4
Set-JsonConfig -Path ".\appsettings.json" -Backup -Properties @{
"database.host" = "db-new.internal"
"logging.level" = "DEBUG"
}

执行结果示例:

1
2
3
4
5
6
7
# 原文件已备份为 appsettings.json.bak.20250402100000
# appsettings.json 中的值已更新
Get-Content .\appsettings.json | ConvertFrom-Json | Select-Object -ExpandProperty database

host port name
---- ---- ----
db-new.internal 5432 app_prod

读取 YAML 配置

YAML 在 Kubernetes、CI/CD 等场景中广泛使用。PowerShell 本身不支持 YAML,但 powershell-yaml 模块弥补了这个缺口。下面的函数封装了 YAML 读取逻辑,并在模块缺失时给出友好提示。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# 读取 YAML 配置文件(需先安装 powershell-yaml 模块)
function Get-YamlConfig {
param(
[Parameter(Mandatory)]
[string]$Path
)

# 检查模块是否已安装
if (-not (Get-Module -ListAvailable -Name powershell-yaml)) {
Write-Warning "需要安装 powershell-yaml 模块: Install-Module powershell-yaml -Scope CurrentUser"
return $null
}

Import-Module powershell-yaml
$content = Get-Content $Path -Raw
return $content | ConvertFrom-Yaml
}

使用方式很简单:

1
2
3
4
5
6
# 首次使用前安装模块(只需执行一次)
# Install-Module -Name powershell-yaml -Scope CurrentUser

# 读取 YAML 配置
$config = Get-YamlConfig -Path ".\config.yaml"
$config.server.host

执行结果示例:

1
0.0.0.0

解析 Kubernetes 多文档 YAML

Kubernetes 的资源清单文件通常包含多个文档,用 --- 分隔。标准的 YAML 解析器只处理第一个文档,因此需要先分割再逐一解析。下面的函数会将每个文档提取出 kindnamenamespace 等关键信息。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# 读取 Kubernetes 风格的多文档 YAML,提取每个资源的元数据
function Get-YamlMultiDocument {
param([Parameter(Mandatory)][string]$Path)

Import-Module powershell-yaml
$content = Get-Content $Path -Raw

# 按 --- 分割多文档,过滤空行
$documents = $content -split '(?m)^---\s*$' | Where-Object { $_.Trim() }

foreach ($doc in $documents) {
$yaml = $doc | ConvertFrom-Yaml
[PSCustomObject]@{
Kind = $yaml.kind
Name = $yaml.metadata.name
Namespace = $yaml.metadata.namespace
Content = $yaml
}
}
}

假设有一个 deploy.yaml 包含 Namespace 和 Deployment 两个资源:

1
2
3
4
5
6
7
8
9
10
11
12
apiVersion: v1
kind: Namespace
metadata:
name: my-app
---
apiVersion: apps/v1
kind: Deployment
metadata:
name: web-server
namespace: my-app
spec:
replicas: 3

解析结果如下:

1
Get-YamlMultiDocument -Path ".\deploy.yaml" | Format-Table Kind, Name, Namespace

执行结果示例:

1
2
3
4
Kind       Name        Namespace
---- ---- ---------
Namespace my-app
Deployment web-server my-app

Schema 验证

配置项的错误往往在运行时才暴露,提前做 Schema 验证可以有效减少故障。下面的函数支持必填检查、类型校验、长度限制、枚举值和正则匹配等规则。

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
# 对配置对象执行 Schema 验证
function Test-ConfigSchema {
param(
[Parameter(Mandatory)]
[PSCustomObject]$Config,

[Parameter(Mandatory)]
[hashtable]$Schema
)

$errors = @()

foreach ($rule in $Schema.GetEnumerator()) {
$key = $rule.Key
$constraints = $rule.Value
$value = $Config.$key

# 必填检查
if ($constraints.Required -and -not $value) {
$errors += "缺少必填字段: $key"
continue
}

if ($null -ne $value) {
# 类型检查
if ($constraints.Type -and $value.GetType().Name -ne $constraints.Type) {
$errors += "$key 类型错误: 期望 $($constraints.Type), 实际 $($value.GetType().Name)"
}
# 最小长度检查
if ($constraints.MinLength -and $value.Length -lt $constraints.MinLength) {
$errors += "$key 长度不足: 最小 $($constraints.MinLength)"
}
# 枚举值检查
if ($constraints.AllowedValues -and $value -notin $constraints.AllowedValues) {
$errors += "$key 值非法: $value, 允许值: $($constraints.AllowedValues -join ', ')"
}
# 正则匹配检查
if ($constraints.Pattern -and $value -notmatch $constraints.Pattern) {
$errors += "$key 格式不匹配: $($constraints.Pattern)"
}
}
}

if ($errors) {
Write-Host "配置验证失败:" -ForegroundColor Red
$errors | ForEach-Object { Write-Host " - $_" -ForegroundColor Yellow }
return $false
}

Write-Host "配置验证通过" -ForegroundColor Green
return $true
}

定义验证规则并执行检查:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# 定义 Schema 规则
$schema = @{
serverName = @{ Required = $true; Type = "String"; MinLength = 3 }
port = @{ Required = $true; Type = "Int32" }
environment = @{ Required = $true; AllowedValues = @("dev", "staging", "prod") }
database = @{ Required = $true; Pattern = "^[a-z][a-z0-9_]+$" }
}

# 构造配置对象(这里故意写错 environment 值)
$config = [PSCustomObject]@{
serverName = "prod-sql-01"
port = 1433
environment = "production"
database = "app_db"
}

Test-ConfigSchema -Config $config -Schema $schema

执行结果示例:

1
2
3
配置验证失败:
- environment 值非法: production, 允许值: dev, staging, prod
False

模板渲染

在管理 Nginx、HAProxy 等配置时,硬编码不利于多环境复用。模板渲染可以将占位符替换为实际值,还支持条件块来控制内容是否输出。

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
# 渲染配置模板,支持变量替换和条件块
function Resolve-ConfigTemplate {
param(
[Parameter(Mandatory)]
[string]$TemplatePath,

[Parameter(Mandatory)]
[hashtable]$Variables,

[string]$OutputPath
)

$template = Get-Content $TemplatePath -Raw

# 替换 {{变量名}} 占位符
foreach ($var in $Variables.GetEnumerator()) {
$template = $template -replace "\{\{$($var.Key)\}\}", $var.Value
}

# 处理条件块 {{#if VAR}}...{{/if}}
$template = [regex]::Replace(
$template,
'\{\{#if\s+(\w+)\}\}(.*?)\{\{/if\}\}',
{
param($m)
if ($Variables[$m.Groups[1].Value]) { $m.Groups[2].Value } else { "" }
},
[System.Text.RegularExpressions.RegexOptions]::Singleline
)

# 输出到文件或返回渲染结果
if ($OutputPath) {
$template | Set-Content $OutputPath -Encoding UTF8
Write-Host "配置已渲染: $OutputPath"
}

return $template
}

准备一个 Nginx 配置模板:

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
# 创建 Nginx 配置模板
$template = @"
server {
listen {{PORT}};
server_name {{HOST}};
{{#if SSL}}listen 443 ssl;
ssl_certificate {{SSL_CERT}};{{/if}}
location / {
proxy_pass http://{{BACKEND}};
}
}
"@

$template | Set-Content "$env:TEMP\nginx.tpl"

# 渲染模板:启用 SSL 的生产环境
Resolve-ConfigTemplate -TemplatePath "$env:TEMP\nginx.tpl" `
-Variables @{
PORT = "8080"
HOST = "app.example.com"
SSL = $true
SSL_CERT = "/etc/ssl/cert.pem"
BACKEND = "127.0.0.1:3000"
} `
-OutputPath ".\nginx.conf"

执行结果示例:

1
2
3
4
5
6
7
8
9
10
11
12
配置已渲染: .\nginx.conf

# 生成的 nginx.conf 内容:
server {
listen 8080;
server_name app.example.com;
listen 443 ssl;
ssl_certificate /etc/ssl/cert.pem;
location / {
proxy_pass http://127.0.0.1:3000;
}
}

环境配置切换

在不同环境(开发、预发布、生产)之间切换时,需要加载对应的配置并注入到环境变量中。下面的函数根据环境名称查找对应配置文件,将所有配置项导出为以 APP_ 为前缀的环境变量。

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
# 切换应用环境,加载对应配置并导出为环境变量
function Switch-AppEnvironment {
param(
[Parameter(Mandatory)]
[ValidateSet("dev", "staging", "prod")]
[string]$Environment,

[string]$ConfigDir = ".\config"
)

# 查找对应环境的配置文件
$configFile = Join-Path $ConfigDir "$Environment.json"

if (-not (Test-Path $configFile)) {
throw "配置文件不存在: $configFile"
}

$config = Get-JsonConfig -Path $configFile

# 将每个配置项导出为环境变量
foreach ($prop in $config.PSObject.Properties) {
[Environment]::SetEnvironmentVariable(
"APP_$($prop.Name.ToUpper())", $prop.Value, "Process"
)
}

# 写入当前环境标记
[Environment]::SetEnvironmentVariable("APP_ENV", $Environment, "Process")

Write-Host "已切换到 $Environment 环境" -ForegroundColor Green
return $config
}

在开发环境与生产环境之间切换:

1
2
3
4
5
6
# 切换到开发环境
Switch-AppEnvironment -Environment dev -ConfigDir ".\config"

# 查看加载的环境变量
$env:APP_ENV
$env:APP_SERVER_HOST

执行结果示例:

1
2
3
4
已切换到 dev 环境

dev
127.0.0.1

管理配置文件时,建议将敏感信息(密码、密钥)从配置文件中分离,使用环境变量或密钥管理服务替代。模板渲染前务必做 Schema 验证,避免无效配置上线。通过本文介绍的工具函数,你可以构建一套完整的配置管理流程:读取配置、Schema 校验、模板渲染、环境切换,覆盖从开发到生产的全链路。