Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TFS CI Build - Update custom define variable after build is succeed

We had set up my TFS CI Build, and we're managing one variable for our purposes to maintaining versioning, We want to update after every success build, any idea how to do so?

I had written PowerShell script

param([Int32]$currentPatchVersion)
Write-Host "Current patch version "$currentPatchVersion
$NewVersion=$currentPatchVersion + 1
Write-Host "New patch version "$NewVersion
Write-Host ("##vso[task.setvariable variable=PackageVersion.Patch;]$NewVersion")

but it just applies on the fly.

I want's to apply it on setting permanently.

like image 875
Nilesh Moradiya Avatar asked Jun 17 '16 11:06

Nilesh Moradiya


1 Answers

"##vso[task.setvariable variable=PackageVersion.Patch;]$NewVersion" just set the variable value in the build process, it doesn't set the value in the build definition level. If you want to update the variable value in the build definition permanently, you can call the Rest API to set the value of the variables in the definition. Refer to following section for details:

Create a "testvariable" as example: enter image description here

Create a Power Shell script with following code and upload it into source control:

[String]$buildID = "$env:BUILD_BUILDID"
[String]$project = "$env:SYSTEM_TEAMPROJECT"
[String]$projecturi = "$env:SYSTEM_TEAMFOUNDATIONCOLLECTIONURI"

$username="alternativeusername"
$password="alternativepassword"

$basicAuth= ("{0}:{1}"-f $username,$password)
$basicAuth=[System.Text.Encoding]::UTF8.GetBytes($basicAuth)
$basicAuth=[System.Convert]::ToBase64String($basicAuth)
$headers= @{Authorization=("Basic {0}"-f $basicAuth)}

$buildurl= $projecturi + $project + "/_apis/build/builds/" + $buildID + "?api-version=2.0"

$getbuild = Invoke-RestMethod -Uri $buildurl -headers $headers -Method Get |select definition

$definitionid = $getbuild.definition.id

$defurl = $projecturi + $project + "/_apis/build/definitions/" + $definitionid + "?api-version=2.0"

$definition = Invoke-RestMethod -Uri $defurl -headers $headers -Method Get

$definition.variables.testvariable.value = "1.0.0.1"

$json = @($definition) | ConvertTo-Json  -Depth 999

$updatedef = Invoke-RestMethod  -Uri $defurl -headers $headers -Method Put -Body $json -ContentType "application/json; charset=utf-8"

This script will get the current build definition and update the value of "testvariable" to "1.0.0.1". You need to enable alternative credential.

And then you can add a "PowerShell Script" task in your build definition to run this script.

like image 170
Eddie Chen - MSFT Avatar answered Nov 04 '22 18:11

Eddie Chen - MSFT