At work we create our build/release through Azure Pipelines. We also label our sources, this means that after a successful build we create a tag in our git repository. This however fails sometimes, usually due to the fact that the tag already exists. The problem with that is that is still caused our builds to succeed. This isn’t what I wanted so I found a way to let it fail the build.

For this to work you need to make use of the GIT commandline on the agent. But the credentials aren’t stored by default in the agent. So we need to add  the following statement to our YAML:

- checkout: self 
  persistCredentials: true

Checkout self just means that we want to checkout the repository configured for the build. The magic happens in the persist credentials. This allows us to run GIT commands on the commandline with the correct credentials. To check if a tag exists we use the “git tag” command (more information here). You can find the yaml below:

- task: [email protected]
  displayName: "Check if GIT tag does not exist"
  inputs:
    targetType: 'inline'
    script: |

      $status =  (git tag -l "$(Build.BuildNumber)")
      
      if (![string]::IsNullOrWhitespace($status)) 
      { 
        Write-Host  "##vso[task.LogIssue type=error;]Tag '$status' already exsists in repository. Has this release been created before? Remove the tag first."
        exit 1

      }

We ask for a list of tags that match the name of the current build by passing the Devops Build variable “Build.BuildNumber”. If the result of that function isn’t an empty string the tag already exists and we create a error message in the build report and let the build fail.

Leave a Reply

Your email address will not be published. Required fields are marked *