python-gitlab

The core of our new GitLab admin tool box is the python-gitlab Python module.

It provides an easy-to-use command line tool and a Python module for the GitLab API.

The complete documentation can be found here: https://python-gitlab.readthedocs.io/en/stable/

Installation

Use root privileges to install the module on a Debian-based systems..

sudo apt install python3-pip

sudo python3 -m pip \
             --disable-pip-version-check \
             --no-cache-dir \
             install --upgrade \
             python-gitlab

or on RPM-based systems you also need root privileges.

yum install python3-pip

sudo python3 -m pip \
             --disable-pip-version-check \
             --no-cache-dir \
             install --upgrade \
             python-gitlab

On macOS, before installing the module, use Homebrew to install Python3.

brew install python3

python3 -m pip \
        --disable-pip-version-check \
        --no-cache-dir \
        install --upgrade \
        python-gitlab

Tip, idea It's advised sure to run the pip command on a regular basis in order to keep the module up-to-date.

Configuration

Within your home directory create the file ~/.python-gitlab.cfg and add the following content:

[global]
default = gitlab
ssl_verify = true
timeout = 5

[gitlab]
url = https://gitlab.inf.ethz.ch/
private_token = ***********************
api_version = 4

Replace the stared-out token with the token from GitLab. How to obtain said token is described in the next section.

API Token

In order to access your GitLab account from python-gitlab, we must generate an API token:

  1. Login to the gitlab.inf.ethz.ch
  2. Click on your account icon in the top right corner
  3. Click Settings
  4. Choose Access Tokens from the left menu bar
  5. In the section Add a personal access token fill in the following fields
    1. Name: A name of your choosing, i.e. python-gitlab
    2. Expires at: While not required, it's a good idea to set an expiration date since renewing the token is easy
    3. Scopes section: enable api
  6. Click Create personal access token
  7. Now you'll be able to copy the token from the field on top called Your new personal access token. After leaving the page, you won't be able to access it again.
  8. Paste the token into the private_token field in ~/.python-gitlab.cfg

Testing

Run the following command to verify that the GitLab API access works:

 gitlab -o yaml user list --username $USER

If everything works correctly, this command should output some details about your GitLab account.

Usage

The python-gitlab CLI can be used as a wrapper for the GitLab API. Consult the documentation on how to use the CLI. Here are some examples:

 # List projects
 gitlab project list

 # Create a project
 gitlab project create --name project_name

Page URL: https://isg.inf.ethz.ch/bin/view/Main/HelpVersionControlGitLabPython
2024-11-21
© 2024 Eidgenössische Technische Hochschule Zürich