是否可以为管道模板中的阶段设置基于 System.PullRequest.TargetBranch 的条件?

Bas*_*ast 5 azure-devops azure-pipelines azure-pipelines-yaml azure-devops-pipelines

我有一个解决方案,其中 git 分支与环境直接相关(必须是这样,所以请不要讨论这是好还是坏,我知道这不是最佳实践)。

我们可以选择对环境运行验证部署(包括自动测试),而无需实际将解决方案部署到环境中。因此,我想设置一个管道,每当向该环境的分支打开拉取请求时,就为该环境运行此验证。此外,我对大部分管道使用了模板。主存储库中的实际管道只是一个指向另一个存储库中的模板管道的微小解决方案。该模板又针对每个各自的环境具有阶段。

我在主管道中成功添加了一个标识当前分支的解决方案,对于拉取请求,该解决方案应该是目标分支:

variables:
  - name: currentBranch
    ${{ if eq(variables['Build.Reason'], 'PullRequest') }}:
      value: $(System.PullRequest.TargetBranch)
    ${{ if ne(variables['Build.Reason'], 'PullRequest') }}:
      value: $(Build.SourceBranch)
Run Code Online (Sandbox Code Playgroud)

我想currentBranch通过参数将此变量发送到模板,因为我的模板管道根据分支有不同的阶段。我的解决方案是使用这样的管道:

extends:
  template: <template-reference>
  parameters:
    branch: $(currentBranch)
Run Code Online (Sandbox Code Playgroud)

...然后对于我的管道中的一个阶段执行以下操作:

- stage: TestAndDeployBranchName
    condition: eq('${{ parameters.branch }}', 'refs/heads/branchName')
    jobs:
      - job1... etc.
Run Code Online (Sandbox Code Playgroud)

基本上,如果当前分支是“branchName”,或者(对于拉取请求)当目标分支是“branchName”(来自发送到模板的“branch”参数)时,该阶段应该运行。

但是,我在这里看到不适System.PullRequest.TargetBranch用于模板,并且进一步看到当模板展开时,参数不适用于模板(变量为空)。因此,我的管道无法按预期工作(条件在应有的时候没有触发,即当分支名称匹配时)。

有什么方法可以System.PullRequest.TargetBranch在模板内的条件中使用,或者我应该寻找其他解决方案吗?

Bas*_*ast 4

经过进一步调查后,我得出的结论是我想做的事情是不可能的。

简而言之,System.PullRequest.TargetBranch(并且我假设其中至少有一些其他变量System.PullRequest在模板的编译时(即评估条件时)不可用。因此,不可能在模板的条件中使用这些变量。

由于我的目标是仅针对拉取请求运行某些步骤,因此基于拉取请求的目标分支,我通过创建重复的管道解决了这个问题。每个管道都是相同的,并且引用相同的模板,只是模板的输入参数不同。然后,我添加了每个“PR 管道”作为分支策略的一部分运行,每个分支都适用。

这很好用,但是如果我对另一个分支有相同的要求,它需要我创建一个新的管道。此外,我必须单独维护每个 PR 管道(这可能是好是坏)。

这不是一个理想的解决方案,但它确实有效。

参考公关渠道:

trigger: none # no trigger as PR triggers are set by branch policies

#This references the template repository to reuse the basic pipeline
resources:
  repositories:
  - repository: <template repo>
    type: git # "git" means azure devops repository
    name: <template name> # Syntax: <project>/<repo>
    ref: refs/heads/master # Grab latest pipeline template from the master branch

stages:
  - stage: VerifyPullRequest
    condition: |
      and(
        not(failed()), 
        not(canceled()), 
        eq(variables['Build.Reason'], 'PullRequest')
      )
    displayName: 'Verify Pull Request'
    jobs:
      - template: <template reference> # Template reference
        parameters:
          image: <image>
          targetBranch: <targetBranch> # Adjust this to match each respective relevant branch
Run Code Online (Sandbox Code Playgroud)

targetBranch参数用于模板中相关地方进行PR验证。

分支策略示例:(为每个相关分支进行设置) 分支策略设置图片