How to use Release Definition REST API for VSTS? - powershell

I have been successfully able to use Release Definition API on our TFS 2015 Update 3 on prem instance using API Version "3.0-preview.1". But ever since I started testing this on VSTS, I am continuously getting a 404 error stating
Page not found And a long block of HTML.
I am using PowerShell to call the API. And I am creating the API request as mentioned in the documentation using Personal Access Token and Alternate credential method.
https://fabfiber.vsrm.visualstudio.com/DefaultCollection/ff213d65-d61d-447c-b39d-d16f21b18364/_apis/release/definitions?api-version=3.0-preview.1
Can someone let me know if I am missing something.

Try this code:
$vstsAccount = "[your vsts name]"
$user = "test"
$accessToken="[personal access token]"
$teamProject="[team project name]"
Function QueryWorkItem{
$base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f $user,$accessToken)))
$uri="https://$vstsAccount.vsrm.visualstudio.com/defaultcollection/$teamProject/_apis/release/definitions?api-version=3.0-preview.1"
$result = Invoke-RestMethod -Uri $uri -Method Get -Headers #{Authorization=("Basic {0}" -f $base64AuthInfo)}
}

You may refer the blog :-
https://blogs.msdn.microsoft.com/chandananjani/2016/04/15/using-releasemanagement-rest-apis/
https://blogs.msdn.microsoft.com/chandananjani/2016/04/27/using-releasehttpclient-for-interacting-with-releasemanagement-service/
as well to know as how to use the release management REST API's.

Related

Azure cli: clone pipeline

Looking at az pipelines documentation it seems it's not possible to clone a pipeline using cli.
I've looked at getting the yaml (az pipelines show -name=x > x_orig.yaml) and then trying to change json and create pipeline from modified yaml, but that feels like a lot of work that could break after next update.
Is there a way to clone a pipline without going the the Web UI?
Currently, there indeed is not available Azure CLI that can clone or export/import a pipeline to create a new pipeline.
I also searched and tried the Azure DevOps REST API for Pipelines, but did not find the available API.
Ideally, the Azure CLI "az pipelines create" can provide an input parameter that allows users specify an existing pipeline as a starting point for the new pipeline.
If your projects really need this feature, I recommend that you can directly report a feature request on the "Azure/azure-cli" repository to ask adding the parameter like as above mentioned. That will allow you directly interact with the appropriate engineering team, and make it more convenient for the engineering team to collect and categorize your suggestions.
As a workaround, we could clone the build definition via power shell script to call REST API.
Note: We need to change the original build definition name.
REST API
Get build definition:
GET https://dev.azure.com/{organization}/{project}/_apis/build/definitions/{definitionId}?api-version=6.0
Create build definition
POST https://dev.azure.com/{organization}/{project}/_apis/build/definitions?api-version=6.0
Power shell script
$connectionToken="{pat}"
$base64AuthInfo= [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes(":$($connectionToken)"))
$BuildDefinitionInfoURL = "https://dev.azure.com/{org name}/{project name}/_apis/build/definitions/386"
$BuildDefinitionInfo = Invoke-RestMethod -Uri $BuildDefinitionInfoURL -Headers #{authorization = "Basic $base64AuthInfo"} -Method Get
Write-Host $BuildDefinitionInfo.name
$BuildDefinitionInfo.name = $BuildDefinitionInfo.name +" clone"
Write-Host $BuildDefinitionInfo.name
$body = $BuildDefinitionInfo | ConvertTo-Json -Depth 99
$createBuildDefinitionURL = "https://dev.azure.com/{org name}/{project name}/_apis/build/definitions?api-version=6.0"
$response = Invoke-RestMethod -Uri $createBuildDefinitionURL -ContentType "application/json" -Body $body -Headers #{Authorization=("Basic {0}" -f $base64AuthInfo)} -Method POST
Write-Host $response.id
Result:

How would you access attributes of work items (Features, User Stories, Bugs, or Tasks) associated with a build in the release pipeline?

My team and I are trying to find a way to automatically build release notes and generate them in markdown to be put into a Wiki for users to access. I found a video from Microsoft where their team uses a process where they have release notes for each feature in their Feature objects, but they have manually query those objects and build a markdown file for each release manually. I'm sure by now they must have figured this out, but can't find anything from them yet on that.
Now, I have seen a couple of market place tools (Bravo Notes for one) that do this, but I figured there must be a way we can make a task ourselves that does this for us and automatically place the markdown file in our Wiki (after an approval process of course).
If anyone has any ideas on how I can accomplish this, please let me know. I'm not afraid of getting my hands dirty with some Powershell scripts.
You can use Azure DevOps Rest API to get the work item that associated to the build, then get work item details. create from the details a Markdown file and add it to the wiki.
Example to PowerShell script that do it (get work items asscoited with the build and print the AssignedTo field):
$user = ""
$token = "MY-PAT"
$base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f $user,$token)))
$url = "https://dev.azure.com/{org}/{project}/_apis/build/builds/{buildId}/workitems?api-version=5.1"
$workItems = Invoke-RestMethod -Uri $url -Method Get -ContentType application/json -Headers #{Authorization=("Basic {0}" -f $base64AuthInfo)}
$json = $workItems | ConvertTo-Json
$workItems.value.ForEach({
$workItem = Invoke-RestMethod -Uri $_.url -Method Get -ContentType application/json -Headers #{Authorization=("Basic {0}" -f $base64AuthInfo)}
Write-Host $workItem.fields.'System.AssignedTo'.displayName
})

How to create a new build or release using the API and YAML

I'm just looking for direction here as, possibly, the api already does this and I'm misunderstanding / can't find the right resource.
What I would like to do is to be able to call the azure-devops api to create a new build definition for me when I supply it with all the necessary yaml files for each stage.
I expected a create endpoint which would take in a few basic pieces of information to create the build / release definition then a collection of yaml files to create the tasks.
I've found Create your first pipeline and Api 5.0 BuildDefinition/Create however neither of these mention posting a yaml definition to the api. I was expecting far less items in the request body considering the yaml definitions contain most of the information required.
Does the api support this? Will it ever support this?
There is no docs for Rest Api with yaml, but if you try to get an existing yaml definition you`ll meet the next example:
So if you want to edit the process you have to edit existing yaml file. If you want create/clone an existing build definition you may try to create/clone yaml file and post a request (Definitions - Create) with the process member:
yamlFilename = path to yaml file in the repository
type = 2
This powershell example to clone a build definition with yaml:
$pat = '{personal access token}'
$base64AuthInfo = [System.Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes(":$pat"))
$uri = 'https://dev.azure.com/{organization}/{team_project}/_apis/build/definitions/{buil_id}?api-version=5.0'
$result = Invoke-RestMethod -Method Get -Uri $uri -Headers #{Authorization=("Basic {0}" -f $base64AuthInfo)} -ErrorAction Stop
$body = $result | ConvertTo-Json -Depth 7
$existingyaml = '"yamlFilename": "{path to yaml for existing buildef}"'
$newyaml = '"yamlFilename": "{path to new yaml}"'
$buildname = '"name": "{existing build name}"'
$newbuildname = '"name": "{new build name}"'
$body = $body.Replace($existingyaml, $newyaml)
$body = $body.Replace($buildname, $newbuildname)
$Uri = "https://dev.azure.com/{organization}/{team_project}/_apis/build/definitions?api-version=5.0"
$newBuildDef = Invoke-RestMethod -Uri $Uri -Headers #{Authorization=("Basic {0}" -f $base64AuthInfo)} -Method Post -Body $body -ContentType "application/json" -ErrorAction Stop
Yes, you are right, you could do a get on a build using the api, and change the variables, it should work.
If you only need to modify variables, you could use variable group to store values, then you can get the variable group and modify the variable values using the Variablegroups api.

Getting a file from BitBucket Rest API v2.0

I have a script which grabs a file from GIT using the bitbucket REST API (1.0) however it has recently stopped working. I'm theorizing this may be due to the v1 REST API being depreciated but I'm not sure.
Anyway I am trying to retrieve the file using the new 2.0 REST API but I can't seem to get the syntax right as the request continually fails.
I'm starting out with curl since its easiest to test. This is what I'm trying:
curl -u myusername#mydomain.com "https://api.bitbucket.org/2.0/repositories/MyCompany/myrepo/downloads/Scripts/Environment Setup/test.txt"
Enter host password for user 'myusername#mydomain.com': redacted
{"type": "error", "error": {"message": "Resource not found", "detail": "There is no API hosted at this URL.\n\nFor information about our API's, please refer to the documentation at: https://developer.atlassian.com/bitbucket/api/2/reference/"}}
Here is the reference documentation I am using: https://developer.atlassian.com/bitbucket/api/2/reference/resource/repositories/%7Busername%7D/%7Brepo_slug%7D/downloads/%7Bfilename%7D
Maybe I am using the wrong function? I'm not sure.
For posterities sake, you don't want to use the following to download an individual file from bitbucket:
https://api.bitbucket.org/2.0/repositories/MyCompany/myrepo/downloads/path/to/your/file.txt
("Downloads" is to download entire repo files like a .zip file)
Instead you want to do:
curl --user myuser#mydomain.com:password "https://api.bitbucket.org/2.0/repositories/MyCompany/myrepo/src/master/path/to/file.txt"
If you're trying to use Invoke-RestRequest (in powershell) note there are some extra steps. With the old 1.0 API you could do:
$cred = Get-Credential
$uri = "https://api.bitbucket.org/1.0/repositories/MyCompany/$($filepath)"
# Get the files from bitbucket (GIT)
Invoke-RestMethod -Credential $cred -Uri $uri -Proxy $proxyUri -OutFile $destination
With the new 2.0 API that no longer works. Powershell's Invoke-RestMethod waits for a 401 response before sending the credentials, and the new 2.0 bitbucket api never provides one, so credentials never get sent causing a 403 forbidden.
To work around that you have to use the following ugly hack to force Invoke-RestMethod to send the credentials immediately in an Authorization header:
$cred = Get-Credential
$uri = "https://api.bitbucket.org/2.0/repositories/MyCompany/$($filepath)"
$username = ($cred.GetNetworkCredential()).username
$password = ($cred.GetNetworkCredential()).password
$base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f $username,$password)))
# Get the files from bitbucket (GIT)
Invoke-RestMethod -Headers #{Authorization=("Basic {0}" -f $base64AuthInfo)} -Uri $uri -Proxy $proxyUri -OutFile $destination
Hopefully that helps someone else out in the future!
Thanks #Jim Redmond for the help.
You can also use the PowerShell module BitbucketServerAutomation. There's not a ton of cmdlets, they do have Get-BBServerFile and Get-BBServerFileContent. I have found it is well written, very usable and being updated regularly. The Invoke-BBServerRestMethod cmdlet is available if you need a command it doesn't have.

Check previous build information in VSTS (VSTS API)

Are previous build variables accessible during execution of a VSTS build? For example, can I get $(Build.SourceVersion) or $(Build.QueuedBy) of the previous build?
I can get current build information through the build variables like $(Build.SourceVersion) but can I get something like $(Build.Previous.SourceVersion)?
There aren’t the built-in variables for previous build information, the workaround is that you can call Builds REST API (can be filter status, such as completed, inProgress) through PowerShell during this build. (The first item of the result is the newest one)
$base64authinfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f $User, $Password)))
$responseFromGet = Invoke-RestMethod -Method Get -ContentType application/json -Uri $Uri -Headers #{Authorization=("Basic {0}" -f $base64authinfo)}
Some articles about calling REST API: Calling VSTS APIs with PowerShell, VSTS/TFS REST API: The basics and working with builds and releases
You can use value of System.AccessToken variable as password (Check Allow scripts to access OAuth token option in Options tab) and username can be anything.
No. "Previous" is a nebulous concept when you're talking about things that can run in parallel. What if you have 3 builds running concurrently?