在构建时使用变量将条件插入YAML模板中的Azure DevOps

时间:2020-07-17 16:51:56

标签: azure-devops yaml multistage-pipeline

是否可以使用在管道(仪表板)中定义的变量来在YAML模板上使用条件插入进行操作:

我是说我有以下步骤:


- ${{ if eq(variables.['somevar'], '')}}:
    - task: Bash@3
      displayName: Var does not being declared
      inputs:
        targetType: 'inline'
        script: |
         echo "This is a step where the var 'somevar' does not being declared'
    - task: Bash@3
      displayName: Another Step
      inputs:
        targetType: 'inline'
        script: |
         echo "This is another step where the var 'somevar' does not being declared'

应在未声明变量时运行

enter image description here


- ${{ if ne(variables.['somevar'], '')}}:
    - task: Bash@3
      displayName: Var is being declared
      inputs:
        targetType: 'inline'
        script: |
         echo "This is a step where the var 'somevar' is being declared with some value'
    - task: Bash@3
      displayName: Another Step
      inputs:
        targetType: 'inline'
        script: |
         echo "This is another step where the var 'somevar' is being declared with some value'

这应该在声明变量时运行

enter image description here


我知道它存在Runtime参数,但是我不想每次(手动)运行管道时都使用它们。我希望某些管道在声明变量时运行某些步骤,而另一些未声明变量时,其他管道不会执行某些步骤。

我也知道它存在于每个步骤中,例如

condition: eq(variables.somevar, 'value')

但是我想在某些情况下使用条件插入来运行,就像上面示例中的许多步骤一样。一步之遥

1 个答案:

答案 0 :(得分:2)

当我声明了以下内容时,我希望某些管道运行某些步骤 变量,而其他一些管道在 变量未声明。

为什么不使用Runtime parameters?使用运行时参数,我们可以轻松满足您的要求。

无论如何,要通过使用变量来实现这一点,我们可以尝试为Yaml模板Specify condition

创建Yaml模板:

# File: somevar-nondeclared.yml
steps:
- task: Bash@3
  displayName: Var does not being declared
  inputs:
     targetType: 'inline'
     script: |
      echo "This is a step where the var 'somevar' does not being declared"
- task: Bash@3
  displayName: Another Step
  inputs:
     targetType: 'inline'
     script: |
      echo "This is another step where the var 'somevar' does not being declared"

# File: somevar-declared.yml
steps:
- task: Bash@3
  displayName: Var is being declared
  inputs:
    targetType: 'inline'
    script: |
     echo "This is a step where the var 'somevar' is being declared with some value"
- task: Bash@3
  displayName: Another Step
  inputs:
    targetType: 'inline'
    script: |
     echo "This is another step where the var 'somevar' is being declared with some value"

还有azure-pipelines.yml供您参考:

# File: azure-pipelines.yml

trigger: none

jobs:
- job: Linux
  pool:
    vmImage: 'ubuntu-latest'
  steps:
  - template: somevar-nondeclared.yml 
  condition: eq(variables['somevar'], '')

- job: Windows
  pool:
    vmImage: 'windows-latest'
  steps:
  - template: somevar-declared.yml
  condition: ne(variables['somevar'], '')

因此,如果您在运行管道时声明了变量,它将运行Windows作业。否则,它将在此示例中运行Linux作业。

enter image description here