如何在 Team Services 中替换 JSON 文件的变量?

gog*_*gog 5 azure-devops

我坚持使用角度项目的发布变量替换。我有一个settings.json文件,我想替换一些变量:

{ 
    test : "variable to replace"
}
Run Code Online (Sandbox Code Playgroud)

我试图在市场上找到一些自定义任务,但所有任务似乎都只适用于 web.config 的 xml 文件。

Fre*_*ric 6

我使用市场https://marketplace.visualstudio.com/items?itemName=qetza.replacetokens 中的“替换代币”

您将所需的值定义为发布定义中的变量,然后添加替换令牌任务并为存储库中要替换值的所有目标文本文件配置通配符路径(例如:**/*.json)。被替换的令牌具有可配置的前缀和后缀(默认为“#{”和“}#”)。因此,如果您有一个名为constr的变量,则可以将其放入 config.json

{
   "connectionstring": "#{constr}#"
}
Run Code Online (Sandbox Code Playgroud)

它会像这样部署文件

{
   "connectionstring": "server=localhost,user id=admin,password=secret"
}
Run Code Online (Sandbox Code Playgroud)


Jus*_*ore 5

VSTS 版本中的 IIS Web 应用部署任务在 *文件转换和变量替换选项下具有 JSON 变量替换。\n为需要替换的变量提供 json 文件和 JSONPath 表达式的列表

\n\n

例如,要替换下面示例中 \xe2\x80\x98ConnectionString\xe2\x80\x99 的值,您需要在构建/发布定义(或发布定义\xe2\x80\x99s 环境)。

\n\n
{\n\xc2\xa0\xc2\xa0"Data": {\n\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0"DefaultConnection": {\n\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0"ConnectionString": "Server=(localdb)\\SQLEXPRESS;Database=MyDB;Trusted_Connection=True"\n\xc2\xa0\xc2\xa0\xc2\xa0\xc2\xa0}\n\xc2\xa0\xc2\xa0}\n}\n
Run Code Online (Sandbox Code Playgroud)\n


Mar*_*Liu 2

您可以在发布变量选项卡中添加变量,然后使用PowerShell任务来更新settings.json的内容。

假设原始内容是

{ 
    test : "old
}
Run Code Online (Sandbox Code Playgroud)

并且你想将其更改为

{ 
    test : "new"
}
Run Code Online (Sandbox Code Playgroud)

因此,您可以通过以下步骤替换 json 文件中的变量:

1.添加变量

使用要替换的值在发布变量选项卡中定义一个变量(使用 value 进行变量测试new):

在此输入图像描述

2.添加PowerShell任务

powershell任务的设置:

类型:内联脚本。

内联脚本:

# System.DefaultWorkingDirectory is the path like C:\_work\r1\a, so you need specify where your appsettings.json is.
$path="$(System.DefaultWorkingDirectory)\buildName\drop\WebApplication1\src\WebApplication1\appsettings.json"
(Get-Content $path) -replace "old",$(test) | out-file $path
Run Code Online (Sandbox Code Playgroud)

  • 这是否要求您知道以前的值,而不是属性名称?这是非常脆弱的。 (3认同)