Gitlab API and Python

To start, create a config file with your Gitlab personal token:

vi ~/.python-gitlab.cfg

With contents similar to below:

 [global]
 default = gitlab
 ssl_verify = true
 timeout = 5
 [gitlab]
 url = https://gitlab.com
 private_token = 1234ABCD1234ABCD
 api_version = 4

next create a directory and a python virtualenv:

bash
mkdir ./code/python/test
python3 -m venv env
source env/bin/activate
pip3 install requests python-gitlab

Check which python binary we are using:

which python

Should be similar to:

/Users/me/code/python/test/env/bin/python

And finally use the module in a Python script. In the example below I am fetching a list of all my groups. Filtering that for those that include the word ‘foobar’ then printing out each project in the groups with the shared_gitlab_runner attribute. I think pick an example project and change that setting to False:

import gitlab

gl = gitlab.Gitlab.from_config('gitlab', ['/Users/me/.python-gitlab.cfg'])

all_groups = gl.groups.list(all=True)

for group in all_groups:
    if "foobar" in str(group.full_name):
        projects = group.projects.list()

        for project in projects:
            print(f"{project.shared_runners_enabled}\t{project.id}\t{group.full_path}\t{project.name}")

project_id=1111222233
project = gl.projects.get(project_id)
project.shared_runners_enabled = False
project.save()
print(project.shared_runners_enabled)

Leave a Reply

  • (will not be published)

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>