pythongoogle-cloud-platformgcloudgoogle-cloud-resource-manager

google-cloud-resource-manage list projects 403 The caller does not have permission


I created a GCP service account and assigned the needed permissions for listing the projects inside the organization. When I'm using the gcloud cli, everything works:

gcloud auth activate-service-account --key-file=./key.json
gcloud projects list

# -> List of all projects

But when I try the "same" with the Python Client for Google Cloud Resource Manager, I receive a 403 The caller does not have permission error message.

# pip install google-cloud-resource-manager==1.4.1
from google.oauth2 import service_account
from google.cloud import resourcemanager_v3

# Load gcp credentials
credentials = service_account.Credentials.from_service_account_file('./key.json')

# Create resourcemanager_v3 ProjectsClient
resourcemanager_v3_projects_client = resourcemanager_v3.ProjectsClient(credentials=credentials)

# Initialize request argument(s)
list_projects_request = resourcemanager_v3.ListProjectsRequest(show_deleted=False, parent='')

# Make the request
page_result = resourcemanager_v3_projects_client.list_projects(request=list_projects_request)


# -> Error...
# -> grpc_helpers.py", line 68, in error_remapped_callable
# -> raise exceptions.from_grpc_error(exc) from exc
# -> google.api_core.exceptions.PermissionDenied: 403 The caller does not have permission

Does the Python Client for Google Cloud Resource Manager needs some other permission than the gcloud cli or do I miss something inside the Python code?


Solution

  • Seems I missed the parent parameter...
    The following snipped should list the projects of a specific folder or organization.

    # pip install google-cloud-resource-manager==1.4.1
    from google.oauth2 import service_account
    from google.cloud import resourcemanager_v3
    
    # Load gcp credentials
    credentials = service_account.Credentials.from_service_account_file('./key.json')
    
    # Create resourcemanager_v3 ProjectsClient
    resourcemanager_v3_projects_client = resourcemanager_v3.ProjectsClient(credentials=credentials)
    
    # Initialize request argument(s)
    list_projects_request = resourcemanager_v3.ListProjectsRequest(show_deleted=False, parent='folders/%folder-id%') # for organization: 'organizations/%organization-id%'
    
    # Make the request
    page_result = resourcemanager_v3_projects_client.list_projects(request=list_projects_request)
    
    # Handle the response
    for response in page_result:
        print(response)