I have a script I need to lock a branch in azure git
How to use lock api in a powershell script to lock a branch in azure git
Asked
Active
Viewed 647 times
1

Avin Verma
- 11
- 1
- 6
1 Answers
0
The API documentation can be found here: locking a branch in Azure DevOps.
An example is:
PATCH https://dev.azure.com/{organization}/{project}/_apis/git/repositories/{repositoryId}/refs?filter={filter}&api-version=6.0
The branch you wish to lock is in the {filter}
variable.
Here's a working example I just tested using curl from within Git Bash:
curl
--header "Content-Type: application/json"
--data '{"isLocked": true}'
--user username:password
--request PATCH "https://dev.azure.com/{organization}/{project}/_apis/git/repositories/{repositoryId}/refs?filter=heads/my-branch-name&api-version=6.0"
In my case, for password, I used a personal access token.

TTT
- 22,611
- 8
- 63
- 69
-
This API is not working as I tried with all the parameters but still it is not working – Avin Verma Apr 05 '21 at 08:57
-
@AvinVerma what is the error you're getting? – TTT Apr 05 '21 at 15:27
-
@AvinVerma I added an example which I just tested and is working for me. – TTT Apr 05 '21 at 15:37
-
Script is executing successfully but branch is not locked – Avin Verma Apr 06 '21 at 05:15
-
I use this Invoke-WebRequest -Headers $headers -Uri PATCH "dev.azure.com/{organization}/{project}/_apis/git/repositories/{repositoryId}/refs?filter=heads/master&api-version=6.0" – Avin Verma Apr 06 '21 at 12:42
-
@AvinVerma are you getting a JSON response? I tried this with read-only access on my token, and I didn't get a JSON response. With read/write access I do get a response. When isLocked is true the JSON response includes `"isLockedBy":{"displayName":"..."` – TTT Apr 06 '21 at 13:55
-
Is there a way to lock all the branches at once? – Sarun Jun 20 '22 at 12:45
-
@Sarun - what is the use case for that? That sounds like adjusting permissions on the entire repo so that no one can contribute/push except for one person. Is that really what you would want? If yes, it should be fairly straightforward to simply loop through all branches and make the API call for each branch. I can't find a more efficient alternative than that documented, but perhaps one exists... – TTT Jun 20 '22 at 16:05
-
@TTT - I need to migrate the repos to a different url. After migration, I wanted to lock the source repos so that no further changes are made. Yes, I can loop through and do it, was just wondering if there was a better solution. – Sarun Jun 24 '22 at 14:41
-
@Sarun in that case I would lock down the source repo, not every branch. Even if you lock every branch it wouldn't prevent pushing new branches, which wouldn't be locked. Just change the permission on the source repo to be read-only. – TTT Jun 24 '22 at 14:44