Is there a short 7-digit version of $(SourceVersion) in Azure Devops?
You can use traditional command substitution via backticks to obtain the short git hash (SHA-1), assuming that the code is being checked out in $(Build.SourcesDirectory)
:
- bash: |
short_hash=`git rev-parse --short=7 HEAD` ## At least 7 digits, more if needed for uniqueness
echo ""
echo "Full git hash: $(Build.SourceVersion)"
echo "Short git hash: $short_hash"
echo "##vso[task.setvariable variable=short_hash]$short_hash" ## Store variable for subsequent steps
workingDirectory: $(Build.SourcesDirectory)
displayName: Get short git hash
Output:
Full git hash: f8d63b1aaa20cf348a9b5fc6477ac80ed23d5ca0
Short git hash: f8d63b1
The following steps in the pipeline can then use the short hash via the variable $(short_hash)
.
(This is better than manually trimming down the full git hash to seven characters, since this will add extra digits if needed to uniquely identify the commit, see https://stackoverflow.com/a/21015031/1447415.)
Update: Improved version
The following improved version checks that the git hashes match (that the full hash starts with the short hash) and fails the step otherwise:
- bash: |
short_hash=`git rev-parse --short=7 HEAD`
echo ""
echo "Full git hash: $(Build.SourceVersion)"
echo "Short git hash: $short_hash"
echo ""
## Fail step if full hash does not start with short hash
if [[ $(Build.SourceVersion) != $short_hash* ]]; then
echo "--> Hashes do not match! Aborting."
exit 1
fi
echo "--> Hashes match. Storing short hash for subsequent steps."
## Store variable for subsequent steps
echo "##vso[task.setvariable variable=short_hash]$short_hash"
workingDirectory: $(Build.SourcesDirectory)
displayName: Get short git hash
- script: |
echo $sourceVersion
commitHash=${sourceVersion:0:7}
echo $commitHash
echo "##vso[task.setvariable variable=commitHash]$commitHash" ## Set variable for using in other tasks.
env: { sourceVersion: $(Build.SourceVersion) }
displayName: Git Hash 7-digit
workingDirectory: #workingDirectory
- task: Docker@2
displayName: Build & Push image
inputs:
command: 'buildAndPush'
containerRegistry: '$(myRegistry)'
repository: $(myContainerRepository)
Dockerfile: $(myDockerfile)
buildContext: '$(myBuildContext)'
tags: $(commitHash) ## The variable was defined above.
Here's example for vmImage: "ubuntu-latest". Step:
- Split 7-characters from Pre-defined GitHash
- Assign it to Pipeline variable. Don't confuse
$(azure_pipeline_variable) with ${bash_shell_variable} or $bash_shell_variable
. - Use it by $(commitHash)
Read more:
- Assign variable in Azure pipeline
- Using script in Azure pipeline