根据运行时条件在 Azure Pipeline 中执行或不执行模板

maz*_*aze 11 azure-pipelines azure-pipelines-yaml

我已经运行了 Azure Pipeline。现在,我想仅当运行时某个条件成立时才执行一系列步骤。

例子

steps:
  - template: steps_checkout.yml
  # some more steps here

  - bash: |
    if [ some condition ]; then 
      echo "##vso[task.setVariable variable=rebuild_lib]false"
      echo "Did set rebuild_lib to false"
     fi

  - if eq( variables.rebuild_lib, true) ):
    - template: steps_lib_build.yml
Run Code Online (Sandbox Code Playgroud)

该行if eq( variables.rebuild_lib, true) )不起作用,因为它不是正确的条件语法。我可以用

${{ if eq( parameters.something, true ) }}
Run Code Online (Sandbox Code Playgroud)

但这需要在运行时知道。根据https://learn.microsoft.com/en-us/azure/devops/pipelines/process/expressions?view=azure-devops ,表达式也可以$[ if eq(variables.rebuild_lib), true]在运行时进行评估,但是使用这个,我得到

Unexpected value '$[ if eq( variables.rebuild_lib, true) ) ]'
Run Code Online (Sandbox Code Playgroud)

似乎 yml 不能在运行时以这种方式修改。

那么我如何决定在运行时使用模板呢?

我可以想象将变量作为参数传递给下一个模板adapter.yml。然后,该模板adapter.yml获取变量作为参数,并可以使用${{}}表达式,并再次使用下一个模板steps_lib_build.yml...但仅为此创建模板似乎不知何故...解决方法。

还使用类似的东西

- template: steps_lib_build.yml
  condition: ...
Run Code Online (Sandbox Code Playgroud)

不起作用。

有没有好的方法可以做到这一点?

Fel*_*lix 4

在当前的 yaml 中,您尝试使用参数来选择模板。但根据文档:Parameters to select a template at running,这仅在运行时使用。所以在这里,我们可以使用作业条件输出变量来帮助我们分离第二个yaml模板。

这是一个可以帮助您的演示 yaml 示例:

trigger: none

pool:
  vmImage: ubuntu-latest

jobs:
  - job: A
    steps:
    - task: Bash@3
      name: ProduceVar  # because we're going to depend on it, we need to name the step
      inputs:
        targetType: 'inline'
        script: 'echo "##vso[task.setVariable variable=rebuild_lib;isOutput=true]false"'
  - job: B
    condition: and(succeeded(), eq(dependencies.A.outputs['ProduceVar.rebuild_lib'], 'true'))
    dependsOn: A
    steps:
      # - script: echo Hello B
      - template: start.yaml
Run Code Online (Sandbox Code Playgroud)

请注意:我们应该使用任务Bash来帮助我们设置输出变量,因为我们将依赖于任务名称。