我有多个 Azure DevOps 管道文件,其中包含许多阶段,如下所示:
...
- stage: 'qa'
dependsOn:
- dev
condition: |
and
(
condition1,
condition2,
...,
startswith(variables['Build.SourceBranch'], 'refs/heads/development')
)
# This needs to stay the same
- stage: 'uat'
dependsOn:
- dev
condition: |
and
(
condition1,
condition2,
...,
startswith(variables['Build.SourceBranch'], 'refs/heads/development')
)
...
现在我们正在将所有这些文件更新为新的部署策略,我需要更改两件事 - dependentOn 子句和refs/heads/development
条件中的源分支 - 但仅限于 qa 阶段。
结果应该是这样的
...
- stage: 'qa'
dependsOn:
- build
condition: |
and
(
condition1,
condition2,
...,
startswith(variables['Build.SourceBranch'], 'refs/heads/main')
)
# This needs to stay the same
- stage: 'uat'
dependsOn:
- dev
condition: |
and
(
condition1,
condition2,
...,
startswith(variables['Build.SourceBranch'], 'refs/heads/development')
)
...
我能够很容易地完成第一部分 - 我知道该数组中始终只有一个项目。所以这会起作用sed "/stage: 'qa'/{ n; n; s/dev/build/g }" pipeline.yaml
但第二部分更难,可能有多个条件,我不知道要跳过多少行。
有没有办法告诉sed
只替换文件的一部分中的字符串,比如说字符串出现位置下方的 4 到 10 行stage: 'qa'
?
对于结构化数据,请使用结构感知处理器,而不是只能操作文本表示而无法查看/理解底层逻辑的文本处理器。
您可以使用 YAML 处理器mikefarah/yq,它也具有文本处理功能(适用于条件):
这可能对你有用(GNU sed):
制作阶段的集合
qa
,然后使用替换和反向引用来实现所需的结果。注意 使用双引号将 sed 命令括起来。这使得包含单引号以进行匹配和替换变得更容易。然而,它也会导致 shell 执行意外的操作,因此
!
需要转义否定 ( )(请参阅/.../M"\!"ba
),否则会调用 shell 历史记录。M
另请注意匹配阶段集合末尾时标志的使用。