Deleting branches on Azure DevOps with Powershell - azure

I am trying to delete old branches which are x days old from Azure DevOps by using Powershell, but it is unsuccessful. Could you please help me out on this matter or if you have any better idea to execute this task, I am more than welcome to hear them out! I have been stuck with it for a few weeks now.
Thanks.

Deleting branches on Azure DevOps with Powershell
You could use the REST API to delete those Branch.
However, we do not recommend you to do this. It is not safe to use scripts to delete some old branches, because the script cannot determine whether the branch is important, but it is risky to delete based on the date. So you need to be clear about this before deleting.
First, we could use the REST API Refs - List to list all the branches for the Repo:
GET https://dev.azure.com/{organization}/{project}/_apis/git/repositories/{repositoryId}/refs?api-version=6.0
Then, we loop each branch with REST API Commits - Get Commits:
GET https://dev.azure.com/{organization}/{project}/_apis/git/repositories/{repositoryId}/commits?&searchCriteria.compareVersion.version=<YouBranchName>&api-version=6.0
And compare creation date or activation date, use the REST API to delete those branches:
POST https://dev.azure.com/{organization name}/{project name}/_apis/git/repositories/{repositoryId}/refs?api-version=5.1
Request Body:
[
{
"name": "{branchName}",
"oldObjectId": "{branchObjectId}",
"newObjectId": "0000000000000000000000000000000000000000"
}
]
Alternatively, if you want use git command line to delete, you could refer below document for some more details:
Deleting Old Local Branches With PowerShell

Related

Azure Yaml Pipeline - Update Workitems from multiple Repositories

In a nutshell, I am looking to get a list of work items linked to a git branch.
In more detail
I am working with 4 repositories that I add as resources to my pipeline
- repository: Cms # code repository
name: <ProjectName>/Cms
type: git
ref: develop2022
- repository: QA-Automation # Automated Testing Repo
name: <ProjectName>/QA-Automation
type: git
ref: main
- repository: TdsWDPExplorer # Generate Reports Repo
name: <ProjectName>/TdsWDPExplorer
type: git
ref: master
The Pipeline yaml files them self's are in the 4th Repo and checked out as self
- checkout: Self
path: s/DE-DevOps
I am trying to update the work items associated with the Cms Repository.
I tried using the Workitem Updater task https://marketplace.visualstudio.com/items?itemName=BlueBasher.bluebasher-workitemupdater
But it only sees the workitems associated with the Repository holding the yaml Files (Self).
I also looked at the API to get a list of the work items.
_apis/git/repositories//refs?filter=heads%2fBRANCHNAME&includeLinks=true
Gives me details to a branch but I didn't find the linked work items
Also looking at the workitem I dint see that info
_apis/wit/workitems?ids=ITEM-ID's&$expand=all&api-version=6.0
I am thinking it might be somewhere in _apis/wit/reporting/workitemlinks but haven been able to get the info.
I found a answer that works for me, in a response to Obtain all work items from Azure DevOps that have been merged into a branch via JavaScript
we link the work items to pull requests, I can use the API to query the pull requests in to the given branch and get the linked work items like:
https://dev.azure.com/Organisation/Project/_apis/git/repositories/Cms/pullrequests?searchCriteria.status=completed&searchCriteria.targetRefName=refs/heads/BRANCHNAME&api-version=6.0
I should now be able to extract the ID's and pass them in a PS loop to the Item Updater Task https://marketplace.visualstudio.com/items?itemName=BlueBasher.bluebasher-workitemupdater or using the API to update the workitem
There is also the option to call the API for the pipeline run info https://learn.microsoft.com/en-us/rest/api/azure/devops/pipelines/runs/get?view=azure-devops-rest-7.1#runresources
But I didn't see a way to extract the work items but the information must be somewhere there as well because I can see the work items listed in the pipeline view by resource

Bitbucket API is there a way to return last/current deployed branch name for specific environment?

I am building a small automation tool that will redeploy my last/current deployed branch again via api ,
looking through the document i could not find the right way to fetch my current branch name or anything related to it .
i tried the endpoint /deployments
i got a lot of data , but for somereason i can not see my last/current deployed pipeline in the list .
Thanks
i have found the way ,
https://api.bitbucket.org/2.0/repositories/{workspace}/{repo_slug}/environments/
then fetch pipeline uuid from the env u need and request the pipeline data via
/2.0/repositories/{workspace}/{repo_slug}/pipelines/{pipeline_uuid}

How to get branch name from commit id using azure Devops REST API?

Scenario: I need to get when was the latest commit done in the repo and by whom, and to which branch did that user do the commit on?
Solution:
I'm using python azure.devops module. and here is my code:
cm_search_criteria = models.GitQueryCommitsCriteria(history_mode='firstParent', top=10)
commits = git_client.get_commits(repo.id, search_criteria=cm_search_criteria, project=project.name)
for i in commits:
datetimeobj = datetime.strptime(i.committer.date.strftime("%x"), '%m/%d/%y')
last_commit_on = datetimeobj.date()
last_commit_by = i.committer.email
break
Now how do I get the branch name to which the user had committed the code? In the UI we can see the branch name... how can i get the same data using Azure Devops REST API ?
enter image description here
you may need to use Stats - List to retrieve statistics about all branches within a repository, then evaluate the latest commit, you also need to consider argument of baseVersionDescriptor.versionOptions of firstParent
I'm not sure if Python wrapper module support this seems like the github project is achieved now.

Get the pull request ID of a continuous deployment release [Azure Pipelines]

I am trying to setup azure pipelines to trigger a build on every PR update, and a release on every merge. For a couple of reasons when the PR is merged, i need to access data saved by the latest validation build of the PR.
However to do that i need the PRid during the run of the Release pipeline. How can one achieve that?
From the release you can retrieve the commit Id which triggered the build.
Then you search for the commitId in the list of completed PRs and retrieve your PR number.
$commitId = "$(RELEASE.ARTIFACTS.{YOURARTIFACTALIAS}.SOURCEVERSION)"
$repoId = "$(RELEASE.ARTIFACTS.{YOURARTIFACTALIAS}.REPOSITORY.ID)"
$pullRequestsUri = "https://dev.azure.com/{organization}/{project}_apis/git/repositories/" + $repoId + "/pullrequests?searchCriteria.status=completed&api-version=5.1"
$base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f "", "$(System.AccessToken)")))
$pullRequests = Invoke-RestMethod -Uri $pullRequestsUri -Method GET -ContentType "application/json" -Headers #{Authorization = "Basic $base64AuthInfo" }
foreach ($value in $pullRequests.value) {
if ($value.lastMergeCommit.commitId -eq $commitId) {
$pullRequestId = $value.pullRequestId
}
}
Write-Host $pullRequestId
Based on your scenario, to my knowledge, it is complex to get related build information in your release. Besides, it may cause unexpected result if not cover all possible scenarios.
I'd suggest that you could refer to these steps blow:
Remove publish build/pipeline artifact or unnecessary tasks, just remain tasks for validation, which will save a lot of time. (Because, in general, the validation build will be triggered too many times, waste too much time to publish useless artifact or other data)
Create a new build pipeline and enable Continuous integration for target branch (e.g. master)
Add publish build/pipeline artifact task
Edit release pipeline and link this build pipeline and enable Continuous deployment. (Could add additional filters)
With this way, after completing the pull request, this new build pipeline will be triggered and will publish necessary artifact, then the release will be triggered.
For pull request validation builds, they just do tasks to validate the code (e.g. build project), but not publish artifact.
Simple scenario for saving time:
A pull request has 50 validation builds
old way: publish artifact of each takes 1 minutes, then total time is 50 minutes
new way: the new pipeline do tasks for build and publish, it just run once and may just takes 10 minutes.
Then you can save 40 minutes.
In Release Pipeline, you could use the variable $(RELEASE.ARTIFACTS.<<Source alias name>>.PULLREQUEST.ID) to get the Pull Request ID.
Note: the Source alias name is the name set in the release artifacts.
By the way, if you use a default variable in your script, you must first replace the . in the default variable names with _.
For example: $env:RELEASE_ARTIFACTS_<<Source alias name>>_PULLREQUEST_ID
Here is a doc about the Release variables.
Hope this helps.

How to establish a continuous deployment of non-.NET project/solution to Azure?

I have connected Visual Studio Online to my Azure website. This is not a .NET ASP.NET MVC project, just several static HTML files.
Now I want to get my files uploaded to Azure and available 'online' after my commits/pushes to the TFS.
When a build definition (based on GitContinuousDeploymentTemplate.12.xaml) is executed it fails with an obvious message:
Exception Message: The process parameter ProjectsToBuild is required but no value was set.
My question: how do I setup a build definition so that it automatically copies my static files to Azure on commits?
Or do I need to use a different tooling for this task (like WebMatrix).
update
I ended up with creating an empty website and deploying it manually from Visual Studio using webdeploy. Other possible options to consider to create local Git at Azure.
Alright, let me try to give you an answer:
I was having quite a similar issue. I had a static HTML, JS and CSS site which I needed to have in TFS due to the project and wanted to make my life easier using the continuous deployment. So what I did was following:
When you have a Git in TFS, you get an URL for the repository - something like:
https://yoursite.visualstudio.com/COLLECTION/PROJECT/_git/REPOSITORY
, however in order to access the repository itself, you need to authenticate, which is not currently possible, if you try to put the URL with authentication into Azure:
https://username:password#TFS_URL
It will not accept it. So what you do, in order to bind the deployment is that you just put the URL for repository there (the deployment will fail, however it will prepare the environment for us to proceed).
However, when you link it there, you can get DEPLOYMENT TRIGGER URL on the Configure tab of the Website. What it is for is that when you push a change to your repository (say to GitHub) what happens is that GitHub makes a HTTP POST request to that link and it tells Azure to deploy new code onto the site.
Now I went to Kudu which is the underlaying system of Azure Websites which handles the deployments. I figured that if you send correct contents in the HTTP POST (JSON format) to the DEPLOYMENT TRIGGER URL, you can have it deploy code from any repository and it even authenticates!
So the thing left to do is to generate the alternative authentication credentials on the TFS site and put the whole request together. I wrapped this entire process into the following PowerShell script:
# Windows Azure Website Configuration
#
# WAWS_username: The user account which has access to the website, can be obtained from https://manage.windowsazure.com portal on the Configure tab under DEPLOYMENT TRIGGER URL
# WAWS_password: The password for the account specified above
# WAWS: The Azure site name
$WAWS_username = ''
$WAWS_password = ''
$WAWS = ''
# Visual Studio Online Repository Configuration
#
# VSO_username: The user account used for basic authentication in VSO (has to be manually enabled)
# VSO_password: The password for the account specified above
# VSO_URL: The URL to the Git repository (branch is specified on the https://manage.windowsazure.com Configuration tab BRANCH TO DEPLOY
$VSO_username = ''
$VSO_password = ''
$VSO_URL = ''
# DO NOT EDIT ANY OF THE CODE BELOW
$WAWS_URL = 'https://' + $WAWS + '.scm.azurewebsites.net/deploy'
$BODY = '
{
"format": "basic",
"url": "https://' + $VSO_username + ':' + $VSO_password + '#' + $VSO_URL + '"
}'
$authorization = "Basic "+[System.Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes($WAWS_username+":"+$WAWS_password ))
$bytes = [System.Text.Encoding]::ASCII.GetBytes($BODY)
$webRequest = [System.Net.WebRequest]::Create($WAWS_URL)
$webRequest.Method = "POST"
$webRequest.Headers.Add("Authorization", $authorization)
$webRequest.ContentLength = $bytes.Length
$webRequestStream = $webRequest.GetRequestStream();
$webRequestStream.Write($bytes, 0, $bytes.Length);
$webRequest.GetResponse()
I hope that what I wrote here makes sense. The last thing you would need is to bind this script to a hook in Git, so when you perform a push the script gets automatically triggered after it and the site is deployed. I haven't figured this piece yet tho.
This should also work to deploy a PHP/Node.js and similar code.
The easiest way would be to add them to an empty ASP .NET project, set them to be copied to the output folder, and then "build" the project.
Failing that, you could modify the build process template, but that's a "last resort" option.

Resources