echo $(Build.SourceVersion)
set TestVar=$(Build.SourceVersion)
set MyCustomVar=%TestVar:~0,7%
echo %MyCustomVar%
echo ##vso[task.setvariable variable=ShortSourceVersion]%MyCustomVar%
In this case, we could get the short versions of Build.SourceVersion
and set it as environment variable.
Then we could set this command line task as a task group:
So, we could use this task to set the ShortSourceVersion
directly.
Hope this helps.
Can I substring a variable in Azure Pipelines?
Can I loop an Azure Pipelines task on a runtime array variable instead of an array parameter?
Can an Azure YAML Pipelines <deployment job> use variable environments?
How can I set, reset or over-write a variable in Azure Pipelines at runtime in Powershell?
In the Azure Pipelines PublishSymbols task, how can I use a variable as the searchPattern parameter?
how can I use IF ELSE in variables of azure DevOps yaml pipeline with variable group?
Can Conditional Variable Assignment be Done in Azure Pipelines?
Azure Pipelines using YAML for multiple environments (stages) with different variable values but no YAML duplication
Tell if a variable exists in template with azure pipelines
Cannot authorize variable group in Azure Pipelines
score:-2
Sure you can! If you absolutely must. Here is a runtime computation taking the first 7 characters of the Build.SourceVersion variable.
variables:
example: ${{ format('{0}{1}{2}{3}{4}{5}{6}', variables['Build.SourceVersion'][0], variables['Build.SourceVersion'][1], variables['Build.SourceVersion'][2], variables['Build.SourceVersion'][3], variables['Build.SourceVersion'][4], variables['Build.SourceVersion'][5], variables['Build.SourceVersion'][6]) }}
NB: I can't get it to work with $[
...]
syntax as the variable is apparently empty at the initial.
I know I'm a bit late to this party, but for anyone who comes by here and wants to avoid using Bash, PowerShell and similar, I've managed to do a substring with nothing but Azure Pipelines expressions.
(I'll definitely go straight to hell for writing this code)
Unfortunately, we can not index on string for some reason, so @dsschneidermann's answer does not work. But we can work around this using the split
function.
This definitely is more complex than using scripting, but is, on the other hand, run fully at the compile time.
Append some known character after each and every character in the original string using replace
. I.e., append _
, so that abc
becomes a_b_c_
.
Split the string using the appended character - split('a_b_c_', '_')
. The split
function returns an indexable array.
Use indexing on the array to compose the result
This, besides being unreadable, has the disadvantage that you have to specify all characters that might ever be part of the input value. Failing to do so might cause unexpected behavior. But for a git hash, it's enough to specify the whole alphabet, plus numerics.
The result is this:
- name: Build.SourceVersion.PreparedForSplit
value: ${{ replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(variables['Build.SourceVersion'], 'a', 'a_'), 'b', 'b_'), 'c', 'c_'), 'd', 'd_'), 'e', 'e_'), 'f', 'f_'), 'g', 'g_'), 'h', 'h_'), 'i', 'i_'), 'j', 'j_'), 'k', 'k_'), 'l', 'l_'), 'm', 'm_'), 'n', 'n_'), 'o', 'o_'), 'p', 'p_'), 'q', 'q_'), 'r', 'r_'), 's', 's_'), 't', 't_'), 'u', 'u_'), 'v', 'v_'), 'w', 'w_'), 'x', 'x_'), 'y', 'y_'), 'z', 'z_'), '0', '0_'), '1', '1_'), '2', '2_'), '3', '3_'), '4', '4_'), '5', '5_'), '6', '6_'), '7', '7_'), '8', '8_'), '9', '9_') }}
readonly: true
- name: Build.SourceVersion.Short
value: ${{ split(variables['Build.SourceVersion.PreparedForSplit'], '_')[0] }}${{ split(variables['Build.SourceVersion.PreparedForSplit'], '_')[1] }}${{ split(variables['Build.SourceVersion.PreparedForSplit'], '_')[2] }}${{ split(variables['Build.SourceVersion.PreparedForSplit'], '_')[3] }}${{ split(variables['Build.SourceVersion.PreparedForSplit'], '_')[4] }}${{ split(variables['Build.SourceVersion.PreparedForSplit'], '_')[5] }}${{ split(variables['Build.SourceVersion.PreparedForSplit'], '_')[6] }}
readonly: true
You might put these in a variable template and then, everywhere you need to use them, just include this template, what is a one line of code. So you end up with one hard-to-read code file, but other simple ones, and everything is processed at the template's compile time.
I've also created a PowerShell script for generating the intermediate variable:
# Input variable name
$VariableName = 'Build.SourceVersion'
# Known characters - should be every character that could appear in the input
$Chars = 'abcdefghijklmnopqrstuvwxyz0123456789'
# Character to be appended after every character in the input string
$IntermediateChar = '_'
$output = "variables['$VariableName']"
foreach ($Char in [char[]]$Chars) {
$output = "replace($output, '$Char', '$Char$IntermediateChar')"
Write-Host $output
You are right, there is no native way to do it. You will have to write a script to transform the variable.
Here is an example:
trigger:
- master
resources:
- repo: self
stages:
- stage: Build
displayName: Build image
jobs:
- job: Build
displayName: Build
pool:
vmImage: 'ubuntu-latest'
steps:
- task: CmdLine@2
inputs:
script: ' x=`echo "$(Build.SourceVersion)" | head -c 7`; echo "##vso[task.setvariable variable=MyVar]$x"'
- task: CmdLine@2
inputs:
script: 'echo "$(MyVar)"'
Here is the shortest version that I use for this job;
- bash: |
longcommithash=$(Build.SourceVersion)
echo "##vso[task.setvariable variable=shorthash;]$(echo ${longcommithash::9})"
It gives you the output as shown below;
On Azure devops it's possible to be done using batch technique indeed - like other answers propose in here - however I wanted to remove string from the end of string - and with batch this gets more complex ( See following link ).
Then I've concluded to use Azure's built-in expressions, for example like this:
- name: sourceBranchName
value: ${{ replace(variables['Build.SourceBranch'], 'refs/heads/') }}
replace
will have similar effect to substring - so it will remove unnecessary part from original string.
If however you want to concatenate some string and then remove it from original name - it's possible to be done using for instance format
function:
- name: originBranchName
value: ${{ replace(variables.sourceBranchName, format('-to-{0}', variables.dynamicvar ) ) }}
If dynamicvar
is a
- then function will remove -to-a
from branch name.
Related Query
Is there a way to parametrize/dynamically set variable group names in Azure DevOps Pipelines YAML?
How can I delete Azure DevOps old build pipelines and there leases with Power Shell
Can group name variable be dynamic in azure pipelines?
Is it possible to read or save in a variable the data returned by an Azure Pipelines script?
Use runtime variable for repository name in checkout in Azure Pipelines
Can an array variable defined in Azure DevOps "variable group"
Can variables in Azure Pipelines be used in NodeJS code?
How can I pass a variable to the SqlAzureDacpacDeployment@1 task in azure devops pipeline
how can use template for parameters in azure pipelines
Azure Pipelines - Build.SourceVersionMessage variable not working in expression function
Set variable in bash script and access in expression in Azure Pipelines
Azure Pipelines YAML - error when using variable group for "Deploy Web App" azureSubscription input
Azure Pipelines Set variable in script with string value that contains newline
Multiple Variable Groups in Azure Devops YAML pipelines
Can Azure DevOps build variable Build.Reason be used in YAML template compile time conditions?
How can I trigger a build in Azure pipelines by pushing tags to github
How to use a variable group in a Azure Pipelines yml template?
Azure Pipelines overwrite pipeline variable
Azure Pipelines parameter value from variable template
Loop through variables in variable group in Azure Pipelines
How to refer a variable in parameters block in azure pipelines
Conditionally use a variable group in azure pipelines
How can I use a secret variable in Azure Devops bash task which could be undefined
How can I configure Azure Pipelines to build an iOS project which uses OneSignal?
Azure pipelines variable for PR number of a merged pull request
Can I add more than one variable to an existing variable group in Azure DevOps?
How to pass variable template to extend template as a parameter in azure pipelines
How to use or access newly created pipeline variable inside a exe of C# so that i can assign value inside program in azure dev-ops build pipeline?
Azure Devops Release Pipelines - Variable to obtain the Source (build pipeline) value?
How can I cache Sonar plugins in Azure DevOps Pipelines so that they don't download everytime the pipeline runs?
How Can I Overwrite a List Variable Using Azure DevOps REST API?
How can I automatically link variable groups and agent pool when import release definitions to Azure DevOps?
Azure DevOps YAML Pipelines - can they pull a script from a repo?
Azure pipelines bash tries to execute the variable instead of expanding
How can I set a variable based on which agent is running an Azure DevOps build pipeline?
Azure Pipelines - Output variable from python script file to pipeline variable
Why can I not pass a runtime variable in if condition in azure devops yaml template
How can I add to the extended properties collection of a build in Azure Devops pipelines
Can Azure pipelines get source from TFS Service Connection?
Can I enforce the same variables across variable groups in the Azure DevOps Pipeline Library?
More Query from same tag
Docker fails to build in Azure Pipelines with "error MSB1001"
Compile go program with C dependency for Windows
tf.exe authenticate for vsts
Azure DevOps Pipelines - "nodejs: command not found" when running bash script
Build Docker with artifacts in Azure DevOps Pipeline
Azure Pipelines: Passing a variable as a parameter to a template
Using app_offline with TFS2015 RM
Per-month or per-minute billing of Azure Devops Pipelines parallel jobs
What are the "Pre-job" and "Post-job" tasks appearing in Azure DevOps Pipeline Logs?
Azure pipeline jobs queue by agent
How to store result of a AWS CLI command in Classic Azure DevOps Pipeline
SonarQube Error ECONNREFUSED when trying to build pipeline
Is caching npm ci in Azure Pipelines a bad idea?
Azure DevOps VSTest@2 isn't finding the correct test .dll to execute tests against
How to resolve "No hosted parallelism has been purchased or granted" in free tier?
Azure DevOps run a step only on certain days
How to use a Python script exit code as a condition for the following task in Azure Pipeline?
Is it possible to make Task Groups parameter values settable at release time?
How to handle special characters in Azure DevOps yaml pipeline?
Azure Pipeline: Pass System.Debug to a pwsh switch parameter
Connect-AzAccount : The term 'Connect-AzAccount' is not recognized as the name of a cmdlet, function, script file, or operable program
Unable to apply Git Tag in Azure pipeline cloud build. Works on local agent though
Azure DevOps with SonarCloud not finding tests
Getting Deployment triggered by User
Azure Pipelines Environments and Helm
The "Microsoft.CodeAnalysis.BuildTasks.Csc" task could not be loaded from the assembly
While scanning a simple key, could not find expected ':'. Syntax error in azure-pipeline.yaml
Is there a way to queue a VSTS build with SVN post commit hook?
Is it possible to write yaml pipeline script where a build stage having one job related to master branch and another job related to publish branch?
How to exclude everything that is not in the include - Azure DevOps YAML Pipeline
Azure DevOps pipelines - get build number of previous stage
VSTS Build - The replacement token 'version' has no value
Under what cases does a VSTS build produce an empty drop
Add Azure hosted build agents IP addresses to Analysis Services Firewall rules
ASP.NET Azure Web App Pipeline: No package found with specified pattern: D:\a\1\s\**\*.zip
Why does removing FetchData.razor from a default Blazor WASM project cause it to fail in Azure App Services?
Azure packages disappearing after installing it via ssh
Azure run from package (.zip) with parameters
How to add files and folders to an Azure Web App from within Visual Studio Code
Can you run Java SDK and .net core in the same Azure web app?
Font on React app not found when deployed on azure web app
com.google.api.gax.rpc.UnknownException in Springboot app deployed on Azure app service
PHP readfile content corruption on Azure Web App(Linux)
How to determine why a file upload did not happen in `az fs upload` when there are no error messages?
CycloneDx is not able to find project.assets.json file in correct path
I am using ExistsAsync to check whether the CloudBlockBlob is exists but it is taking too much time
function app/logic app to send json files from storage account to Event Hub in Azure
sync NAS based fileshare with Azure Storage container C#
Azure Blob Storage Returns 404 from Azure App Service
AZcopy help for sync two destination using database mapping
How to list blob names from 'a' to 'z' in Azure Python SDK?
Azure function does not access to Azure files share
Multiple users uploading into the same storage account via desktop app
Not seeing Azure Service Fabric application with Docker support template in Azure DevOps Portal
Azure powershell mention file path within inline script
How to generate a build artifact in Azure Devops through Powershell
Automatically update ARM templates when Swagger changes
How to deploy only delta changes/files in different environments?
CosmosDB database-level throughput using MongoDB API no longer requires sharded collections?
Getting an Incorrect Syntax Error in CosmosDB When Using BETWEEN Statement For ISO 8601 Formatted DateTime
Azure Cosmos Db document partition key having duplicate, but find duplicate document with combination of other columns