如何在 Azure DevOps YAML 的条件下使用数组

Cra*_*aig 2 yaml azure devops

我有一个模板,它为每个环境定义了一组分支,以便我可以控制哪些分支导致部署到特定环境。例如,我想要部署到生产的唯一分支是 master,但对于 UAT,我想要 release、hotfix 和 master。我已经设置了一个父模板,它在“每个”循环中调用下游模板。在部署模板中,我想将允许的分支数组与当前分支进行比较,以确定是否继续。这是传递分支数组的父模板的一部分:

- template: pipeline-templates/environment-pipeline.yml
  parameters:
    envs: 
      - name: devtest
        branches: 
        - 'refs/heads/master'
        - 'refs/heads/develop'
        - 'refs/heads/hotfix/'
        - 'refs/heads/release/'
      - name: nightly
        branches: 
        - 'refs/heads/master'
        - 'refs/heads/develop'
        - 'refs/heads/hotfix/'
        - 'refs/heads/release/'
      - name: qa
        branches: 
        - 'refs/heads/master'
        - 'refs/heads/hotfix/'
        - 'refs/heads/release/'
      - name: prod
        branches: 
        - 'refs/heads/master'
Run Code Online (Sandbox Code Playgroud)

environment-pipeline.yml下面,然后调用每个环境的部署模板。

parameters:
  - name: envs # collection of environments to create/deploy
    type: object
    default:
      env:
        name: ''
        branches: []

stages:
- ${{ each env in parameters.envs }}:
  - template: deploy.yml
    parameters:
      environmentName: ${{ env.name }}
      onlyForBranches: ${{ env.branches }}
Run Code Online (Sandbox Code Playgroud)

以上一切工作正常(注意,我删除了很多 YAML 以简化示例)。下一阶段是对部署模板中的分支数组使用条件。这就是我希望它会起作用的方式,但没有。

parameters:
  environmentName: ''
  onlyForBranches: []

stages:
  - stage: branch_gate
    condition: and(succeeded(), in(variables['Build.SourceBranch'], ${{ parameters.onlyForBranches }}))

# then the deploy stages go here if above condition passes
Run Code Online (Sandbox Code Playgroud)

这会导致以下错误:

无法从数组转换为字符串。

有什么方法可以使这项工作,还是应该使用不同的方法?

小智 5

in不是要使用的功能。它接受 n 个参数,如果第一个参数等于其余参数中的任何一个,则为真:in('B', 'A', 'B', 'C') => true

尝试containsvalue代替:

condition: and(succeeded(), containsvalue(${{ parameters.onlyForBranches }}, variables['Build.SourceBranch']))