Update 22/6/2016
That’s how fast things go. Since this blogpost there has been a new update on VSTS that allows you to access the OAuth token by just clicking a checkbox.
In the Release Environment, click the elipsis asnd select Deployment Conditions (or Configure Variables etc.). It opens a new screen where you also can navigate to the Tab General. (This is not directly accesible form the elipsis)
Click the Oauth checkbox, and you have the variable at your service
Good luck !
A few days ago I blogged about how to call the VSTS REST API from within your build definition. By means of checking a checkbox of the build definition, you get a hidden environment variable (System.AccessToken) that contains a authorization key to the VSTS account you are residing in to call the REST API. By adding this key to the header you can access the REST API without any problem.
When I tried to do the same trick in my VSTS Release definition I came to the unfortunate conclusion that this checkbox and functionality is not (yet!) there.
Fortunately there is an easy way to fix this! In this post I describe the steps that you need to take to be able to call the REST API from within your release definition.
1. Create a Personal Access Token
Instead of the variable you get out of the box, you need to create a Personal Access Token (PAT). I describe how to do that in this blogpost
2. Create a hidden variable in your Release Pipeline
Create or open a release definition and create a variable called RestToken (or something). Set the value to the PAT and make sure you make it hidden!
3. Encode token and add to header
The PAT needs to be Base64 Encoded and then it should be added to the header of your REST call. Use this Powershell snippet to create the token. I made it a bit more intelligent so it can handle both the System.Accesstoken (when used from the build) or the PAT you provide in the release definition.
##Creates either a Basic Authentication token or a Bearer token depending on where the method is called from
function CreateAuthenticationToken([string] $accesstoken)
{
$accesstoken = “”;
if([string]::IsNullOrEmpty($env:System.AccessToken))
{
$userpass = “:$($RestToken)”
$encodedCreds = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes($userpass))
$accesstoken = “Basic $encodedCreds“
}
else
{
$accesstoken = “Bearer $RestToken“
}
return $accesstoken;
}
4. Call REST API from Powershell
Last but not least, create a Invoke-WebRequest and send the accesstoken in the header
Invoke-RestMethod -Uri <vsts url> -Headers @{Authorization = $token} -Method Get -ContentType “application/json”
Hope this helps!
Trackbacks/Pingbacks
[…] Call VSTS REST API from Release Management by Rene van Osnabrugge […]
[…] uses the Release Management System.AccessToken that you should enable on your environment. For that read my blog post here. Or, if I should use the Personal Access Token that I provided as a parameter, and build up […]