Delete your old GitLab CI pipelines
No more long history of pipelines, let’s clean it all up 🧹
Introduction
Failed, passed, canceled, pending, there are a lot of chances that you have a long list of old jobs in your GitLab project.
Hopefully, GitLab provides API endpoints to list them or delete pipelines one by one. You see where I’m going with this, we will call the “list” endpoint. Save the list into an array. Then loop over the array and call the delete endpoint.
As we love automation, we will write a JS script 🤖
Endpoints
First, we need to read the GitLab doc to know more about these endpoints and how to call them. You can read it here.
This page documents multiple features:
- list project pipelines
- get a single pipeline
- get variables of a pipeline
- …
- delete a pipeline
We will focus on two of them, list project pipelines and delete a pipeline.
Call the GitLab API
As you may know; you need to be authenticated when calling the GitLab API. First, you need to create an Auth Token (here) with the API rights. Then, you will have to pass the token in the headers as “PRIVATE-TOKEN”.
An example with CURL:
curl --header "PRIVATE-TOKEN: <your_access_token>" "https://gitlab.example.com/api/v4/projects/1/pipelines/46"
As we want to write a JS script, we will use Axios to call the endpoint. You will have to configure your Axios instance as follow:
List pipelines
Now that we are able to call GitLab API, we will list the project’s pipelines.
This bunch of calls will get the last 100 pipelines. They will be useful in the next of the article as we will loop other them to get each pipeline id and delete them one by one.
Delete a pipeline
To delete a pipeline, we will operate as follow:
We make a delete HTTP request to the GitLab API endpoint and pass the id in the path.
Delete all pipelines
As we know how to get pipelines and delete a single pipeline, we are able to loop on our pipeline array and delete them one by one as follow:
Wrap Up & Bonus
We are now able to clean the pipeline history in our GitLab projects. Here is the full code:
As you can see, I have added some features. This code uses “dotenv” library to load an environment file like this:
PROJECT_ID=20210318PRIVATE_TOKEN=AAAA-BBBBBBBBBBB
GitLab Repo: https://dmg.link/blog-pipelines-repo.
You can find my other articles and follow me here. Thanks for reading, I hope you learned something new today 🚀