如何在Azure Pipeline中获取Branch\Tag字段提交哈希作为变量
在Azure Pipeline中根据Branch/Tag输入设置commit变量的实现方法
可以通过脚本任务判断构建触发源是否为提交哈希(commit hash),进而设置目标变量,具体实现如下:
方法说明
当用户在流水线触发页面的Branch/Tag字段输入commit hash时,Azure Pipeline会自动将BUILD_SOURCEBRANCH环境变量设为refs/commits/<commit-hash>格式,同时BUILD_SOURCEVERSION会存储完整的commit hash值。我们可以利用这两个环境变量判断并设置$(commit)变量。
实现步骤
- 在Azure Pipeline YAML中添加PowerShell(或Bash)任务,放在需要使用
$(commit)变量的任务之前。 - 编写脚本逻辑:
- 默认将
commit变量设为none - 检查
BUILD_SOURCEBRANCH是否符合commit hash触发的格式 - 如果是,将
BUILD_SOURCEVERSION赋值给commit变量 - 通过Azure Pipeline日志命令输出变量,供后续任务使用
- 默认将
PowerShell脚本示例
steps: - task: PowerShell@2 displayName: 'Set commit variable' inputs: targetType: 'inline' script: | $commitValue = "none" # 判断是否为commit hash触发的构建 if ($env:BUILD_SOURCEBRANCH -like "refs/commits/*") { $commitValue = $env:BUILD_SOURCEVERSION } # 设置输出变量,后续任务可通过$(commit)引用 Write-Host "##vso[task.setvariable variable=commit;]$commitValue"
Bash脚本示例
若偏好使用Bash,可替换为以下脚本:
steps: - task: Bash@3 displayName: 'Set commit variable' inputs: targetType: 'inline' script: | commitValue="none" # 判断是否为commit hash触发的构建 if [[ "$BUILD_SOURCEBRANCH" == refs/commits/* ]]; then commitValue="$BUILD_SOURCEVERSION" fi # 设置输出变量 echo "##vso[task.setvariable variable=commit;]$commitValue"
验证方式
完成设置后,后续任务可直接通过$(commit)引用该变量,例如添加打印变量的任务:
- task: PowerShell@2 displayName: 'Print commit variable' inputs: targetType: 'inline' script: | Write-Host "Current commit value: $(commit)"
输入commit hash触发构建时会打印完整哈希值;选择分支或标签触发时则打印none。
内容的提问来源于stack exchange,提问作者Mor.sound
相关产品推荐
相关产品推荐

