是否可以以编程方式取消Azure DevOps管道作业?

时间:2020-05-27 13:16:24

标签: azure azure-devops azure-pipelines azure-pipelines-yaml

由于可以在Azure DevOps管道中停止单个步骤,所以:

echo "##vso[task.complete result=Succeeded;]DONE"

请参阅:https://github.com/microsoft/azure-pipelines-tasks/blob/master/docs/authoring/commands.md#task-logging-commands

是否还可以检查条件并据此停止整个管道运行或作业?

PS。我知道,您可以为工作设置条件,但就我而言,整个流程是单个工作,由于其他原因,将其拆分为多个工作没有意义。

2 个答案:

答案 0 :(得分:9)

您可以通过REST API取消构建:

trailing

这里有个例子:

IconButton

为此,您将获得输出:

enter image description here

如果出现此类错误:

PATCH https://dev.azure.com/atbagga/atbagga/_apis/build/Builds/120
Request content: {'status': 'Cancelling'}

请确保您的构建帐户具有停止构建的权限:

您将在本节中找到它:

enter image description here

enter image description here

请注意

您不能做的是将构建设置为完成。如果您这样做。整个管道仍将执行。因此,如果这不是您想要的,则需要为每个步骤添加条件,并在管道中预先设置一个输出变量,并以此方式忽略这些步骤。

steps:
- task: PowerShell@2
  name: ConditionalStep
  inputs:
    targetType: 'inline'
    script: |
      Write-Host "I'm here"
      Write-Host ('$(SomeVariable)' -eq 'Stop')
      if ('$(SomeVariable)' -eq 'Stop') {
        $uri = "https://dev.azure.com/thecodemanual/DevOps Manual/_apis/build/builds/$(Build.BuildId)?api-version=5.1"

        $json = @{status="Cancelling"} | ConvertTo-Json -Compress

        $build = Invoke-RestMethod -Uri $uri -Method Patch -Headers @{Authorization = "Bearer $(System.AccessToken)"} -ContentType "application/json" -Body $json

        Write-Host $build
      }
      Write-Host "And now here!"
    pwsh: true
- pwsh: Start-Sleep -Seconds 60    
- task: PowerShell@2
  inputs:
    targetType: 'inline'
    script: |
      $uri = "https://dev.azure.com/thecodemanual/DevOps Manual/_apis/build/builds/$(Build.BuildId)/timeline?api-version=5.1"

      Write-Host $uri

      # Invoke the REST call
      $build = Invoke-RestMethod -Uri $uri -Method Get -Headers @{Authorization = "Bearer $(System.AccessToken)"} -ContentType "application/json"

      $taskResult = $build.records | Where-Object {$_.name -eq "ConditionalStep" } | Select-Object result

      Write-Host $taskResult.result

    pwsh: true

答案 1 :(得分:0)

我知道调用 REST API 是一个很好的解决方案,根据官方文档。但是我不会调用 REST API,而是有条件地触发一个有语法错误的 python 脚本。构建将被记录为失败。

错误.py

py thon('I am a syntax error to abort the build')

pipeline.yaml

- ${{ if gt(length(parameters.X,10))}} :
  - bash: echo "Check the length of input -- ABORTING THE BUILD"
  - bash: python path/error.py
- bash : echo "build passed - length is less than 10"
相关问题