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

12
这里是我尝试有条件地插入模板的方法。根据运行时提供的管道变量,我想要调用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)

测试if.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"

fresh-deploy.yml 的模拟文件:

# fresh-deploy.yml
steps:
  script: echo 'Kick off fresh deploy!'

update.yml 的模拟文件:

# update.yml
steps:
  script: echo 'Updating existing installation!'

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

值得注意的是:我还在检查是否可以将其作为变量而不是参数来使其工作。如果能指出我在变量显示方面做错了什么,那就太好了。

这是结果: enter image description here


我找到了这个链接,讲述了为什么它不起作用:运行时与编译时。然而,情况并不是那么明确。https://developercommunity.visualstudio.com/content/problem/653819/yaml-pipeline-conditional-insertion-does-not-work.html - Vyas Bharghava
在编译时,“Set Should Update to false”尚未运行,这意味着变量shouldUpdate的值仍为“false”。将“Should Update?”任务更改为-脚本:echo“shouldUpdate is $(shouldUpdate)” displayName:“Should Update?$(shouldUpdate)”,它将显示“shouldUpdate is true”。 完成:Should Update? false,这可能更容易理解。 - Yang Shen - MSFT
1
@YangShen-MSFT: 如果以下内容无法正常工作:
  • $[ if eq(${{ parameters.freshInstall }}, 'true') ]:
    • template: ./fresh-deploy.yml
- Vyas Bharghava
不好意思,必须在编译时进行操作,将其更改为$[ <expression> ]并不能改变该表达式必须在编译时的事实。您将会遇到错误:Unexpected Value - Yang Shen - MSFT
1
@YangShen-MSFT:如果您能提供一个解决方案来使用队列时间变量值实现条件插入,那将是非常棒的。谢谢! - Vyas Bharghava
2个回答

19

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

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

请在此处查看文档。


0

我认为你的问题现在已经解决了,因为运行时参数现在允许是布尔类型的。 请查看运行时参数。我有一个类似的用例,并且使用它成功实现了。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接