从触发的管道构建中获取触发管道的提交ID

时间:2020-11-09 15:42:13

标签: azure-devops

我有管道A,它在Develop分支上成功构建后会触发管道B。我想使用以下命令获取在Develop Branch上运行的Pipeline A构建的提交ID,但它没有确切的ID

 - bash: |
          COMMAND="$(echo '$(build.sourceversion)' | cut -c-7)"
          echo "##vso[task.setvariable variable=dockertag]$COMMAND"
        displayName: GetCommitID

请问我是否想念一些东西。预先感谢。

2 个答案:

答案 0 :(得分:0)

根据我的测试,尽管管道B是由管道A触发的,但管道A无法将提交ID直接传递给管道B。

因此变量build.sourceversion将不会显示正确的提交ID。

要解决此问题,您可以添加powershell任务以在管道A中将Rest Api运行到Update the Pipeline B definition

这里是一个例子:

在管道B中设置变量

enter image description here

管道A:

......
steps:
.....
- powershell: |
   $token = "PAT"
   
   $url="https://dev.azure.com/{OrganizationName}/{ProjectName}/_apis/build/definitions/{PipelineBDefinitionId}?api-version=6.0"
   
   $token = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes(":$($token)"))
   
   
   
   $response = Invoke-RestMethod -Uri $url -Headers @{Authorization = "Basic $token"} -Method Get -ContentType application/json
   
   
   $response.variables.test.value = "$(Build.SourceVersion)"
   
   echo $response.variables.test.value
   
   
   $updateurl = "https://dev.azure.com/{OrganizationName}/{ProjectName}/_apis/build/definitions/{PipelineBDefinitionId}?api-version=6.0"
   
   $json = @($response) | ConvertTo-Json -Depth 99
   
   $updatedef = Invoke-RestMethod -Uri $updateurl -Method Put -Body $json -ContentType "application/json" -Headers @{Authorization = "Basic $token"} 
  displayName: 'PowerShell Script'

管道B:$(test)可以显示完整的提交ID。

steps:
- powershell: |
   $COMMAND="$(echo '$(test)' | cut -c-7)"
   echo "##vso[task.setvariable variable=dockertag]$COMMAND"
  displayName: 'PowerShell Script'

- powershell: 'echo $(dockertag)'
  displayName: 'PowerShell Script'

结果:

enter image description here

答案 1 :(得分:0)

如果您使用管道资源作为触发器,您也可以直接引用提交 ID。查看文档:{​​{3}}

resources.pipeline.<Alias>.projectName
resources.pipeline.<Alias>.projectID
resources.pipeline.<Alias>.pipelineName
resources.pipeline.<Alias>.pipelineID
resources.pipeline.<Alias>.runName
resources.pipeline.<Alias>.runID
resources.pipeline.<Alias>.runURI
resources.pipeline.<Alias>.sourceBranch
resources.pipeline.<Alias>.sourceCommit
resources.pipeline.<Alias>.sourceProvider
resources.pipeline.<Alias>.requestedFor
resources.pipeline.<Alias>.requestedForID

有意义吗?