Search code examples
azure-devopsazure-pipelinesazure-pipelines-yamlcicd

Checkout CI commit id in CD pipeline, triggered by CI in Azure DevOps


I have a CI and CD pipeline - both .yaml files, running in Azure DevOps.

The CD pipeline is triggered when the CI pipeline completes:

resources:
  pipelines:
    - pipeline: ci
      source: "MyProject - CI"
      trigger:
        branches:
          include:
            - main
            - develop

In the CD pipeline I should have access to the source code as well, which I can do by using the Checkout task.

However, this task always takes the latest version of the source, and not the source that was the trigger of the CI pipeline.

Is there any way to access the CI's commit id, and use that version to checkout?


Solution

  • You can use rest api and powershell in your build. As an example, you can use Build.TriggeredBy.BuildId to get comment info of previous build:

    $token = "$(System.AccessToken)" 
    
    $base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f $user,$token)))
    $orgUrl = "$(System.CollectionUri)"
    $teamProject = "$(System.TeamProject)"
    
    $buildId = '$(Build.TriggeredBy.BuildId)'
    
    $restGetBuild = "$orgUrl/$teamProject/_apis/build/builds/$buildId`?api-version=6.0"
    
    function InvokeGetRequest ($GetUrl)
    {    
        return Invoke-RestMethod -Uri $GetUrl -Method Get -ContentType "application/json" -Headers @{Authorization=("Basic {0}" -f $base64AuthInfo)}
    }
    
    
    $result = InvokeGetRequest $restGetBuild
    
    $commit = $result.sourceVersion
    
    & git checkout $commit