如何使用 Azure DevOps Services 管道 yaml 中的变量指定触发器

How to specify triggers using variables in Azure DevOps Services pipeline yaml

以下 azure pipeline 代码报错

'A template expression is not allowed in this context'

variables:
  major: 2020
  minor: 3
  patch: 1
  major_minor_patch: $(major).$(minor).$(patch)

trigger:
- master
- Dev
- release/R${{variables.major_minor_patch}}
- release/${{variables.major_minor_patch}}/*

我的意图是使用 major、minor 和 patch 变量来指定将形成 CI 触发器的分支,而不是在管道 YAML 中对其进行硬编码。

  1. 因为找不到解决我的情况的文档,我错过了什么?
  2. 如果我尝试做的事情不受支持,是否有建议的实现方法?

谢谢

我也没有找到这方面的证据,但我认为这是设计使然的正确行为。触发器是启动管道 运行 的东西。在运行发起之前,无法计算变量。当他们可以的时候,已经太晚了——整个事情都被触发了。

这就是为什么我认为您必须调整并尝试仅使用通配符来实现您的目标。如果应该为名称中包含版本的发布分支触发管道,也许这个通配符模式可能有效:release/R?.?.?

不支持触发器块中的变量。有关详细信息,请参阅文档 here

Trigger blocks can't contain variables or template expressions.

如果您不希望管道被其他分支触发,您可以尝试以下解决方法。

创建一个额外的管道来检查源分支是否匹配 release/major_minor_patch。并在此附加管道中触发主管道。

variables:
  major: 2020
  minor: 3
  patch: 1
  triggerMain: false

trigger:
 branches:
   include:
    - releases/*
       
steps:
- powershell: |
     $branch = "$(Build.SourceBranchName)"
     if ($branch -match "$(major).$(minor).$(patch)") {
       echo "##vso[task.setvariable variable=triggerMain]True"  #set variable triggerMain to true if matches.
     }

- task: TriggerBuild@3
  inputs:
    definitionIsInCurrentTeamProject: true
    buildDefinition: '56'  #{id of your main pipeline}
    queueBuildForUserThatTriggeredBuild: true
    ignoreSslCertificateErrors: false
    useSameSourceVersion: true
    useSameBranch: true
    waitForQueuedBuildsToFinish: false
    storeInEnvironmentVariable: false
    authenticationMethod: 'Personal Access Token'
    password: '$(system.accesstoken)'
    enableBuildInQueueCondition: false
    dependentOnSuccessfulBuildCondition: false
    dependentOnFailedBuildCondition: false
    checkbuildsoncurrentbranch: false
    failTaskIfConditionsAreNotFulfilled: false
  condition: eq(variables['triggerMain'], 'True')

在上面的管道中。它将首先被触发以检查源分支是否与 farmat 匹配。如果匹配,则执行任务TriggerBuild触发主管道。

我遇到了同样的问题,我的方法是这样的:

trigger:
  batch: true
  branches:
    include:
    - dev
    - master
    - releases/*

jobs:
  - job: Job    
    condition: eq(variables['Build.SourceBranch'], variables['TARGET_BRANCH'])
    steps: ...

在同一个管道上我做了一个条件作业,它在每个分支上被触发但它只执行我的目标分支中的步骤。