我有一个使用 Kubernetes 任务的部署管道:
- task: Kubernetes@1
displayName: 'Apply deployment'
inputs:
connectionType: '***'
namespace: '***'
command: 'apply'
useConfigurationFile: true
configuration: '$(System.DefaultWorkingDirectory)/deploy/kube/api/deployment.yaml'
secretType: 'generic'
此任务使用另一个 yaml 文件 (
deployment.yaml
)
我想更改我的 deployment.yaml
中的一些数据
为此我测试了Yaml writer
除了资源表之外,它的效果很好。 例子: 我有
deployment.yaml
:
spec:
template:
spec:
containers:
- name: api
image: 'imageVersion'
我想更改“图像”属性,这给了我们
spec.template.spec.containers[0].image
- task: YamlWriter@0
inputs:
file: '$(System.DefaultWorkingDirectory)/deploy/kube/api/deployment.yaml'
set: "spec.template.spec.containers['api'].image='my-image:latest'"
该值已被替换,但它还在
'containers[0]': {}
的末尾添加了 deployment.yaml
。
如何解决这个问题/您是否有任何替代方案可以解决此需求,而无需使用带有 sed 命令的脚本?
非常感谢🙏
在 Azure Pipelines 中使用 Yaml Writer 任务时,我可以重现相同的情况。它将在 YAML 文件末尾添加附加值
'containers[0]': {}
。似乎无法正确处理Yaml文件内资源表的内容。
如何解决此问题/您是否有任何替代方案可以解决此需求,而无需使用带有 sed 命令的脚本?
为了满足您的要求,您可以更改为使用以下方法:
方法1:您可以尝试使用替换令牌扩展中的替换令牌任务。
步骤如下:
Step1:在yaml文件中添加占位符,格式为:
${PipelinevariableName}#
例如:
spec:
template:
spec:
containers:
- name: api
image: '#{APIimageversion}#'
Step2:在Azure Pipeline中,您可以添加替换令牌任务并设置Pipeline变量(与占位符中的名称相同)。
例如:
variables:
APIimageversion: my-image:latest
- task: qetza.replacetokens.replacetokens-task.replacetokens@6
displayName: 'Replace tokens'
inputs:
root: '$(System.DefaultWorkingDirectory)/deploy/kube/api'
sources: deployment.yaml
结果:
方法2:如果您不想在 YAML 文件中使用占位符字符,可以使用 RegEx Match & Replace 扩展中的 RegEx Match & Replace 任务。
此任务将使用正则表达式来匹配文件中的字段。
这是一个例子:
spec:
template:
spec:
containers:
- name: api
image: 'imageVersion'
任务示例:
steps:
- task: RegExMatchReplace@2
displayName: 'RegEx Match & Replace'
inputs:
PathToFile: $(System.DefaultWorkingDirectory)/deploy/kube/api/deployment.yaml
RegEx: "image: '[A-Za-z]+'"
ValueToReplace: "image: 'my-image:latest'"
您可以使用此站点来转换正则表达式:Regex Generator