为自动管道动态设置参数值

时间:2021-02-17 20:32:50

标签: azure-devops continuous-integration azure-pipelines

如果我创建了一个参数,我可以在手动运行管道时设置它的值。但是当管道自动运行时,它使用默认值。当管道自动运行时(比如响应推送到存储库)有没有办法向它传递参数的值?

这是我玩的 yaml 文件。目标是能够控制在管道中运行哪些测试。

parameters:
  - name: testFiles
    type: string
    default: cypress/integration/first.spec.js

trigger:
  - azure-test

pool:
  vmImage: ubuntu-latest

steps:
  - task: NodeTool@0
    inputs:
      versionSpec: "10.x"
    displayName: "Install Node.js"

  - script: npm install
    displayName: "npm install"

  - script: npx cypress run --record --key [record key removed] --spec ${{ parameters.testFiles }}
    displayName: "run cypress"

1 个答案:

答案 0 :(得分:3)

<块引用>

当管道自动运行时(比如响应推送到存储库)有没有办法向它传递参数的值?

运行自动流水线时,只会使用默认参数值。

所以我们可以通过改变参数的默认值来实现这个需求。

根据我的测试,我找到了一个方便的方法:可以使用If expression来检查触发方式(手动或者CI)。然后就可以设置参数的值了。

注意:我们在定义参数时不能使用if表达式,所以需要使用变量来传递值。

您可以参考this ticket

这是我的例子:

trigger:
- master


variables:
   ${{ if eq( variables['Build.Reason'], 'IndividualCI' ) }}: 
    buildVersion: $(BUILD.SOURCEVERSIONMESSAGE)
   ${{ if ne( variables['Build.Reason'], 'IndividualCI' ) }}: 
    buildVersion: cypress/integration/first.spec.js

parameters:
  - name: testFiles
    type: string  
    default: $(buildVersion)


pool:
  vmImage: ubuntu-latest

steps:
- script: echo ${{ parameters.testFiles }}
  displayName: 'Run a one-line script'

变量$(Build.Reason)用于确认触发方式。

变量 $(BUILD.SOURCEVERSIONMESSAGE) 包含提交的消息。

步骤如下:

  1. 在仓库中推送更改时,需要添加注释。注释是测试文件路径。

enter image description here

  1. CI 触发的管道将获取此注释并将其设置为参数默认值。

enter image description here

在这种情况下,类似于手动运行管道来设置参数值。

当您手动运行管道时,它将使用定义的默认值。您也可以在手动运行管道时修改该值。

enter image description here

相关问题