Azure Pipelines中通过BuildId查询构建产物对应管线SourceVersion咨询
解决方案
前置权限配置
首先需要为当前管线的服务账号配置对应权限,否则无法查询其他管线的运行数据:
- 进入对应项目的「项目设置」->「权限」,搜索账号「项目集合生成服务(你的组织名称)」
- 为该账号授予「生成」分类下的「读取生成」权限
变量定义示例
首先在YAML头部定义手动输入的三个管线BuildId参数:
parameters: - name: Repo1PipelineBuildId type: string displayName: 仓库1对应管线的BuildId - name: Repo2PipelineBuildId type: string displayName: 仓库2对应管线的BuildId - name: Repo3PipelineBuildId type: string displayName: 仓库3对应管线的BuildId
实现方式
方式1:通过Azure CLI查询(推荐)
使用Azure DevOps CLI的管线查询命令直接获取对应字段,无需手动处理认证逻辑:
- task: AzureCLI@2 inputs: azureSubscription: '你配置的Azure DevOps服务连接名' scriptType: 'bash' scriptLocation: 'inlineScript' inlineScript: | # 查询仓库1对应管线运行的SourceVersion REPO1_SOURCE_VERSION=$(az pipelines runs show --id ${{ parameters.Repo1PipelineBuildId }} --query "sourceVersion" -o tsv) echo "##vso[task.setvariable variable=Repo1SourceVersion]$REPO1_SOURCE_VERSION" # 查询仓库2对应管线运行的SourceVersion REPO2_SOURCE_VERSION=$(az pipelines runs show --id ${{ parameters.Repo2PipelineBuildId }} --query "sourceVersion" -o tsv) echo "##vso[task.setvariable variable=Repo2SourceVersion]$REPO2_SOURCE_VERSION" # 查询仓库3对应管线运行的SourceVersion REPO3_SOURCE_VERSION=$(az pipelines runs show --id ${{ parameters.Repo3PipelineBuildId }} --query "sourceVersion" -o tsv) echo "##vso[task.setvariable variable=Repo3SourceVersion]$REPO3_SOURCE_VERSION" addSpnToEnvironment: true
方式2:直接调用REST API查询
如果无法使用Azure CLI,可以直接调用Azure DevOps官方REST API获取数据:
- task: Bash@3 inputs: targetType: 'inline' script: | # 替换为你自己的组织名和项目名 ORG_NAME="你的组织名称" PROJECT_NAME="你的项目名称" # 查询仓库1对应SourceVersion RESPONSE=$(curl -s -u :$SYSTEM_ACCESSTOKEN "https://dev.azure.com/$ORG_NAME/$PROJECT_NAME/_apis/build/builds/${{ parameters.Repo1PipelineBuildId }}?api-version=7.0") REPO1_SOURCE_VERSION=$(echo $RESPONSE | jq -r '.sourceVersion') echo "##vso[task.setvariable variable=Repo1SourceVersion]$REPO1_SOURCE_VERSION" # 仓库2、仓库3的查询逻辑同上,替换参数即可 env: SYSTEM_ACCESSTOKEN: $(System.AccessToken)
后续使用说明
拿到三个RepoXSourceVersion变量后,你可以直接在后续的checkout步骤中指定对应仓库的commit版本完成检出,也可以自行构造对应仓库的commit链接输出到运行日志或自定义扩展字段,展示到管线运行的详情页。
内容的提问来源于stack exchange,提问作者FraS
相关产品推荐
相关产品推荐

