Permalink
Cannot retrieve contributors at this time
Name already in use
A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
gcp-gce-project-audit-bq/get_folders_native.py
Go to fileThis commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
81 lines (59 sloc)
2.27 KB
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import json | |
import base64 | |
import google.auth | |
from google.cloud import resourcemanager_v3 | |
from settings import ORGANIZATION_ID | |
credentials, project_id = google.auth.default() | |
def get_reverse_path(folder_id, path): | |
displayName = folders[folder_id]['folder'].display_name | |
parent = folders[folder_id]['folder'].parent | |
parts = parent.split('/') | |
type = parts[0] | |
parent_id = parts[1] | |
if type == 'folders': | |
return get_reverse_path(folder_id=parent_id, | |
path=(path + '/' + displayName)) | |
else: | |
return path + '/' + displayName | |
return parent_id | |
def get_proper_path(reverse_path): | |
parts = reverse_path.split('/') | |
parts.reverse() | |
path = '' | |
for part in parts: | |
if part: | |
path = path + '/' + part | |
return path | |
def get_path(folder_id): | |
displayName = folders[folder_id]['folder'].display_name | |
parent = folders[folder_id]['folder'].parent | |
parts = parent.split('/') | |
type = parts[0] | |
parent_id = parts[1] | |
if type != 'folders': | |
return '/' + displayName | |
parent_path = folders[parent_id]['path'] | |
if parent_path: | |
return parent_path + '/' + displayName | |
reverse_path = get_reverse_path(folder_id=folder_id, path='') | |
return get_proper_path(reverse_path=reverse_path) | |
def get_folders(folder_id, type_flag='folder'): | |
client = resourcemanager_v3.FoldersClient(credentials=credentials) | |
if (type_flag == 'organization'): | |
folder_list=client.list_folders(parent=f'organizations/{folder_id}').folders | |
else: | |
folder_list=client.list_folders(parent=f'folders/{folder_id}').folders | |
for folder in folder_list: | |
name = folder.name | |
id = name.split('/')[1] | |
policy = client.get_iam_policy(resource = name) | |
folders[id] = {'folder': folder, 'perm': policy} | |
get_folders(folder_id=id) | |
return folders | |
def add_paths(): | |
for folder_id in folders: | |
#reverse_path = get_reverse_path(folder_id=folder_id, path='') | |
folders[folder_id]['path'] = get_path(folder_id=folder_id) | |
folders = {} | |
folders = get_folders(folder_id=ORGANIZATION_ID, type_flag="organization") | |
add_paths() |