Azure DevOps YAML模板如何自动识别调用方仓库主分支?
自动获取Azure DevOps调用方仓库主分支名的解决方案
以下是几种无需手动传递主分支参数的实现方案,可直接在SharedTemplates的DoFancyStuff模板中使用:
方案1:通过Azure DevOps REST API获取仓库默认分支
利用Azure DevOps自带的系统变量和REST API,直接查询调用方仓库的默认分支配置,无需任何前置配置。
在模板中添加如下步骤,先获取默认分支名,再判断执行动作:
steps: - powershell: | $headers = @{ Authorization = "Bearer $(System.AccessToken)" } $repoApiUrl = "$(System.TeamFoundationCollectionUri)$(System.TeamProject)/_apis/git/repositories/$(Build.Repository.ID)?api-version=7.1-preview.1" $repoInfo = Invoke-RestMethod -Uri $repoApiUrl -Headers $headers -Method Get echo "##vso[task.setvariable variable=repoDefaultBranch;]$($repoInfo.defaultBranch -replace 'refs/heads/','')" displayName: '获取仓库默认分支' env: SYSTEM_ACCESSTOKEN: $(System.AccessToken) - script: | echo "执行动作A(主分支)" displayName: '执行动作A' condition: eq(variables['Build.SourceBranchName'], variables['repoDefaultBranch']) - script: | echo "执行动作B(非主分支)" displayName: '执行动作B' condition: ne(variables['Build.SourceBranchName'], variables['repoDefaultBranch'])
说明:
$(Build.Repository.ID):自动指向当前触发构建的调用方仓库ID$(System.AccessToken):管道自带的权限令牌,需确保构建服务账号有仓库读取权限- 提取分支名时去掉
refs/heads/前缀,和Build.SourceBranchName格式统一
方案2:在项目仓库定义仓库级变量
如果不想依赖API调用,可在每个项目仓库的管道设置中定义一次仓库级变量,模板直接引用:
- 进入项目仓库的Azure DevOps管道设置 → 变量 → 新建变量,命名为
mainBranchName,值设为对应仓库的主分支(如RepoXX设为dev,RepoYY设为master) - 在DoFancyStuff模板中直接使用该变量判断:
steps: - script: | echo "执行动作A(主分支)" displayName: '执行动作A' condition: eq(variables['Build.SourceBranchName'], variables['mainBranchName']) - script: | echo "执行动作B(非主分支)" displayName: '执行动作B' condition: ne(variables['Build.SourceBranchName'], variables['mainBranchName'])
优势:配置一次后所有管道都能复用,比手动传参数更简洁
方案3:通过Git命令获取默认分支
利用Git命令查询当前仓库的默认分支,无需依赖Azure DevOps API:
steps: - script: | git remote show origin | grep -i "HEAD branch:" | awk '{print $NF}' > default_branch.txt echo "##vso[task.setvariable variable=repoDefaultBranch;]$(cat default_branch.txt)" displayName: '获取Git默认分支' condition: eq(variables['Agent.OS'], 'Linux') - powershell: | $defaultBranch = (git remote show origin | Select-String "HEAD branch").Line.Split()[-1] echo "##vso[task.setvariable variable=repoDefaultBranch;]$defaultBranch" displayName: '获取Git默认分支' condition: eq(variables['Agent.OS'], 'Windows_NT') - script: | echo "执行动作A(主分支)" displayName: '执行动作A' condition: eq(variables['Build.SourceBranchName'], variables['repoDefaultBranch']) - script: | echo "执行动作B(非主分支)" displayName: '执行动作B' condition: ne(variables['Build.SourceBranchName'], variables['repoDefaultBranch'])
说明:需确保构建代理已安装Git,且能正常访问远程仓库(Azure DevOps构建代理默认已满足)
内容的提问来源于stack exchange,提问作者SimonAx
相关产品推荐
相关产品推荐

