如何:在 Azure DevOps YAML 中有条件地插入模板?

Vya*_*ava 13 azure-devops azure-pipelines azure-pipelines-yaml

以下是我尝试完成有条件插入模板的方法。根据要求,我想根据运行时提供的管道变量调用 fresh-deploy.yml 或 update.yml 。用户可以将名为“freshInstall”的变量编辑为 true 或 false。

主管道(入口点):

# azure-pipelines.yml
variables:
  shouldUpdate: 'false'

jobs:
  - job: TestJob
    pool:
      name: "Vyas' Local Machine"
    steps:
    - checkout: none
    - template: ./testIf.yml
      parameters:
        freshInstall: $(freshInstall)
Run Code Online (Sandbox Code Playgroud)

testif.yml:

# testIf.yml
parameters:
  - name: freshInstall
    type: string  # Can't be boolean as runtime supplied variable values ARE strings

steps:

  # set a preexisting variable valued 'false' to 'true'
  - powershell: |
      $shouldUpdate = 'true'
      Write-Host "##vso[task.SetVariable variable=shouldUpdate]$shouldUpdate"
    displayName: 'Set Should Update to $(shouldUpdate)'

  # Check if the parameter 'freshInstall' is passed in correctly
  - script: echo "Should freshInstall ${{ parameters['freshInstall'] }}"
    displayName: 'Is Fresh Install? ${{ parameters.freshInstall }}'

  # Should skip this
  - ${{ if eq(parameters.freshInstall, 'true') }}:
    - template: ./fresh-deploy.yml

  # Shoud include this
  - ${{ if eq(parameters.freshInstall, 'false') }}:
    - template: ./update.yml

  # Check variables vs parameters.  Include as per value set
  - ${{ if eq(variables.shouldUpdate, 'true') }}:
    - template: ./update.yml

  # Use all 3 syntaxes of variable access
  - script: echo "shouldUpdate is variables['shouldUpdate']"
    displayName: "Should Update? variables.shouldUpdate"
Run Code Online (Sandbox Code Playgroud)

fresh-deploy.yml 的模拟文件:

# fresh-deploy.yml
steps:
  script: echo 'Kick off fresh deploy!'
Run Code Online (Sandbox Code Playgroud)

update.yml 的模拟文件:

# update.yml
steps:
  script: echo 'Updating existing installation!'
Run Code Online (Sandbox Code Playgroud)

关键问题:预期是当变量“freshInstall”为 false 时插入 update.yml 模板并运行脚本。

很高兴知道:我还在检查如果它是变量而不是参数,我是否可以以某种方式让它工作。如果我能指出我在变量显示方面做错了什么,那就太好了。

结果如下: 在此输入图像描述

Luc*_*ico 19

这个解决方案现在对我有用:

- ${{ if eq(parameters.generateSwaggerFiles, true) }}:
    - template: generate-swagger-files.yaml
      parameters:
        appName: 'example'
        swaggerVersions:
          - v1
          - v2
Run Code Online (Sandbox Code Playgroud)

请在此处查看文档。


rav*_*ram 0

我认为您的问题现在已经解决,因为现在允许运行时参数为布尔值。查看运行时参数。我有一个类似的用例,并且能够使用它来实现它。