cURL to delete specific branches from GitLab

Viewed 139

I am little confused on how to make use of cURL command to delete the unnecessary branches we have in our GitLab instance.

I want to delete the branches which are named as "tobedeleted_*" , so any branch name which starts with "tobedeleted" I want to delete it.

However one more additional thing which I want to check is, I want to delete the branches which are having an attribute in api where created_at is more than 1 month or 30 days.

This way, I want to make sure that I don't delete any branch which is newly created.

I have set of commands which can be executed manually to perform this which requires input of project id & branch name which is supposed to be deleted, but I want to automate it with the help of writing script or some curl commands which I will either schedule with the help of jenkins or gitlab schedule feature.

Can you guys help me on how to automate it?

I can tell you the details I have, I am basically lagging in writing the if conditions which will make it easier I believe.

I want to do this for all the projects which are present in a group number 6. So, To get all the project ids, I can make use of this curl command:

curl -s --location --request GET '$CI_API_V4_URL/groups/6/projects' --header 'PRIVATE-TOKEN:<my_pvt_token>' | sed 's/,/\n/g' | grep -w "id" | awk -F ':' '{print $2}' | sed -s 's/{"id"//g'

To get all the branches which are supposed to be deleted of a project which requires input of project ids, In the below curl command I am using projectid as 11

curl -s --location --request GET '$CI_API_V4_URL/projects/11/repository/branches' --header 'PRIVATE-TOKEN: <my_pvt_token>' | sed 's/,/\n/g' | grep -w "name" | awk -F ':' '{print $2}' | sed 's/"//g' | grep 'tobedeleted*'

Once, I extract the name of the branch of all the projects, I need to give input of project id and branch name and iterate it to the following cURL command:

curl --request DELETE --header "PRIVATE-TOKEN:<my_pvt_token>" "$CI_API_V4_URL/projects/11/repository/branches/tobedeleted_username_6819"

I am very confused on how can I iterate through the projects by keep on deleting the multiple branches I have of that project.

Any help is really appreciated. Also, this could be little easier if I was going to directly delete the merged branches with gitlab api, but I want to delete the specific named branches only.

Ref:

https://docs.gitlab.com/ee/api/branches.html#delete-repository-branch

https://docs.gitlab.com/ee/api/branches.html#list-repository-branches

https://docs.gitlab.com/ee/api/projects.html#list-all-projects

0 Answers
Related