Thursday, September 3, 2020

AzureDevops: autocancel pipelines? How it is?

 Hi everyone!



In this topic I would like to disscuss very small feature, but very important for some projects.

Autocancal pull request. 

What it is, and what is the majour feature will be talking today!

So let's talk first of all, why we need cancel pull request (PR).
    Definetelly, if we talking about pull request in case with Azure Devops, we 100% is talking about GIT.
This is decentralize system. I remember the time, from TFS 2012, when become available git in TFS, and only one possible way to not cover each other is use web hook for git. If some one tried to push old branch to master (or other branch with policy), the system show to engineer the error: that branch is not new. "Please pull code from master branch and merge conflicts."
    But in some scenario, engineers would like to strick cancel pull request, if some one push new changes.
From my perspective of views it is not good practise. But any way Microsoft provide one interesting feature in azure pipelines (part YAML config):

pr: 
  autoCancel: true

This biggest misunderstanding about this feature from engineers side is that many people thinking that this parameter is completly close  pull request.

But in fact this parameter is cancel previous pipeline runs if new changes were pushed to the same pr.

One important moment! It cancel pipeline only inside same pull request. 

If you want to achieve cancel all builds, you need encapsulate in you pipeline this code:


- task: PowerShell@2

      inputs:
        targetType: inline
        script: |

          $header = @{ Authorization = "Bearer $(system.accesstoken)" }
          $buildsUrl = "$(System.TeamFoundationCollectionUri)$(System.TeamProject)/_apis/build/builds?api-version=5.1"
          echo $buildsUrl
          $builds = Invoke-RestMethod -Uri $buildsUrl -Method Get -Header $header

          $buildsToStop = $builds.value.Where({ ($_.status -eq 'inProgress') -and ($_.definition.name -eq "$(Build.DefinitionName)") -and ($_.id -ne $(Build.BuildId))})

          ForEach($build in $buildsToStop)
          {
            echo $build.id
            $build.status = "cancelling"
            $body = $build | ConvertTo-Json -Depth 10
            $urlToCancel = "$(System.TeamFoundationCollectionUri)$(System.TeamProject)/_apis/build/builds/$($build.id)?api-version=5.1"
            echo $urlToCancel
            Invoke-RestMethod -Uri $urlToCancel -Method Patch -ContentType application/json -Body $body -Header $header
          }


Have a good codding! See you! 

No comments:

Post a Comment