Using Google Cloud APIs and Oauth2, I am trying to list down projects and display IAM Policies for each project using my Python Desktop app. Sample code is below:
appflow = flow.InstalledAppFlow.from_client_secrets_file("client_secrets.json",
scopes=["https://www.googleapis.com/auth/cloud-platform"])
appflow.run_console()
credentials = appflow.credentials
service = googleapiclient.discovery.build(
'cloudresourcemanager', 'v1', credentials=credentials)
operation1 = service.projects().list().execute()
jason=json.dumps(
operation1,
sort_keys=True,
indent=3)
data = json.loads(jason)
#Gets the list of projects in a Python List object [Proj]
proj=[]
for mem in data['projects']:
print(mem['projectId'])
proj.append(mem['projectId'])
for prj in proj:
resource = 'projects/' prj
response1 = service.projects().testIamPermissions(resource=resource, body=None, x__xgafv=None).execute()
response2 = service.projects().listOrgPolicies(resource=resource, body=None, x__xgafv=None).execute()
response3 = service.projects().getIamPolicy(resource=resource, body=None, x__xgafv=None).execute()
I get the similar error for all the 3 calls: googleapiclient.errors.HttpError: <HttpError 400 when requesting https://cloudresourcemanager.googleapis.com/v1/projects/projects/project-name:testIamPermissions?alt=json returned "Request contains an invalid argument.". Details: "Request contains an invalid argument.">
Arguments appear to be correct. Does the service(cloudresourcemanager) version v1/v3 make a difference? Am I missing something? Thanks in Advance.
CodePudding user response:
I think you should not need to parse the resource with projects/
like the HTTPS example because you are using the library that should be abstract this for you, so if you remove resource = 'projects/' prj
and try the call directly with the project id instead
response1 = service.projects().testIamPermissions(resource=prj, body=None, x__xgafv=None).execute()
response2 = service.projects().listOrgPolicies(resource=prj, body=None, x__xgafv=None).execute()
response3 = service.projects().getIamPolicy(resource=prj, body=None, x__xgafv=None).execute()
If it worked, you should no longer get error 400, but rather 403 "permission denied" because you are missing some of the scopes for those API calls(based on your code example).
The example google provided