Search code examples
python-3.xgitlabgitlab-api

How to list all the project variables in a gitlab project via GitLab V4 api


I'd like to list all the project variables in a gitlab project. I have followed their official documentation but seems like I couldn't get it to work.

Below is my code:

import gitlab, os

# authenticate
gl = gitlab.Gitlab('https://gitlab.com/', private_token=os.environ['GITLAB_TOKEN'])

group = gl.groups.get(20, lazy=True)
projects = group.projects.list(include_subgroups=True, all=True)
for project in projects:
    project.variables.list()

Error:

AttributeError: 'GroupProject' object has no attribute 'variables'


Solution

  • The problem is that group.list uses the groups list project API and returns GroupProject objects, not Project objects. GroupProject objects do not have a .variables manager, but Project objects do.

    To resolve this, you must extract the ID from the GroupProject object and call the projects API separately to get the Project object:

    group = gl.groups.get(20, lazy=True)
    group_projects = group.projects.list(include_subgroups=True, all=True)
    for group_project in group_projects:
        project = gl.projects.get(group_project.id)  # can be lazy if you want
        project.variables.list()