3

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'

blackPanther
  • 181
  • 1
  • 3
  • 14

2 Answers2

1

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()
sytech
  • 29,298
  • 3
  • 45
  • 86
  • 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. – blackPanther Aug 24 '22 at 21:22
  • As far as I know, there is no filtering for that in the [list API itself](https://docs.gitlab.com/ee/api/project_level_variables.html) (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 – sytech Aug 24 '22 at 21:37
  • Great, it did the trick, thanks! now `protected_variables` is a list of classes like `[, ]`, whereas I'm just looking for `[API_TOKEN, WEBHOOK_URL]` – blackPanther Aug 24 '22 at 22:17
  • @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. – sytech Aug 24 '22 at 22:19
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()
SuperStormer
  • 4,997
  • 5
  • 25
  • 35