Manage Gitlab with Python
Using python-gitlab to Manage Your GitLab Instance

I’ve been rocking the DevOps journey for a decade, starting with building Cisco’s software-defined datacenters for multi-region OpenStack infrastructures. I then shifted to serverless and container deployments for finance institutions. Now, I’m deep into service meshes like Consul, automating with Ansible and Terraform, and running workloads on Kubernetes and Nomad. Stick around for some new tech and DevOps adventures!
python-gitlab is a Python package that provides a convenient interface to interact with GitLab's APIs. It enables programmatic management of your GitLab instance, allowing tasks such as identifying inactive users, gathering commit statistics, and managing projects. This guide walks you through the setup and provides examples to get started.
Installation
To use python-gitlab, you need to install it via pip. Run the following command in your terminal:
$ pip install python-gitlab
Authentication Setup
To interact with the GitLab API, you need a personal access token for authentication. Follow these steps to generate one:
Log in to your GitLab instance (e.g., https://gitlab.abc.com).
Navigate to User Settings > Access Tokens in the GitLab web interface.
Create a new personal access token:
Provide a name for the token.
Select the necessary scopes (e.g.,
apifor full access).Set an expiration date (optional but recommended for security).
Copy the generated token and store it securely. You will use this in your scripts.
Note: Never share your token publicly or commit it to version control.
Example: listing all public projects
Below is an example of using Python to list all public projects in your GitLab instance:
#! /usr/bin/python
import gitlab
# Replace with your GitLab instance URL and personal access token
GITLAB_URL = "https://gitlab.abc.com"
PRIVATE_TOKEN = "your-personal-access-token"
# Initialize the GitLab client
gl = gitlab.Gitlab(GITLAB_URL, private_token=PRIVATE_TOKEN)
# Fetch all projects with public visibility
projects = gl.projects.list(visibility="public")
# Print project names and paths
for project in projects:
print(f"Name: {project.name}, Path: {project.path}")
The example gitlab_inactive_users.py retrieves user activity data to identify users who have been inactive since a specified date (e.g., September 1, 2018). This is useful for resource management in large organizations.




