To achieve your goal of listing all the subgroups and projects within a GitLab group (including nested subgroups and their projects), you can use the python-gitlab library. Below is a Python script that accomplishes this:
import gitlab
# Replace with your own personal access token
PRIVATE_TOKEN = 'your_private_token_here'
# GitLab server URL (change if you're using a different GitLab instance)
GITLAB_URL = 'https://gitlab.com'
# Initialize a GitLab instance
gl = gitlab.Gitlab(GITLAB_URL, private_token=PRIVATE_TOKEN)
def traverse_group(group):
print(f'Group: {group.full_name} (ID: {group.id})')
# List all projects in this group
projects = group.projects.list(all=True)
for project in projects:
print(f' Project: {project.path_with_namespace} (ID: {project.id})')
# List all subgroups and recurse into them
subgroups = group.subgroups.list(all=True)
for subgroup_info in subgroups:
# Fetch the full subgroup object
subgroup = gl.groups.get(subgroup_info.id)
traverse_group(subgroup)
# Start with the group with ID=234
group = gl.groups.get(234)
# Traverse and list all subgroups and projects
traverse_group(group)
Instructions:
-
Install the python-gitlab library if you haven't already:
pip install python-gitlab
-
Replace 'your_private_token_here' with your actual personal access token. Make sure your token has sufficient permissions to read group and project information.
-
Run the script to print out all the subgroups and projects within the group with ID 234.
Explanation:
- The script initializes a connection to your GitLab instance using your personal access token.
- The
traverse_group function prints the name and ID of each group and then lists all projects within that group.
- It then retrieves all subgroups of the current group and recursively calls
traverse_group on each one.
- This recursive approach ensures that all nested subgroups and their projects are listed, regardless of how deeply they are nested.
Note:
- Ensure that you have the necessary permissions to access the groups and projects.
- If you're using a self-hosted GitLab instance, update the
GITLAB_URL variable with your server's URL.
- The
all=True parameter in the list() methods fetches all items, not just the default page.
Sample Output:
Group: Parent Group (ID: 234)
Project: parent-group/project-one (ID: 101)
Project: parent-group/project-two (ID: 102)
Group: Parent Group / Subgroup A (ID: 235)
Project: parent-group/subgroup-a/project-three (ID: 103)
Group: Parent Group / Subgroup A / Subgroup B (ID: 236)
Project: parent-group/subgroup-a/subgroup-b/project-four (ID: 104)
...
This script provides a comprehensive list of all subgroups and projects within the specified group, meeting your requirements using the python-gitlab library.