【问题标题】:How to replace json file in release in VSTS CD?如何替换 VSTS CD 中发布的 json 文件?
【发布时间】:2018-07-04 10:21:46
【问题描述】:

在将构建部署到 UAT、生产等多个环境时。我想用 config.json 替换一个文件 config.uat.json 或 config.prod.json。有什么选择吗?就像我们有 XML 转换一样。

我知道 Json 变量替换,但这不符合我的目的,因为变量列表很长(几乎 50 个条目)

提前致谢!

【问题讨论】:

  • 为什么你认为 Json 变量替换不能达到你的目的?
  • 感谢您的回复,抱歉回复晚了。 Json 变量替换不是一个好的解决方案,因为列表很长,需要经常更新

标签: azure azure-devops azure-pipelines azure-pipelines-release-pipeline continuous-delivery


【解决方案1】:

JSON variable substitution 应该是一个不错的选择,如果你不想在Variables 标签上一一添加变量,你可以使用 VSTS REST API 更新它们,或者添加一个 powershell 脚本来设置变量。

否则,您可能需要删除 config.uat.json 或 config.prod.json,并将 config.json 复制到目标机器。

【讨论】:

    【解决方案2】:

    在您的Program.cs 文件中,您可以获得一个代表您当前环境的环境变量:

    var builder = WebHost.CreateDefaultBuilder(args);
    var currentEnv = builder.GetSetting("environnement");
    

    使用此currentEnv 值,您将能够加载文件config.{currentEnv}.json

    builder.AddJsonFile($"config.{currentEnv}.json", optional: false, reloadOnChange: true);
    

    编辑

    如果您想在 powershell 中执行此操作,您可以使用默认值对配置文件进行转换:appsettings.json 包含键,appsettings.env.json 包含覆盖。

    要转换您的配置,您可以执行以下操作:

    Param(
       [Parameter(Mandatory=$true)][string]$SpecificConfig
    )
    $defaultConfig = "AppSettings.json";
    $settingsContent = ConvertFrom-Json $defaultConfig;
    $specificContent = ConvertFrom-Json $SpecificConfig;
    
    # Do this on each <property> to override
    if (![string]::IsNullOrEmpty($specificContent.<property>))
    {
        $settingsContent.<property> = $specificContent.<property>;
    }
    Write-Host $settingsContent > $defaultConfig;
    

    【讨论】:

    • 我想到的解决方案之一,如果非常相似的话。我想知道是否有一种方法可以像 xml 转换一样进行 json 转换
    • 你可以,但据我所知,没有内置工具可以正确执行此操作。在 powershell 中,您可以使用 ConvertFrom-Json $file 加载 AppSettings.json。将进行编辑以完成答案。
    • 谢谢,我试试用powershell替换
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多