使用 shell 脚本在 DevOps 中通过替换字符串编辑文件

Edit the files with replacing string in DevOps using shell script

我已经在 DevOps 中为 Azure 数据工厂创建了一个构建管道,它将从 azure 存储库中获取文件。

在部署更改之前,我想替换构建工件中某些文件中的几个字符串值。

下面提到的是我遵循的步骤。

  1. 在存储库的根文件夹中添加了一个 shell 脚本文件。
  2. 创建了指向需要部署的存储库分支的构建管道。
  3. 创建了一个采用构建工件的发布管道。
  4. 在代理作业中添加了一个 shell 脚本,用于替换存储库中文件中的几个字符串值。

下面是存储库结构的屏幕截图。

在构建管道中发布工件后,下面是管道中已发布工件的结构。

我已将示例 shell 脚本添加到工件中已有的代理作业,如下所示

在运行发布版本时,我收到有关路径的以下错误,如下所示

如何使用 power shell 通过替换字符串值来更新工件中的文件。有谁知道如何指向工件中的文件和 运行 替换脚本。如果您可以通过选择文件名来共享示例替换脚本,那将会很有帮助。

Inside the shell script I am not able to go to the repo file location to replace the string value. How to redirect to the root folder of the repo from the shell script file?

请使用 workingDirectory 导航到您要执行脚本的位置。

- task: PowerShell@2
  inputs:
    filePath: '$(System.DefaultWorkingDirectory)\scripts\script.ps1'
    workingDirectory: '$(System.DefaultWorkingDirectory)\templates\'

你需要记住的是,为你的脚本提供完全限定的位置,并为你的 arm 文件所在的目录设置工作目录。

如果您正在寻找其他方法,您始终可以考虑在您的 arm 模板中创建参数,而不是替换值,只需将它们作为那些参数传递即可。

Is the above mentioned steps are correct for replacing a string value or do we need to publish the build first and then replace file from the artifact?

一切由你决定。您可以在创建工件之前替换 arm 文件中的字符串,或者在 运行 之前替换发布管道中的字符串。您可能会问自己的问题:

  • 我会在发布工件之前在替换字符串中存储一些秘密吗
  • 当我替换字符串时,我能否将这些字符串部署到任何环境,或者我需要再次进行替换

但是,请考虑添加参数。也许这是最好的方法。

How to update the files in the artifact by replacing the string values, using power shell. Does anyone have an idea how to point to the files in the artifact and run a replace script.

有一个很棒的扩展程序 Replace Tokens 可以满足您的要求。

通过这个任务,您可以直接select您想要替换的file/files字符串:

我们只需要在 repo 中将 .json 文件中的变量替换为 #{VarValue1}# 格式:

赞:

{
    "$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",
    "contentVersion": "1.0.0.0",
    "parameters": {
        "storageAccounts_leoteststorageaccount_name": {
            "defaultValue": "#{TestValue}#",
            "type": "String"
        }
    },

然后在“变量”选项卡上定义键的值:

测试结果为:

这个方法很简单,不需要考虑文件路径,大家可以试试

您在发布管道的 powershell 任务中看到的上述错误是因为您将 script path 指向 .sh1 文件,而 powershell 任务需要 .ps1 文件。即使您在 script path 字段中指定的路径值是正确的,如果文件不是 .ps1 文件,powershell 任务仍然会失败并出现错误。

如果脚本是bash脚本,你应该使用Bash任务而不是powershell任务。

您可以在 powershell 脚本中查看以下简单示例,以替换 artifacts 文件中的 json 值。参见 this thread

$json = Convertfrom-json (get-content "_Source_alias\artifactsName\arm_template.json")

$json.parameter.value = $(PipelineVariables)

ConvertTo-Json $json -Depth 4 | Out-File _Source_alias\artifactsName\arm_template.json -Force

如果您使用 ARM template deployment task 部署 arm 模板。此任务允许您通过配置 Template parameters 字段和 Override template parameters 字段来替换模板参数。见下文: