调用ProjectsClient.list_projects遇InvalidArgument错误求排查
问题描述
尝试使用Google Cloud Resource Manager API列出项目,代码如下:
from google.cloud import resourcemanager from google.cloud.resourcemanager import ProjectsClient from google.oauth2 import service_account path_json_file = "C:\\Users\\######\\Downloads\\dev-####-analyt-datal-svc- db.json" credentials = service_account.Credentials.from_service_account_file(path_json_file) client = resourcemanager.ProjectsClient(credentials=credentials) print(client) request = resourcemanager.ListProjectsRequest( parent="###-amea-fldr/###-amea-analytics-fldr/##-amea-analytics-dev-fldr", ) page_result = client.list_projects(request=request) print(page_result)
采用服务账号认证,账号已拥有resourcemanager.projects.list权限,但调用时出现错误:
raise _InactiveRpcError(state) grpc._channel._InactiveRpcError: <_InactiveRpcError of RPC that terminated with: status = StatusCode.INVALID_ARGUMENT details = "Request contains an invalid argument." debug_error_string = "{\"created\":\"@1658894641.118000000\",\"description\":\"Error received from peer ipv6:[2404:6800:4007:809::200a]:443\",\"file\":\"src/core/lib/surface/call.cc\",\"file_line\":967,\"grpc_message\":\"Request contains an invalid argument.\",\"grpc_status\":3}"
请问该错误是否因parent参数值错误导致?调用list_projects的方式是否正确?
问题解答
parent参数格式错误是直接触发错误的原因
Google Cloud Resource Manager API要求parent参数必须使用资源完整层级ID格式,即folders/{folder_id}或者organizations/{org_id},不能直接用文件夹名称拼接的路径字符串。你当前传入的内容不符合API的参数规范,所以抛出了INVALID_ARGUMENT错误。调用list_projects的方式需要调整
正确的调用逻辑如下:
- 修正
parent参数格式:如果目标是最底层的文件夹,直接填写folders/[你的文件夹ID],比如把parent改为folders/##-amea-analytics-dev-fldr。 - 遍历分页结果:
list_projects返回的是分页对象,直接打印只能得到实例信息,需要循环遍历才能获取实际的项目数据。
调整后的示例代码:
from google.cloud import resourcemanager from google.oauth2 import service_account path_json_file = "C:\\Users\\######\\Downloads\\dev-####-analyt-datal-svc- db.json" credentials = service_account.Credentials.from_service_account_file(path_json_file) client = resourcemanager.ProjectsClient(credentials=credentials) # 使用正确的parent格式:folders/文件夹ID request = resourcemanager.ListProjectsRequest( parent="folders/##-amea-analytics-dev-fldr", ) # 遍历分页结果获取项目详情 page_result = client.list_projects(request=request) for project in page_result: print(f"项目ID: {project.project_id}, 项目名称: {project.name}, 显示名称: {project.display_name}")
额外需要确认的点:
- 服务账号的
resourcemanager.projects.list权限是否覆盖了你指定的父文件夹层级,确保账号对该文件夹及下属项目有访问权限。 - 文件夹ID是否正确,可在Google Cloud控制台的文件夹详情页查看对应的ID值。
内容的提问来源于stack exchange,提问作者Ramya Vindhisha
相关产品推荐
相关产品推荐

