You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在GitHub Actions/PowerShell中动态处理JSON并关联GitHub Secrets

使用PowerShell动态转换Azure应用设置JSON为GitHub Secrets引用格式

核心脚本实现

以下PowerShell脚本可读取任意平级键值对结构的JSON文件,自动将每个键值对转换为$key = ${{ secrets.$key }}格式:

# 读取JSON文件并转换为PowerShell对象
$jsonFilePath = "C:\path\to\your\azure-appsettings.json"
$appSettings = Get-Content -Path $jsonFilePath -Raw | ConvertFrom-Json

# 转换为哈希表以便遍历所有键
$settingsHash = [hashtable]$appSettings

# 遍历生成目标格式字符串
foreach ($key in $settingsHash.Keys) {
    # 转义$符号确保GitHub Actions语法被原样输出
    Write-Output "$key = `${{ secrets.$key }}"
}

可选:将结果保存到文件

如果需要把转换后的内容持久化到文本文件,可添加输出逻辑:

$outputFilePath = "C:\path\to\output\secrets-references.txt"
# 清空目标文件(可选操作)
if (Test-Path $outputFilePath) { Remove-Item $outputFilePath }

foreach ($key in $settingsHash.Keys) {
    "$key = `${{ secrets.$key }}" | Out-File -Path $outputFilePath -Append -Encoding UTF8
}

嵌套JSON处理(针对特殊场景)

若你的JSON包含嵌套结构,可使用递归函数遍历所有层级的键:

function Convert-NestedSettings {
    param(
        [Parameter(Mandatory)]
        [hashtable]$Settings,
        [string]$ParentKey = ""
    )
    foreach ($key in $Settings.Keys) {
        $fullKey = if ($ParentKey) { "$ParentKey.$key" } else { $key }
        if ($Settings[$key] -is [hashtable]) {
            Convert-NestedSettings -Settings $Settings[$key] -ParentKey $fullKey
        } else {
            Write-Output "$fullKey = `${{ secrets.$fullKey }}"
        }
    }
}

# 调用递归函数处理嵌套JSON
Convert-NestedSettings -Settings $settingsHash

关键注意事项

  • 确保PowerShell拥有源JSON文件的读取权限和输出文件的写入权限
  • 脚本中用反引号`转义$符号,避免PowerShell将GitHub Actions语法解析为本地变量

内容的提问来源于stack exchange,提问作者wehelpdox

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 14:05:17