使用API删除Gitlab Pipeline
通过API删除
不知道为何在Gitlab网页上找不到删除pipiline记录的按钮,查找了Gitlab文档发现可以通过API来删除。
官方文档 Pipelines API | GitLab
curl --header "PRIVATE-TOKEN: <your_access_token>" --request "DELETE" "https://gitlab.example.com/api/v4/projects/1/pipelines/46"
根据文档,删除一个Pipeline需要access token, project id和pipeline id,分别可以在以下页面获取:
-
获取账户的access token:在User Settings -> Access Tokens页面,输入token名字并勾选api,创建一个access token。详细请参考。
-
获取Project ID: 在项目页面 -> Setting -> General 找到 Project ID.
-
获取Pipeline ID: 在项目页面 -> CI/CD -> Pipelines 找到 Pipeline ID.
试了一下,果然成功把Pipeline删了。
批量删除
但如果有几十上百的Pipeline要删除,一个一个地删太麻烦了。Gitlab还提供了获取Pipeline ID的API。
Pipelines API | GitLab
curl --header "PRIVATE-TOKEN: <your_access_token>" "https://gitlab.example.com/api/v4/projects/1/pipelines"
$ curl --header "PRIVATE-TOKEN:xxxxxxxxxxxxxxxxx" "http://git.xxxx.com/api/v4/projects/3341/pipelines"
[{"id":136009,"sha":"82345f541bd6a5299d1468387fa119c30730cd59","ref":"bugfix","status":"pending","web_url":"http://git.xxxx.com/xxxx/xxxx/pipelines/136009"},{"id":136007,"sha":"82345f541bd6a5299d1468387fa119c30730cd59","ref":"feat","status":"pending","web_url":"http://git.xxxx.com/xxxx/xxxx/pipelines/136007"},{"id":136006,"sha":"82345f541bd6a5299d1468387fa119c30730cd59","ref":"dev","status":"pending","web_url":"http://git.xxxx.com/xxxx/xxxx/pipelines/136006"}]
执行完后返回了该项目的所有Pipeline ID(其实并不是所有,Gitlab有分页功能,获取一次只能返回一个页面的Pipeline ID)
转换成python代码
使用shell感觉不太方便,改成了以下的python代码
import requests
class GitlabApi():
def __init__(self, token, url):
self.token = token
self.url = "%s%s" %(url, "api/v4")
self.header = {
"Content-Type": "application/json",
"Private-Token": self.token
}
def delete_pipeline(self, project_id, pipeline_id):
api_url = "%s/projects/%s/pipelines/%s" % (self.url, project_id, pipeline_id)
res = requests.delete(api_url, headers = self.header)
return res
def get_all_pipelines(self, project_id):
data = []
page = 0
total_pages = 1
while page < total_pages:
api_url = "%s/projects/%s/pipelines?page=%d" % (self.url, project_id, page)
res = requests.get(api_url, headers = self.header)
total_pages = int(res.headers["X-Total-Pages"])
data += res.json()
page += 1
return data
if __name__ == "__main__":
project_id = "1234"
api = GitlabApi("xxxxxxxxx", "http://git.xxxx.com/")
pipelines = api.get_all_pipelines(project_id)
for pipeline in pipelines:
print("delete pipeline id [%d]" % pipeline["id"])
api.delete_pipeline(project_id, pipeline["id"])
都看到这了,点个赞再走吧。