5

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'

2 Answers 2

2

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()
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks!! That worked. I'm specifically looking to list protected variables only, instead of all the vars. Do you if there is a special param for that? I have tried project.variables.list(protected=True) but that didn't work.
As far as I know, there is no filtering for that in the list API itself (therefore no such keyword parameter in the Python API wrapper) but it is relatively simple to do that filtering in python: protected_variables = [var for var in project.variables.list(all=True) if var.protected is True] @blackPanther
Great, it did the trick, thanks! now protected_variables is a list of classes like [<ProjectVariable key:API_TOKEN>, <ProjectVariable key:WEBHOOK_URL>], whereas I'm just looking for [API_TOKEN, WEBHOOK_URL]
@blackPanther those are instances, not classes. You can extract the information you want from the object. For example var.value -- if I've answered your original question, please consider voting and accepting it. If you still need more help beyond that, consider raising a separate question.
0

According to the FAQ:

I get an AttributeError when accessing attributes of an object retrieved via a list() call.

Fetching a list of objects, doesn’t always include all attributes in the objects. To retrieve an object with all attributes use a get() call.

Adapting the example to your code:

for project in projects:
    project = gl.projects.get(project.id)
    project.variables.list()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.