Tuesday, June 23, 2015

PowerShell : Trigger a release in Release Management from TFS builds

With TFS 2013, the default template provides the ability to extend the out of box capabilities by providing post build process scripts, that can be used to execute custom PowerShell scripts as part of the build process. With the combination of the post build scripts and the TF_BUILd environment variables its very easy to provide PowerShell customization and execute them during the build. In this post, we'll see how we can combine these together to trigger a release from Release management using the Orchestration service API from release management. If you want to see the details of the REST API, use Fiddler to tract the calls through the Release Management Client application.
I'm using the InitializeReleaseFromBuild API to trigger a release in Release Management. The formatted uri should look like http://RMSERVER:PortNumber/account/releaseManagementService/_apis/releaseManagement/OrchestratorService/InitiateReleaseFromBuild?teamFoundationServerUrl=”tfsserverurl"&teamProject="project"&buildDefinition="definition"&buildNumber="build”&targetStageName="targetStage”

Later using the ReleaseStatus API, we can query the status of the release.

$buildNumber = $env:TF_BUILD_BUILDNUMBER

$location = $MyInvocation.MyCommand.Name
 | Split-Path -Parent (Get-Variable MyInvocation -Scope Script).Value.MyCommand.Path

Push-Location $location

$server = [System.Uri]::EscapeDataString($tfsUrl)
$project = [System.Uri]::EscapeDataString($teamProject)
$definition = [System.Uri]::EscapeDataString($buildDefinition)
$build = [System.Uri]::EscapeDataString($buildNumber)
$targetStage = [System.Uri]::EscapeDataString($targetStageName)

$serverName = $rmserver + ":" + $port
$orchestratorService = "http://$serverName/account/releaseManagementService/_apis/releaseManagement/OrchestratorService"

$status = @{
    "2" = "InProgress";
    "3" = "Released";
    "4" = "Stopped";
    "5" = "Rejected";
    "6" = "Abandoned";

$uri = "$orchestratorService/InitiateReleaseFromBuild?teamFoundationServerUrl=$server&teamProject=$project&buildDefinition=$definition&buildNumber=$build&targetStageName=$targetStage"

$webClient = New-Object System.Net.WebClient
$webClient.UseDefaultCredentials = $true

$releaseId = $webClient.DownloadString($uri)
$url = "$orchestratorService/ReleaseStatus?releaseId=$releaseId"
$releaseStatusId = $webClient.DownloadString($url)
$releaseStatus = $status[$releaseStatusId]


No comments: