azure-devopsazure-pipelinesazure-pipelines-release-pipelineazure-pipelines-tasksazure-pipelines-release-task

How to add tag to a build from classic release after successful deployment to stage


I want to tag a build that is part of the release pipeline automatically after it is successfully deployed to a specific stage[Env].

This will help us deploy the same build in different release pipelines with the tag created as a filter.

We use multiple builds in the same release and we want to tag the latest build for each of them and remove the old tags which was created earlier in the process. so, only one tag will be attached to the build for specific releases.

We were using the task called "artefact tagger" but there is no support anymore for that task and it is EOL.


Solution

  • There is no functionality out-of-the-box to automatically add a tag for a build after a stage is released. Usually, a build tag is used for filtering the expected version of artifacts before deploying a stage in a release.

    Still, you may consider the workaround to call this API in a script of a release pipeline to add a tag for the build in which the artifacts files are published.

    PUT https://dev.azure.com/{organization}/{project}/_apis/build/builds/{buildId}/tags/{tag}?api-version=7.1
    

    Here is a sample PowerShell script for your reference. It retrieved the {buildId} with the value of the predefined variable $(Release.Artifacts.{alias}.BuildId) in a release. The artifacts alias was _Build1 in my sample. The script should run after the previous succeeded deployment step(s) to add a tag r-$(Release.ReleaseId)-$(Release.EnvironmentName) which was expanded as r-950-Dev as we could see in the screenshot below.

    $headers = @{
        'Authorization' = 'Bearer ' + '$(System.AccessToken)'
        'Content-Type' = 'application/json'
    }
    
    $tag = "r-$(Release.ReleaseId)-$(Release.EnvironmentName)"
    
    $URL = "$(System.TeamFoundationCollectionUri)/$(System.TeamProjectId)/_apis/build/builds/$(Release.Artifacts._Build1.BuildId)/tags/${tag}?api-version=7.1"
    
    Invoke-RestMethod -Method Put -Uri $URL -Headers $headers
    

    Image

    Image