Visual Studio Team Services – Triggering A Build From A Build (Using PowerShell)

As of April 2016, Visual Studio Team Services (VSTS) does not support triggering a build from another build. This presents a problem if you want your setup to do something like start two builds from a single pull request onto a branch (because VSTS does not support starting multiple builds from one pull request trigger). Since I want to fire off a build whenever a pull request is made on the develop branch, I had to find my own solution.

Surprisingly, the solution I found is pretty simple: utilize the REST API provided by VSTS within a PowerShell script and run that as a build step within the build that is initially kicked off.

To do this, add a PowerShell step to your build definition and pass the script in through your source control, or write it inline.

vsts1

Be aware that there’s a fairly small character limit on inline scripts. The script below simply posts a build definition id (IOSBUILD_DEFINITIONID) to the API, which kicks off the build. It utilizes an OAuth token from within the build, so we don’t have to worry about credentials. The API response will be written to the build log (Refer to this page for a detailed explanation of the API).

$url = "$($env:SYSTEM_TEAMFOUNDATIONCOLLECTIONURI)$env:SYSTEM_TEAMPROJECTID/_apis/build/builds?api-version=2.0"
 
$body = "{ 'definition' : { 'id' : $env:IOSBUILD_DEFINITIONID }, 'sourceBranch' : '$env:BUILD_SOURCEBRANCH' }"
 
$type = "application/json"

$headers = @{
    Authorization = "Bearer $env:SYSTEM_ACCESSTOKEN"
}
 
Write-Host "URL: $url"
 
$definition = Invoke-RestMethod -Uri $url -Body $body -ContentType $type -Method Post -Headers $headers
 
Write-Host "Definition = $($definition | ConvertTo-Json -Depth 1000)”

Optionally (you could put the id in line with the script instead), set the build definition id of the target build in the source build’s variables. To find the target build id, check the target build’s variables for “system.definitionId”.

vsts2

Then head over to the Options tab and check “Allow Scripts to Access OAuthToken”.

vsts3

And that’s all you have to do. Simple, right?

Update: If you’d like to know how your build can check and report back the status of the build it triggered, check out this follow-up post by Nathan Wilkinson.

author avatar
Andrew Tarr Sr. Software Engineer
Andrew is constantly challenging himself to try new things, both professionally and personally. This attitude has served him well in his ten years of service in the Nebraska Army National Guard and at Don’t Panic Labs, where he has worked on mobile and web application development since 2014.

Related posts